Tuesday, 14 March 2023

Jackson: Use different property names for serialization and deserialization

In this post, I am going to explain how to use different property names for the serialization and deserialization using JsonGetter and JsonSetter annotations.

 


Example

public class Employee {

    private String firstName;

    // # Used during serialization
    @JsonGetter("fname")
    public String getFirstName() {
        return firstName;
    }

    // # Used during deserialization
    @JsonSetter("fn")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

Above snippet generate the property fname during serialization and populate the property firstName from the json property fn during deserialization.

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;

public class Employee {

    private Integer id;

    private String firstName;

    private String lastName;

    public Integer getId() {
        return id;
    }

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

    // # Used during serialization
    @JsonGetter("fname")
    public String getFirstName() {
        return firstName;
    }

    // # Used during deserialization
    @JsonSetter("fn")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    // # Used during serialization
    @JsonGetter("lname")
    public String getLastName() {
        return lastName;
    }

    // # Used during deserialization
    @JsonSetter("ln")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

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

}

JsonGetterAndSetterDemo.java

package com.sample.app;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee;

public class JsonGetterAndSetterDemo {

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        Employee emp = new Employee();
        emp.setId(1);
        emp.setFirstName("Krishna");
        emp.setLastName("Gurram");

        String json = objectMapper.writeValueAsString(emp);
        System.out.println(json);

        String jsonInput = "{\"id\":1,\"fn\":\"Krishna\",\"ln\":\"Gurram\"}";
        Employee deserializedEmp = objectMapper.readValue(jsonInput, Employee.class);
        System.out.println(deserializedEmp);
    }

}

Output

{"id":1,"fname":"Krishna","lname":"Gurram"}
Employee [id=1, firstName=Krishna, lastName=Gurram]

 

Previous                                                 Next                                                 Home

Monday, 13 March 2023

How to configure maximum file upload size in Micronaut?

micronaut:
  server:
    max-request-size: 5GB
    multipart:
      max-file-size: 5GB
      disk: true
    read-idle-timeout: 30m
    write-idle-timeout: 30m
    idle-timeout: 30m
    netty:
      max-chunk-size: 5MB

 

 

Previous                                                    Next                                                    Home

PlantUML: customize the life line strategy in a sequence diagram

At the time of writing this post, there are two life line strategies supported by PlantUML.

 

solid: Put a solid life line in the sequence diagram.

nosolid: It is default one.

 

nosolidLifeline.txt

@startuml

skinparam lifelineStrategy nosolid

sys1 -> sys2: M1
sys1 <- sys2: M2
|||
sys1 -> sys2: M3
sys1 <- sys2: M4
||100||
sys1 -> sys2: M5

@endum

 

Above snippet generate below diagram.

 


 

solidLifeline.txt

@startuml

skinparam lifelineStrategy solid

sys1 -> sys2: M1
sys1 <- sys2: M2
|||
sys1 -> sys2: M3
sys1 <- sys2: M4
||100||
sys1 -> sys2: M5

@endum

 

There is an ongoing issue with solid lifeline, you can check below link.

https://github.com/plantuml/plantuml/issues/1212

 

There is alternative to get the solid behaviour using styles.

@startuml
<style>
lifeLine {
  LineStyle 0
}
</style>
sys1 -> sys2: M1
sys1 <- sys2: M2
sys1 -> sys2: M3
sys1 <- sys2: M4
sys1 -> sys2: M5

@enduml

 

 

Previous                                                    Next                                                    Home

Playwright : drag and drop example

'page.dragAndDrop()' method drags the source element to the target element.

 

Signature

dragAndDrop(String source, String target)
dragAndDrop(String source, String target, DragAndDropOptions options)

 

'dragAndDrop' method first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

 

Find the below working application.

 

dragAndDrop.html

 

<!DOCTYPE HTML>
<html>

<head>
	<style>
		.square {
			height: 100px;
			width: 100px;
			background-color: #555;
		}

		.circle {
			height: 50px;
			width: 50px;
			background-color: #f00;
			border-radius: 50%;
		}
	</style>

	<script>
		function allowDrop(event) {
			event.preventDefault();
		}

		function dragObject(event) {
			event.dataTransfer.setData("text", event.target.id);
		}

		function dropObject(event) {
			event.preventDefault();
			var data = event.dataTransfer.getData("text");
			event.target.appendChild(document.getElementById(data));
		}
	</script>

</head>

<body>

	<div id="square" class="square" draggable="true" ondrop="dropObject(event)" ondragover="allowDrop(event)"></div>
	<br />
	<div id="circle" class="circle" draggable="true" ondragstart="dragObject(event)" width="336" height="69"></div>

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

	}
}

 

DragAndDrop.java

package com.sample.app.miscellaneous;

import java.io.File;
import java.io.IOException;
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 DragAndDrop {

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

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

			String filePath = "/Users/Shared/playwright/before.png";
			page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get(filePath)));

			page.dragAndDrop("#circle", "#square");

			filePath = "/Users/Shared/playwright/after.png";
			page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get(filePath)));
		}

	}

}

 

Run the above program, you will see two files before.png and after.png.

 

before.png

 

 


after.png

 



 

 

Previous                                                 Next                                                 Home

Sunday, 12 March 2023

Playwright: focus the element

Using Locator.focus() method we can focus the element.

 

Let’s see it with an example.

 

Example

page.locator("#demo").focus();

 

Find the below working application.

 

focusAction.html
<!DOCTYPE html>
<html>

<body>

	Enter your something: <input type="text" id="demo" onfocusout="f1()" onfocusin="f2()" onfocus="f3()">

	<br />
	<br />
	<br />

	onfocusout: <p id="result1"></p>
	onfocusin: <p id="result2"></p>
	onfocus: <p id="result3"></p>

	<input type="button" id="myButton" value="submit" />


	<script>
		function f1() {
			let x = document.getElementById("demo");
			x.value = x.value.toUpperCase();
			document.getElementById("result1").innerHTML = x.value;
			document.getElementById("result2").innerHTML = "";
			document.getElementById("result3").innerHTML = "";
		}

		function f2() {
			document.getElementById("result2").innerHTML = "Element is in focus";
		}

		function f3() {
			document.getElementById("result3").innerHTML = "Element is in focus";

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

	}
}

FocusEvent.java

package com.sample.app.actions;

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 FocusEvent {
	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("actions" + File.separator + "focusAction.html");

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

			page.locator("#demo").focus();
			String result1, result2, result3;
			result1 = page.locator("#result1").innerText();
			result2 = page.locator("#result2").innerText();
			result3 = page.locator("#result3").innerText();
			System.out.println("result1 : " + result1);
			System.out.println("result2 : " + result2);
			System.out.println("result3 : " + result3);

			
			System.out.println("\nType hello to input box");
			page.locator("#demo").type("Hello");
			result1 = page.locator("#result1").textContent();
			result2 = page.locator("#result2").textContent();
			result3 = page.locator("#result3").textContent();
			System.out.println("result1 : " + result1);
			System.out.println("result2 : " + result2);
			System.out.println("result3 : " + result3);
			
			
			// To generate focus out event
			System.out.println("\nMove the cursor out of textbox");
			page.locator("#myButton").click();
			
			result1 = page.locator("#result1").textContent();
			result2 = page.locator("#result2").textContent();
			result3 = page.locator("#result3").textContent();
			System.out.println("result1 : " + result1);
			System.out.println("result2 : " + result2);
			System.out.println("result3 : " + result3);
			
			
		}
	}

}

Output

result1 : 
result2 : Element is in focus
result3 : Element is in focus

Type hello to input box
result1 : 
result2 : Element is in focus
result3 : Element is in focus

Move the cursor out of textbox
result1 : HELLO
result2 : 
result3 :

  

Previous                                                 Next                                                 Home

PlantUML: customize padding using skinparam

Following statements can be used to customize the padding for participant, box.

skinparam ParticipantPadding 25
skinparam BoxPadding 15

 

paddingDemo.txt

@startuml

skinparam ParticipantPadding 25
skinparam BoxPadding 15

' Participants definition
actor client #green

box Internal Service #gold
participant server #445566
database database as db1 #00FFFF
end box

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

How to configure read and write time outs of Micronaut application

 

micronaut:
  server:
    read-idle-timeout: 30m
    write-idle-timeout: 30m
    idle-timeout: 30m

 

 

Previous                                                    Next                                                    Home