Wednesday, 5 July 2023

Micronaut: Bind HTTP header to a method parameter

@Header annotation can be applied to method argument to indicate that the method argument is bound from an HTTP header.

 

Example

@Get(value = "/headers", produces = MediaType.TEXT_PLAIN)
public String printHeaders(@Header("Content-Type") String contentType, @Header("secret-key") String secretKey) {

	final StringBuilder builder = new StringBuilder();
	builder.append("contentType").append("=").append(contentType);
	builder.append("\n");
	builder.append("secretKey").append("=").append(secretKey);

	return builder.toString();
}

Find the below working application.

 

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

 

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-header</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 io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;

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

	@Get(value = "/headers", produces = MediaType.TEXT_PLAIN)
	public String printHeaders(@Header("Content-Type") String contentType, @Header("secret-key") String secretKey) {

		final StringBuilder builder = new StringBuilder();
		builder.append("contentType").append("=").append(contentType);
		builder.append("\n");
		builder.append("secretKey").append("=").append(secretKey);

		return builder.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-header-0.1.jar’ in project target folder.

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

 

Execute below command to run the application.

java -jar ./target/micronaut-rest-bind-request-header-0.1.jar

 

Execute below command to check the api functionality.

curl --location --request GET 'http://localhost:8080/hello/headers' \
--header 'Content-Type: application/json' \
--header 'secret-key: sec1234567'

$curl --location --request GET 'http://localhost:8080/hello/headers' \
--header 'Content-Type: application/json' \
--header 'secret-key: sec1234567'
contentType=application/json
secretKey=sec1234567

 

You can download this application from this link.


 

Previous                                                    Next                                                    Home

Micronaut: @CookieValue: bind a cookie value to method argument

 @CookieValue annotaiton can be applied to method argument to indicate that the method argument is bound from an HTTP cookie.

 

Example

@Get(value = "/cookies", produces = MediaType.TEXT_PLAIN)
public String printCookies(@CookieValue(value = "myCookie", defaultValue = "no cookie found") String cookie) {
	return cookie;
}

 

Above snippet bind the cookie value associated with the cookie myCookie to the method argument cookie.

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-rest-bind-cookie’.

 

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-cookie</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 io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.CookieValue;
import io.micronaut.http.annotation.Get;

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

	@Get(value = "/cookies", produces = MediaType.TEXT_PLAIN)
	public String printCookies(@CookieValue(value = "myCookie", defaultValue = "no cookie found") String cookie) {
		return cookie;
	}
}

 

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-cookie-0.1.jar’ in project target folder.

 

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

 

Execute below command to run the application.

java -jar ./target/micronaut-rest-bind-cookie-0.1.jar

Execute below command to get the value associated with the cookie ‘myCookie’. 

curl --cookie "myCookie=demo1,3,krishna" --request GET http://localhost:8080/hello/cookies   
$curl --cookie "myCookie=demo1,3,krishna" --request GET http://localhost:8080/hello/cookies   
demo1,3,krishna

 You can download the application from this link.


 

Previous                                                    Next                                                    Home

Tuesday, 4 July 2023

PlantUML: add notes on a link in class diagram

Following keywords are used to add notes on a link.

 

a.   note on link

b.   note left on link

c.    note right on link

d.   note top on link

e.   note bottom on link

 

Use above keywords just after the link definition.

 

Example

List <|.. AbstractList 
note on link #red: note that is red color

AbstractList <|-- ArrayList
note left on link #00FF00 
	note that is green color
end note

 

noteOnLinks.txt

@startuml

class List
class AbstractList
class ArrayList
class LinkedList
class Serializable

List <|.. AbstractList 
note on link #red: note that is red color

AbstractList <|-- ArrayList
note left on link #00FF00 
	note that is green color
end note

AbstractList <|-- LinkedList
note right on link #gold 
	note that is gold color
end note

Serializable <|.. ArrayList
note top on link #lightblue  
	note that is lightblue color
end note

Serializable <|.. LinkedList
note bottom on link #aqua  
	note that is aqua color
end note

@enduml

 Above snippet generate below diagram.



 

 

Previous                                                    Next                                                    Home

Playwright: How to configure base url?

We can set the baseurl using NewContextOptions.

 

Example

new Browser.NewContextOptions().setBaseURL("https://self-learning-java-tutorial.blogspot.com");

 

Find the below working application.

 

SetBaseURL.java

package com.sample.app.miscellaneous;

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

public class SetBaseURL {

	public static void main(String[] args) throws InterruptedException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			NewContextOptions newContextOptions = new Browser.NewContextOptions()
					.setBaseURL("https://self-learning-java-tutorial.blogspot.com");
			BrowserContext browserContext = browser.newContext(newContextOptions);

			Page page = browserContext.newPage();
			page.navigate("2014/01/data-types-in-java_31.html");
			System.out.println("title : " + page.title());
			
			page.navigate("2014/01/running-simple-hello-world-applcation.html");
			System.out.println("title : " + page.title());
		}
	}
}

 

Output

title : Programming for beginners: Data Types in Java
title : Programming for beginners: Running Simple Hello World Applcation in Java

 

 

Previous                                                 Next                                                 Home

Playwright: ignore https or ssl errors

Below snippet ignore https errors.

 

NewContextOptions newContextOptions = new Browser.NewContextOptions().setIgnoreHTTPSErrors(true);

 

Find the below working application.


IgnoreSSLErrors.java

package com.sample.app.miscellaneous;

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

public class IgnoreSSLErrors {

	public static void main(String[] args) throws InterruptedException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100));

			NewContextOptions newContextOptions = new Browser.NewContextOptions().setIgnoreHTTPSErrors(true);
			BrowserContext browserContext = browser.newContext(newContextOptions);

			Page page = browserContext.newPage();
			page.navigate("https://self-learning-java-tutorial.blogspot.com/2014/07/basic-java.html");
		}
	}
}

 

Previous                                                 Next                                                 Home

Sunday, 2 July 2023

Playwright: launch installed chrome browser

By setting the channel to 'chrome', we can launch the page in local chrome browser.

 

Example

playwright
.chromium()
.launch(new BrowserType
			.LaunchOptions()
			.setHeadless(false)
			.setSlowMo(100)
			.setChannel("chrome"));

 

Following are the supported values for the channel.

 

chrome, chrome-beta, chrome-dev, chrome-canary, msedge, msedge-beta, msedge-dev, msedge-canary

 

a.   chrome,

b.   chrome-beta,

c.    chrome-dev,

d.   chrome-canary,

e.   msedge,

f.     msedge-beta,

g.   msedge-dev,

h.   msedge-canary

 

Find the below working application.

 

LaunchChromeBrowser.java

package com.sample.app.miscellaneous;

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

public class LaunchChromeBrowser {

	public static void main(String[] args) throws InterruptedException {
		try (Playwright playwright = Playwright.create()) {
			Browser browser = playwright.chromium()
					.launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(100).setChannel("chrome"));
			Page page = browser.newPage();
			page.navigate("https://self-learning-java-tutorial.blogspot.com/2014/07/basic-java.html");
		}
	}

}

 

 

Previous                                                 Next                                                 Home