Sunday, 9 July 2023

Micronaut: @QueryValue: bind the request query parameter to a method argument

@QueryValue annotation bound the query parameter to a method argument.

 

Example

@Get(value = "/even-numbers", produces = MediaType.TEXT_PLAIN)
public String evenNumbers(@Nullable @QueryValue("from") Integer from, @Nullable @QueryValue("to") Integer to) {

	if (from == null || from < 0) {
		from = 0;
	}

	if (to == null || to < 0) {
		to = from + 10;
	}

	final StringJoiner stringJoiner = new StringJoiner(",");

	for (int i = from; i < to; i += 2) {
		stringJoiner.add("" + i);
	}

	return stringJoiner.toString();
}

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-rest-bind-request-query-param’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-rest-bind-request-query-param</artifactId>
	<version>0.1</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>io.micronaut</groupId>
		<artifactId>micronaut-parent</artifactId>
		<version>3.7.4</version>
	</parent>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>11</jdk.version>
		<release.version>11</release.version>
		<micronaut.version>3.7.3</micronaut.version>
		<micronaut.runtime>netty</micronaut.runtime>
		<exec.mainClass>com.sample.app.App</exec.mainClass>
	</properties>

	<repositories>
		<repository>
			<id>central</id>
			<url>https://repo.maven.apache.org/maven2</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-validation</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-client</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-server-netty</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-jackson-databind</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>jakarta.annotation</groupId>
			<artifactId>jakarta.annotation-api</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut.test</groupId>
			<artifactId>micronaut-test-junit5</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>io.micronaut.build</groupId>
				<artifactId>micronaut-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<!-- Uncomment to enable incremental compilation -->
					<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->

					<annotationProcessorPaths
						combine.children="append">
						<path>
							<groupId>io.micronaut</groupId>
							<artifactId>micronaut-http-validation</artifactId>
							<version>${micronaut.version}</version>
						</path>
					</annotationProcessorPaths>

				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

 

Step 3: Define HelloController class.

 

HelloController.java

package com.sample.app.controller;

import java.util.StringJoiner;

import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;

@Controller("/hello")
public class HelloController {

	@Get(value = "/even-numbers", produces = MediaType.TEXT_PLAIN)
	public String evenNumbers(@Nullable @QueryValue("from") Integer from, @Nullable @QueryValue("to") Integer to) {

		if (from == null || from < 0) {
			from = 0;
		}

		if (to == null || to < 0) {
			to = from + 10;
		}

		final StringJoiner stringJoiner = new StringJoiner(",");

		for (int i = from; i < to; i += 2) {
			stringJoiner.add("" + i);
		}

		return stringJoiner.toString();
	}
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import io.micronaut.runtime.Micronaut;

public class App {

	public static void main(String[] args) {
		Micronaut.run(App.class);

		// Use this if you want the beans to be initialized eagerly
		/*
		 * Micronaut.build(args) .eagerInitSingletons(true) .mainClass(App.class)
		 * .start();
		 */
	}
}

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-rest-bind-request-query-param-0.1.jar’ in project target folder.

$ls ./target/
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-rest-bind-request-query-param-0.1.jar
original-micronaut-rest-bind-request-query-param-0.1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-rest-bind-request-query-param-0.1.jar

 

Run below command to test the application.

curl --location --request GET 'http://localhost:8080/hello/even-numbers/?from=2&to=20'

$curl --location --request GET 'http://localhost:8080/hello/even-numbers/?from=2&to=20'
2,4,6,8,10,12,14,16,18

You can download this application from this link.


Previous                                                    Next                                                    Home

PlantUML: Define an enum in a class diagram

‘enum’ keyword defines an enum.

 

Example

enum TimeUnit {
	DAYS
	HOURS
	MINUTES
}

 

enum.txt

@startuml

interface List{
	+ int size()
	+ void clear()
}

abstract class AbstractList{
	# int modCount	
}
class ArrayList
class LinkedList
class Serializable

enum TimeUnit {
	DAYS
	HOURS
	MINUTES
}

List <|.. AbstractList 
AbstractList <|-- ArrayList
AbstractList <|-- LinkedList
Serializable <|.. ArrayList
Serializable <|.. LinkedList

@enduml

 

Above snippet generate below diagram.


  

Previous                                                    Next                                                    Home

PlantUML: Define interface in a class diagram

‘interface’ keyword define an interface.

 

Example

interface List{
	+ int size()
	+ void clear()
}

 

Find the below working application.

 

interface.txt

@startuml

interface List{
	+ int size()
	+ void clear()
}

abstract class AbstractList{
	# int modCount	
}
class ArrayList
class LinkedList
class Serializable

enum TimeUnit {
	DAYS
	HOURS
	MINUTES
}

List <|.. AbstractList 
AbstractList <|-- ArrayList
AbstractList <|-- LinkedList
Serializable <|.. ArrayList
Serializable <|.. LinkedList

@enduml

 

Above snippet generate below diagram.

 


 

  

Previous                                                    Next                                                    Home

Playwright: Download a file using playwright

Using ‘Response.body()’ method, we can get the buffer associated with the response body.

 

Example

Page page = browser.newPage();
String url = "https://github.com/harikrishna553/java-libs/raw/master/plantUMLExamples/activityDiagrams/backward.png";
Response response = page.navigate(url);
byte[] body = response.body();

 

Find the below working application.

 

DownloadFile.java

 

package com.sample.app.miscellaneous;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.Response;

public class DownloadFile {

	public static boolean writeContent(byte[] content, String filePath) {
		if (filePath == null || content == null) {
			throw new IllegalArgumentException("filePath and content must not be null");
		}

		Path file = Paths.get(filePath);
		try {
			Files.write(file, content);
		} catch (IOException e) {
			return false;
		}

		return true;

	}

	public static void main(String[] args) {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));
			Page page = browser.newPage();
			String url = "https://github.com/harikrishna553/java-libs/raw/master/plantUMLExamples/activityDiagrams/backward.png";
			Response response = page.navigate(url);

			// response.finished();
			byte[] body = response.body();
			String filePath = "/Users/Shared/playwright/backward.png";
			writeContent(body, filePath);

		}
	}

}

 

Above snippet download backward.png file to the location "/Users/Shared/playwright/backward.png”.

 

backward.png


 

 

 

Previous                                                 Next                                                 Home

Playwright: How to add custom headers?

Using 'page.setExtraHTTPHeaders()' method, we can set the extra HTTP headers, these will be sent with every request the page initiates.

 

Example

Map<String, String> headers = new HashMap<>();
headers.put("header1", "value1");
headers.put("header2", "value2");
headers.put("header3", "value3");

page.setExtraHTTPHeaders(headers);

Find the below working application.

 

CustomHeaders.java

package com.sample.app.miscellaneous;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

public class CustomHeaders {

	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));
			Page page = browser.newPage();

			Map<String, String> headers = new HashMap<>();
			headers.put("header1", "value1");
			headers.put("header2", "value2");
			headers.put("header3", "value3");

			page.setExtraHTTPHeaders(headers);
			page.navigate("https://self-learning-java-tutorial.blogspot.com/");

		}
	}

}





 

 

Previous                                                 Next                                                 Home

Wednesday, 5 July 2023

Playwright: Open a page in new tab

Using the keyboard modifier 'META', we can open the url in a new tab.

 

Example

List<KeyboardModifier> modifiers = Arrays.asList(KeyboardModifier.META);
clickOptions.setModifiers(modifiers);
page.locator("a#java").click(clickOptions);

Find the below working application.

 

openInNewTab.html

<!DOCTYPE html>
<html>

<head>
	<title>Hello World</title>
</head>

<body>

	<form onsubmit="return false;">

		<table>
			<tr>
				<td>
					<p>Java</p>
				</td>
				<td> <a href="https://self-learning-java-tutorial.blogspot.com/" id="java">Java tutorial</a> </td>
			</tr>

			<tr>
				<td>
					<p>Playwright</p>
				</td>
				<td> <a href="https://playwright.dev/" id="playwright">Playwright tutorial</a> </td>
			</tr>


		</table>

	</form>


</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();
		}

	}
}

OpenInNewTab.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Locator.ClickOptions;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.KeyboardModifier;
import com.sample.app.util.FileUtil;

public class OpenInNewTab {

	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 + "openInNewTab.html");

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

			ClickOptions clickOptions = new ClickOptions();

			List<KeyboardModifier> modifiers = Arrays.asList(KeyboardModifier.META);
			clickOptions.setModifiers(modifiers);
			page.locator("a#java").click(clickOptions);
			page.locator("a#playwright").click(clickOptions);

			page.waitForTimeout(8000);

			// Get all the opened pages in the context
			List<Page> pages = page.context().pages();
			for (Page tempPage : pages) {
				System.out.println(tempPage.title());
			}

		}
	}

}

Output

Hello World
Fast and reliable end-to-end testing for modern web apps | Playwright
Programming for beginners




Previous                                                 Next                                                 Home

PlantUML: Define abstract class

‘abstract’ keyword is used to define abstract class.

 

Example

abstract class AbstractList{
	# int modCount	
}

 

abstractClass.txt

@startuml

interface List{
	+ int size()
	+ void clear()
}

abstract class AbstractList{
	# int modCount	
}
class ArrayList
class LinkedList
class Serializable

enum TimeUnit {
	DAYS
	HOURS
	MINUTES
}

List <|.. AbstractList 
AbstractList <|-- ArrayList
AbstractList <|-- LinkedList
Serializable <|.. ArrayList
Serializable <|.. LinkedList

@enduml

 

Above snippet generate below diagram.



 


Previous                                                    Next                                                    Home