Saturday, 15 July 2023

Micronaut: Upload a file as InputStream

We can bind the request body to a InputStream using @Body annotation.

 

Example

@Post(value = "/read", processes = MediaType.TEXT_PLAIN)
@ExecuteOn(TaskExecutors.IO)
String read(@Body InputStream inputStream) throws IOException { 
	return IOUtils.readText(new BufferedReader(new InputStreamReader(inputStream)));
}

 

Find the below working applcation.

 

Step 1: Create new maven project ‘micronaut-read-input-stream’.

 

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-read-input-stream</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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import io.micronaut.core.io.IOUtils;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
import io.micronaut.scheduling.TaskExecutors;
import io.micronaut.scheduling.annotation.ExecuteOn;

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

	@Post(value = "/read", processes = MediaType.TEXT_PLAIN)
	@ExecuteOn(TaskExecutors.IO)
	String read(@Body InputStream inputStream) throws IOException { 
		return IOUtils.readText(new BufferedReader(new InputStreamReader(inputStream)));
	}
}

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

 

$ls ./target/
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-read-input-stream-0.1.jar
original-micronaut-read-input-stream-0.1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-read-input-stream-0.1.jar

 

Execute below command to read demo.txt file content.

curl --location --request POST 'http://localhost:8080/hello/read' \
--header 'Content-Type: text/plain' \
--data-binary '@/Users/Shared/demo.txt'

$curl --location --request POST 'http://localhost:8080/hello/read' \
--header 'Content-Type: text/plain' \
--data-binary '@/Users/Shared/demo.txt'
hello
hi
how are
you

You can download this application from this link.


 

Previous                                                    Next                                                    Home

PlantUML: hide and show members in class diagram

diagram1.txt

@startuml

class Employee{
	int id
	String name
	int age

	String aboutMe()
}

class Manager{
	int noOfReportees
}

Employee <|-- Manager

@enduml

Above snippet generate below diagram.

 


How to hide members (fields, methods) in the class diagram?

Using the keyword ‘hide members’, we can hide the members of class diagram.

 

hideMembers.txt

@startuml

hide members

class Employee{
	int id
	String name
	int age

	String aboutMe()
}

class Manager{
	int noOfReportees
}

Employee <|-- Manager

@enduml

Above snippet generate below diagram.


 


 

How to show specific entity members, fields?

show Class methods

show Class fields

 

For example, below snippet show Manager class fields and Employee class methods

 

show Manager fields

show Employee methods

 

 

showMembers.txt

@startuml

hide members

class Employee{
	int id
	String name
	int age

	String aboutMe()
}

class Manager{
	int noOfReportees
}

Employee <|-- Manager

' Show Manager field and Employee methods
show Manager fields
show Employee methods

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

Playwright: get all the styles associated with an element

Using evaluate method and ‘getComputedStyle’ we can get all the styles associated with an element.

 

Example

Locator locator1 = page.locator("#para1");
Map<String, Object> styles1 = (Map<String, Object>) locator1.evaluate("locator => getComputedStyle(locator)");

 

Find the below working application.

 

stylesOfElement.html

 

<html>

<head>
	<title>
		Styles of element
	</title>

	<style>
		p#para1 {
			width: 450px;
			margin: 0 auto;
			padding: 25px;
			font: 2rem/2 sans-serif;
			text-align: center;
			background: rgb(114, 123, 27);
			color: white;
		}

		p#para2 {
			width: 550px;
			margin: 0 auto;
			padding: 35px;
			font: 3rem/3 sans-serif;
			text-align: center;
			background: rgb(122, 51, 114);
			color: white;
		}
	</style>
</head>

<p id="para1">Hello World!!!!</p>
<p id="para2">Hello World!!!!</p>

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

	}
}

 

GetAllStylesOfElement.java

package com.sample.app.miscellaneous;

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

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

public class GetAllStylesOfElement {
	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 + "stylesOfElement.html");

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

			Locator locator1 = page.locator("#para1");
			Map<String, Object> styles1 = (Map<String, Object>) locator1
					.evaluate("locator => getComputedStyle(locator)");

			Locator locator2 = page.locator("#para2");
			Map<String, Object> styles2 = (Map<String, Object>) locator2
					.evaluate("locator => getComputedStyle(locator)");

			System.out.println("Styles associated with the id para1 are : ");
			System.out.println("width : " + styles1.get("width"));
			System.out.println("margin : " + styles1.get("margin"));
			System.out.println("padding : " + styles1.get("padding"));
			System.out.println("font : " + styles1.get("font"));
			System.out.println("text-align : " + styles1.get("textAlign"));
			System.out.println("background : " + styles1.get("background"));
			System.out.println("color : " + styles1.get("color"));

			System.out.println("\n\nStyles associated with the id para2 are : ");
			System.out.println("width : " + styles2.get("width"));
			System.out.println("margin : " + styles2.get("margin"));
			System.out.println("padding : " + styles2.get("padding"));
			System.out.println("font : " + styles2.get("font"));
			System.out.println("text-align : " + styles2.get("textAlign"));
			System.out.println("background : " + styles2.get("background"));
			System.out.println("color : " + styles2.get("color"));
		}
	}
}

 

Output

Styles associated with the id para1 are : 
width : 450px
margin : 0px 382px
padding : 25px
font : 32px / 64px sans-serif
text-align : center
background : rgb(114, 123, 27) none repeat scroll 0% 0% / auto padding-box border-box
color : rgb(255, 255, 255)


Styles associated with the id para2 are : 
width : 550px
margin : 0px 322px
padding : 35px
font : 48px / 144px sans-serif
text-align : center
background : rgb(122, 51, 114) none repeat scroll 0% 0% / auto padding-box border-box
color : rgb(255, 255, 255)

 


 

Previous                                                 Next                                                 Home

Thursday, 13 July 2023

Playwright: Get elements relative to an ElementHandle

Using ElementHandle, we can get the parent, grandparent, siblings, childs etc.,

 

Example

ElementHandle elementHandle = page.querySelector("#para1");
ElementHandle grandParent = elementHandle.querySelector("xpath=../..");
List<ElementHandle> siblings = elementHandle.querySelectorAll("xpath=following-sibling::*");

 

Find the below working application.

 

relativeElements.html

<html id="html">

<head id="head">
	<title id="title">Relative Elements</title>
	</headname="title">

<body>
	<p id="para1">Paragraph1</p>

	<p id="para2">Paragraph2</p>

	<p id="para3">Paragraph3</p>
</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();
		}

	}
}

ElementsRelativeToThisElement.java

package com.sample.app.miscellaneous;

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

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

public class ElementsRelativeToThisElement {

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

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

			ElementHandle elementHandle = page.querySelector("#para1");
			ElementHandle grandParent = elementHandle.querySelector("xpath=../..");
			List<ElementHandle> siblings = elementHandle.querySelectorAll("xpath=following-sibling::*");

			System.out.println("elementHandle : " + elementHandle.getAttribute("id"));
			System.out.println("grandParent : " + grandParent.getAttribute("id"));

			System.out.println("Siblings");
			for (ElementHandle sibling : siblings) {
				System.out.println("\t" + sibling.getAttribute("id"));
			}

		}
	}

}

Output

elementHandle : para1
grandParent : html
Siblings
	para2
	para3

  

Previous                                                 Next                                                 Home

PlantUML: How to use non letters in class name?

By putting quotes " around the class name, we can define a class name with non-letter characters.

 

nonLetterClass.txt

@startuml

class "My new class 1" as CLS1
abstract class "My new abstract class 1" as CLS2
interface "My new interface 1" as INTF1
enum "My enum 1" as ENUM1

INTF1 <|.. CLS2
CLS2 <|-- CLS1

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home