Friday, 10 March 2023

Jackson: sort list of objects (JsonNode, ArrayNode)

Suppose, I have employee details like below

 

emps.json

{
	"emps" : [
		{
			"id" : 1,
			"name" : "Krishna",
			"age" : 34
		},
		{
			"id" : 2,
			"name" : "Gopi",
			"age" : 39
		},
		{
			"id" : 3,
			"name" : "Ram",
			"age" : 24
		},
		{
			"id" : 4,
			"name" : "Arun",
			"age" : 34
		}
	]
}

 

Sort the data by age

Step 1: Get the JsonNode from given json.

ObjectMapper objectMapper = new ObjectMapper();
String empsInfo = resourceAsString("emps.json");
JsonNode jsonNode = objectMapper.readTree(empsInfo);
JsonNode empsNode = jsonNode.get("emps");

 

Step 2: Sort the empsNode by age.

List<JsonNode> dataNodes = empsNode.findParents("age");
List<JsonNode> nodesByAge = dataNodes.stream().sorted(Comparator.comparing(o -> o.get("age").asInt())).collect(Collectors.toList());

Find the below working application.

 

App.java

package com.sample.app;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = App.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();
		}

	}

	public static void main(String[] args) throws IOException {

		ObjectMapper objectMapper = new ObjectMapper();
		String empsInfo = resourceAsString("emps.json");
		JsonNode jsonNode = objectMapper.readTree(empsInfo);

		JsonNode empsNode = jsonNode.get("emps");
		List<JsonNode> dataNodes = empsNode.findParents("age");
		List<JsonNode> nodesByAge = dataNodes.stream().sorted(Comparator.comparing(o -> o.get("age").asInt()))
				.collect(Collectors.toList());

		System.out.println("Sort by age");
		for (JsonNode emp : nodesByAge) {
			System.out.println(emp);
		}

		System.out.println("\nSort by name");
		dataNodes = empsNode.findParents("name");
		List<JsonNode> nodesByName = dataNodes.stream().sorted(Comparator.comparing(o -> o.get("name").asText()))
				.collect(Collectors.toList());

		for (JsonNode emp : nodesByName) {
			System.out.println(emp);
		}
	}

}

Output

Sort by age
{"id":3,"name":"Ram","age":24}
{"id":1,"name":"Krishna","age":34}
{"id":4,"name":"Arun","age":34}
{"id":2,"name":"Gopi","age":39}

Sort by name
{"id":4,"name":"Arun","age":34}
{"id":2,"name":"Gopi","age":39}
{"id":1,"name":"Krishna","age":34}
{"id":3,"name":"Ram","age":24}




Previous                                                 Next                                                 Home

Thursday, 9 March 2023

How to configure port and scheme for Micronaut application

Set following properties in application.yml file.

micronaut:
  server:
    port: 12345
  ssl:
    enabled: true
    keyStore:
      path: classpath:server.p12
      password: keyStorePassword
      type: PKCS12

 

Previous                                                    Next                                                    Home

PlantUML: skinparam: change color and fonts of a drawing

skinparam command can be used to change the colors and fonts for the drawing.

 

skinParam.txt

@startuml

hide footbox

skinparam sequenceArrowThickness 3
skinparam roundcorner 25
skinparam maxmessagesize 50
skinparam sequenceParticipant underline

client -> server : Submit the job
server -> database: Request the job configuration
database -> server: Send job configuration
server -> client: Send job execution status

@enduml

 

Above snippet generate below diagram.

  


Find the another example below.

 

skinParam1.txt

@startuml

hide footbox

skinparam sequenceArrowThickness 3
skinparam roundcorner 25
skinparam maxmessagesize 50
skinparam sequenceParticipant underline
skinparam arrowColor #FF0000
skinparam actorBorderColor #00FF00
skinparam lifeLineBorderColor blue
skinparam lifeLineBackgroundColor #A9DCDF
skinparam participantBorderColor #0000FF
skinparam participantBackgroundColor DodgerBlue
skinparam participantFontName Impact
skinparam participantFontSize 13
skinparam participantFontColor #A9DCDF
skinparam actorBackgroundColor aqua
skinparam actorFontColor #00FFFF
skinparam actorFontSize 13
skinparam actorFontName Aapex

client -> server : Submit the job
server -> database: Request the job configuration
database -> server: Send job configuration
server -> client: Send job execution status

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

Playwright: upload multiple files

Using 'setInputFiles' method, we can set the value of the file input.

 

Example

Path[] paths = { Paths.get(filePath1), Paths.get(filePath2) };
page.locator("#myFile").setInputFiles(paths);

 Find the below working application.

 

emp.json

{
	"id": 1,
	"name": "Krishna",
	"age": 32
}

address.json

{
	"city": "Bangalore",
	"country": "India"
}

multiFileUpload.html

<!DOCTYPE html>
<html>

<head>
	<title>File upload example</title>

	<script>
		function appendFileContent(content) {
			const node = document.createElement("p");
			const textnode = document.createTextNode(content);
			node.appendChild(textnode);
			document.getElementById("fileContent").appendChild(node);
		}
		function readFile(file) {
			const reader = new FileReader();
			reader.onload = evt => {
				appendFileContent(reader.result);
			};
			reader.readAsText(file);
		}
		function init() {
			const fileSelector = document.getElementById("myFile");
			fileSelector.addEventListener("change", event => {
				const fileList = event.target.files;
				for (const file of fileList) {
					readFile(file);
				}
			});
		}
	</script>
</head>

<body onload="init()">
	<p>Click on the "Choose File" button to upload one or files:</p>

	<input type="file" id="myFile" name="filename" multiple />

	<pre id="fileContent"></pre>
</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();
		}

	}
}

UploadMultipleFiles.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;
import java.net.URL;
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.sample.app.util.FileUtil;

public class UploadMultipleFiles {

	public static String resourceFilePath(String resourceFile) {
		ClassLoader classLoader = FileUploadDemo.class.getClassLoader();
		URL url = classLoader.getResource(resourceFile);
		return url.getPath();
	}

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

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

			String filePath1 = resourceFilePath("files" + File.separator + "emp.json");
			String filePath2 = resourceFilePath("files" + File.separator + "address.json");
			Path[] paths = { Paths.get(filePath1), Paths.get(filePath2) };
			page.locator("#myFile").setInputFiles(paths);

			String text = page.locator("#fileContent").textContent();
			System.out.println("files content : \n" + text);

		}
	}
}

Output

file content : 
{
	"id": 1,
	"name": "Krishna",
	"age": 32
}{
	"city": "Bangalore",
	"country": "India"
}

 


 

 

Previous                                                 Next                                                 Home

Wednesday, 8 March 2023

Playwright: upload a file

Using 'setInputFiles' method, we can set the value of the file input.

 

Example

String filePath = resourceFilePath("files" + File.separator + "emp.json");
page.locator("#myFile").setInputFiles(Paths.get(filePath));

Find the below working application.

 

emp.json

{
	"id": 1,
	"name": "Krishna",
	"age": 32
}

fileUpload.html

<!DOCTYPE html>
<html>

<head>
	<title>File upload example</title>

	<script>
		function init() {
			document.getElementById('myFile').addEventListener('change', handleFileSelect, false);
		}

		function handleFileSelect(event) {
			const reader = new FileReader()
			reader.onload = handleFileLoad;
			reader.readAsText(event.target.files[0])
		}

		function handleFileLoad(event) {
			console.log(event);
			document.getElementById('fileContent').textContent = event.target.result;
		}
	</script>
</head>

<body onload="init()">

	<p>Click on the "Choose File" button to upload a file:</p>


	<input type="file" id="myFile" name="filename">


	<pre id="fileContent"></pre>

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

	}
}

FileUploadDemo.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;
import java.net.URL;
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.sample.app.util.FileUtil;

public class FileUploadDemo {

	public static String resourceFilePath(String resourceFile) {
		ClassLoader classLoader = FileUploadDemo.class.getClassLoader();
		URL url = classLoader.getResource(resourceFile);
		return url.getPath();
	}

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

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

			String filePath = resourceFilePath("files" + File.separator + "emp.json");
			page.locator("#myFile").setInputFiles(Paths.get(filePath));

			String text = page.locator("#fileContent").textContent();
			System.out.println("file content : \n" + text);

		}
	}
}

Output

file content : 
{
	"id": 1,
	"name": "Krishna",
	"age": 32
}

 

Previous                                                 Next                                                 Home

PlantUML: Add a spotted character in a coloured circle in stereotype

You can add a a spotted character in a colored circle in stereotype using the syntax (X,color).

 

spottedCharStereotype.txt

@startuml

participant clientStub << (C,#00FFFF) Generated>>
participant server << (T,#FFFF00) Tested>>

clientStub -> server : Send request
server -> clientStub : Send response

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

How to configure log level of Micronaut application?

Set logger.levels property in application.yml file.

 

Example

logger:
  levels:
    io.netty: ERROR
    io.micronaut: ERROR

 

Previous                                                    Next                                                    Home