Wednesday, 22 February 2023

Micronaut: Validate data classes using @Valid annotation

In this post, I am going to explain how to use javax.validation.Valid to trigger cascading validation on data classes or POJOs.

 

Step 1: Define data class and make sure that it is annotated with @Introspected annotation.

@Introspected
public class Employee {

	@Positive
	private int id;
	
	@NotBlank
	private String name;
	
	@Min(18)
	private int age;

	...........
	...........
}

  Step 2: Use @Valid annotation on bean methods to trigger cascading validation.

@Singleton
public class EmployeeService {

	public void registerEmployee(@Valid Employee employee) {
		System.out.println("Employee registered successfully " + employee);
	}
}

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-valid-annotaiton-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-valid-annotaiton-demo</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.3</micronaut.version>
		<slf4j.version>2.0.3</slf4j.version>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>

		<maven.compiler.target>15</maven.compiler.target>
		<maven.compiler.source>15</maven.compiler.source>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject-java</artifactId>
			<version>${micronaut.version}</version>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-runtime</artifactId>
			<version>${micronaut.version}</version>
		</dependency>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-validation</artifactId>
			<version>${micronaut.version}</version>
		</dependency>


		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>

				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

 

Step 3: Define Employee model class.

 

Employee.java

 

package com.sample.app.model;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;

import io.micronaut.core.annotation.Introspected;

@Introspected
public class Employee {

	@Positive
	private int id;
	
	@NotBlank
	private String name;
	
	@Min(18)
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	
}

 

Step 4: Define EmployeeService class.

 

EmployeeService.java

package com.sample.app.service;

import javax.validation.Valid;

import com.sample.app.model.Employee;

import jakarta.inject.Singleton;

@Singleton
public class EmployeeService {

	public void registerEmployee(@Valid Employee employee) {
		System.out.println("Employee registered successfully " + employee);
	}
}

 

Step 5: Define main application class.

 

App.java

 

package com.sample.app;

import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			EmployeeService employeeService = applicationContext.getBean(EmployeeService.class);
			
			Employee emp = new Employee();
			emp.setAge(5);
			emp.setId(1);
			emp.setName("Krishna");
			employeeService.registerEmployee(emp);
		}

	}
}

 

Total project structure looks like below.

 


 

Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-valid-annotaiton-demo-1-jar-with-dependencies.jar’ in project target folder.


$ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-valid-annotaiton-demo-1-jar-with-dependencies.jar
micronaut-valid-annotaiton-demo-1.jar
test-classes

 

Execute below command to run the application.

java -jar ./target/micronaut-valid-annotaiton-demo-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-valid-annotaiton-demo-1-jar-with-dependencies.jar
Exception in thread "main" javax.validation.ConstraintViolationException: registerEmployee.employee.age: must be greater than or equal to 18
	at io.micronaut.validation.ValidatingInterceptor.intercept(ValidatingInterceptor.java:111)
	at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:137)
	at com.sample.app.service.$EmployeeService$Definition$Intercepted.registerEmployee(Unknown Source)
	at com.sample.app.App.main(App.java:18)

You can download this application from this link.



 

Previous                                                    Next                                                    Home

Playwright: select multiple items from a select tag once

Using ‘page.selectOption()’ method, we can select multiple items from a select tag.

 

Example

String valuesToSelect[] = { "red", "green", "yellow" };
page.selectOption("select#favoriteColors", valuesToSelect);

 

Find the below working application.

 

multiselect.html

<html>

<body>

	<h1>Multi select demo</h1>


	<form onsubmit="return false;">
		<label for="colors">Choose a color:</label>
		<select name="colors" id="favoriteColors" multiple>
			<option value="red">Red</option>
			<option value="green">Green</option>
			<option value="yellow">Yellow</option>
			<option value="blue">blue</option>
		</select>
		<br><br>
		<input type="submit" value="Submit" onclick="display()">
	</form>

	<p id="result"></p>

	<script>
		function display() {
			let options = document.getElementById('favoriteColors').selectedOptions;
			let values = Array.from(options).map(({value}) => value);
			let selectedColors = values.join("-->");
			
			console.log(values)
			result.innerHTML = `<b>Selected colors: <br />${selectedColors}</b>`
		}
	</script>


</body>

</html>

 

FileUtil.java

package com.sample.app.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {
	
	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = FileUtil.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}
}

 

MultiSelectDemo.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.sample.app.util.FileUtil;

public class MultiSelectDemo {
	public static void main(String[] args) throws IOException {
		try (Playwright playwright = Playwright.create()) {

			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			final String content = FileUtil.resourceAsString("miscellaneous" + File.separator + "multiSelect.html");

			Page page = browser.newPage();
			page.setContent(content);

			String valuesToSelect[] = { "red", "green", "yellow" };
			page.selectOption("select#favoriteColors", valuesToSelect);
			
			page.locator("input[type=\"submit\"]").click();
			
			String textContent = page.locator("id=result").textContent();
			System.out.println(textContent);
		}
	}
}

 

Output

Selected colors: red-->green-->yellow

 

References

https://playwright.dev/docs/api/class-page#page-select-option

 

 

Previous                                                 Next                                                 Home

PlantUML: short arrows in a sequence diagram

We can specify short arrows using ?

 

shortArrows.txt

@startuml

client2 -> client1 : Hello
client1 -> A: Hello

== with short arrows ==

?-> A: Input 
activate A

A -> A: transform the data
A -> A: Apply business logic

A ->? : response to external device
deactivate A

==with out short arrows==

[-> A: Input
activate A

A -> A: transform the data
A -> A: Apply business logic

A ->] : response to external device
deactivate A

A -> B: Send response
B -> C: Send response

@enduml

Above snippet generates below diagram.

 


 

Previous                                                    Next                                                    Home

Tuesday, 21 February 2023

PlantUML: Specify incoming and outgoing messages in a sequence diagram

[-> A, [--> A : Specify incoming message to the participant A

A ->], A -->] : Specify outgoing message from the participant A

 

incomingOutgoingMsgs.txt

@startuml

[-> A: Input received
activate A

A -> A: transform the data
A -> A: Apply business logic

A ->] : Send the response to external device
deactivate A


[--> A: Input received
activate A

A -> A: transform the data
A -> A: Apply business logic

A -->] : Send the response to external device
deactivate A

@enduml

Above snippet generates below diagram.


 


 

Similarly, you can have following syntaxes too.

[o->
[o->o
[x->
[x<-
->o]
o->o]
->x]
<-]
x<-]

 

incomingOutgoingMsgs1.txt

@startuml

[o-> A: Input received
activate A

A -> A: transform the data
A -> A: Apply business logic

A o->o] : Send the response to external device
deactivate A


[x--> A: Input received
activate A

A -> A: transform the data
A -> A: Apply business logic

A x-->o] : Send the response to external device
deactivate A

@enduml

Above snippet generates below diagram.



 

 

 

 

Previous                                                    Next                                                    Home