Friday, 14 January 2022

Define custom Jackson annotation using @JacksonAnnotationsInside

You can define custom Jackson annotation using @JacksonAnnotationsInside. @JacksonAnnotationsInside is a meta-annotation used to create a "combo-annotations" by having a container annotation, which needs to be annotated with this annotation as well as all annotations it 'contains'.

Example



Find the below working application. 

AppJSON.java

package com.sample.app.jackson;

import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public @interface AppJSON {
	
}

Employee.java

package com.sample.app.model;

import com.sample.app.jackson.AppJSON;

@AppJSON
public class Employee {
	private Integer id;
	private String name;
	private Integer age;

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

App.java

package com.sample.app.jackson;

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

public class App {

	public static void main(String args[]) throws JsonProcessingException {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setName("Krishna");
		
		String result = new ObjectMapper().writeValueAsString(emp);
		System.out.println(result);
	}
}

Output

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


Previous                                                    Next                                                    Home

Handle parameterized error messages using MessageFormat class

 In this post, I am going to explain how to beautify application error messages using MessageFormat class.

‘java.text.MessageFormat’ class provides a format method that takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

For example,

MessageFormat.format("successsful inserts : {0},\nfailed inserts: {1},\nprocessing time : {2} milliseconds", "29", "1", "1234")

Above snippet generates the below message.

successsful inserts : 29,
failed inserts: 1,
processing time : 1234 milliseconds

{0} is replaced with 29

{1} is replaced with 1

{2} is replaced with 1234

 

Find the below working application.

Define AppErrorCodes class.

AppErrorCodes.java

package com.sample.app.format;

import java.text.MessageFormat;

public enum AppErrorCodes {
	ENTITY_CREATED(201, "App-200-1", "Entity is created with id {0}"), BULK_INSERT(201, "App-201-1",
			"successsful inserts : {0},\nfailed inserts: {1},\nprocessing time : {2} milliseconds");

	private String errorCode;
	private String errorMessage;
	private int httpCode;

	AppErrorCodes(int httpCode, String errorCode, String errorMessage) {
		this.httpCode = httpCode;
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}

	public String getFormattedErrorMessage(String... params) {
		return MessageFormat.format(errorMessage, params);
	}
}

Define main application class.

App.java

package com.sample.app.format;

public class App {

	public static void main(String args[]) {
		String formattedMessage = AppErrorCodes.BULK_INSERT.getFormattedErrorMessage("29", "1", "1234");

		System.out.println(formattedMessage);
	}

}

Output

successsful inserts : 29,
failed inserts: 1,
processing time : 1234 milliseconds



You may like

Miscellaneous

Wednesday, 12 January 2022

Call the main method of one class from other class using reflection

 Step 1: Get an instance of the class.

Class<?> clazz = Class.forName("com.sample.app.Test");

Step 2: Get the main method of Test class.

Method main = clazz.getMethod("main", String[].class);

Step 3: Invoke the main method.

String[] args1 = { "Hello", "Hi!!!!" };
main.invoke(null,  (Object) args1);

Find the below working application.

Test.java

package com.sample.app;

public class Test {
	
	public static void main(String args[]) {
		System.out.println("In the main method of Test class");
		
		if(args == null) {
			return;
		}
		
		for(String arg: args) {
			System.out.println(arg);
		}
	}

}

HelloWorld.java

package com.sample.app;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class HelloWorld {

	public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class<?> clazz = Class.forName("com.sample.app.Test");
		Method main = clazz.getMethod("main", String[].class);

		String[] args1 = { "Hello", "Hi!!!!" };

		System.out.println("About to call the main method of Test class");
		main.invoke(null,  (Object) args1);

	}
}

Run main method of HelloWorld class, you will see below output in the console.

About to call the main method of Test class
In the main method of Test class
Hello
Hi!!!!







You may like

Interview Questions

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

instanceof operator behavior with interface and class

Create maven multi module project in Eclipse

 What is multi module project?

A multi module project is used to manage a group of submodules. A multi-module project is built from an aggregator POM which is located in the project’s root directory and has a package type as pom. Child modules inherit from the parent pom.

In a multi-module project, using the single maven command you can build all the artifacts and maintain all the artifact versions in sync. Configuring a CI/CD pipeline is easy, one Jenkin job will do the job.

Let’s see it with an example. I am going to create a root project ‘platform’ and create two modules under this project.

a.   connectors

b.   transformers

Follow the below step-by-step procedure to build multi-module project in Eclipse.

Open Eclipse.

File -> New -> Other



Select ‘Maven Project’.


Click on Next button.

Select the check box ‘Create a simple project (skip archetype selection)’.



Click on Next button.


Set following fields.

a.   Group Id as com.sample.app

b.   Artifact Id as platform

c.    Version to 1.

d.   Packaging type should be pom

 


Click on Finish button.

 

Project hierarchy looks like below.



pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>platform</artifactId>
  <version>1</version>
  <packaging>pom</packaging>
</project>

When you open pom.xml, you can observe packaging type is pom. This pom is called the parent pom. That means it acts as a parent pom to all the projects underneath this project.

 

Let’s create two modules under this project.

a.   connectors

b.   transformers

 

Create connectors module

File -> New -> Other



Select ‘Maven Module’ and click on the Next button.



Select the check box ‘Create a simple project (skip archetype selection).

Set module name as connectors and set the parent project to platform.

 

Click on Next button.



Use default options (packaging is set to jar) and click on Finish button.



connectors project pom.xml is given below.

 

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.sample.app</groupId>
		<artifactId>platform</artifactId>
		<version>1</version>
	</parent>
	<artifactId>connectors</artifactId>
</project>

As you observe pom.xml, parent portion is added with platform project details.

 

‘platform’ project pom.xml contains new module information.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>platform</artifactId>
	<version>1</version>
	<packaging>pom</packaging>
	<modules>
		<module>connectors</module>
	</modules>
</project>

Create transformers module

Follow the same procedure as above. Post transformers module creation, you can observe new module ‘transformers’ is added to platform pom.xml.

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>platform</artifactId>
	<version>1</version>
	<packaging>pom</packaging>
	<modules>
		<module>connectors</module>
		<module>transformers</module>
	</modules>
</project>

Total project structure is given below.



Open a terminal and navigate to the platform pom.xml file and execute the command ‘mvn clean install’. Once the command is executed successfully, you can observe two jar files (connectors-1.jar, transformers-1.jar) get created.


Previous                                                    Next                                                    Home

Thursday, 6 January 2022

instanceof operator behavior with interface and class

 Recently I observed a noticeable behavior of instanceof operator while working with interfaces and classes. Let me explain with an example.

InstanceOfDemo.java
public class InstanceOfDemo {

	static interface A{}
	
	static class B{}
	
	static class C{}
	
	public static void main(String args[]) {
		B obj = new B();
		
		System.out.println(obj instanceof A);
		System.out.println(obj instanceof B);
		System.out.println(obj instanceof C);
	}
}

When I try to compile the above program, I end up in compiler error.



It is because Java does not support multiple class inheritance, so it is known during the compilation that an object of type B cannot be a subtype of C. On the other hand, it is possible that obj can be an instance of interface A.

InstanceOfDemo.java
public class InstanceOfDemo {

	static interface A{}
	
	static class B{}
	
	static class C{}
	
	static class D extends B implements A{}
	
	public static void main(String args[]) {
		B obj = new D();
		
		System.out.println(obj instanceof A);
	}
}

In the above snippet, by looking at 'obj instanceof A' expression compiler cannot deduce in advance whether will it evaluate to true or false, but by looking at 'obj instanceof C' compiler knows that this is always evaluated to false, which is meaningless and helps you to prevent an error.




You may like

Interview Questions

Explain Loop inversion in Java

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

Explain Loop inversion in Java

 Loop inversion is a compiler optimization technique where a while loop is replaced by an if block containing a do..while loop.

How does loop inversion improve performance?

Let me explain with an example.
int i = 0;
int a[] = new int[10];
while (i < 10) {
	a[i] = 0;
	i++;
}

Post loop inversion optimization, above code will be transformed like below.

int i = 0;
int a[] = new int[10];

if (i < 10) {
	do {
		a[i] = 0;
		i++;
	} while (i < 10);
}

How this transformation improve performance?

When the value of i is 10, the processor need not execute a goto instruction to come out of the loop (which is required in the first case). This improves performance. By nature, any jump in the code causes a pipeline stall, which is a detriment to performance.

 

Reference

https://en.wikipedia.org/wiki/Pipeline_stall



You may like

Interview Questions

How to specify jar files in command line?

Check whether I have JDK or JRE in my system

How to check whether string contain only whitespaces or not?

How to call base class method from subclass overriding method?

Can an interface extend multiple interfaces in Java?

Tuesday, 14 December 2021

Gson: Convert json string to Pretty print json string

Below snippet convert the json to Pretty json string.

String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = JsonParser.parseString(uglyJson);
String prettyJsonString = gson.toJson(jsonElement);

 

Find the below working application.

 

PrettyJson.java

package com.sample.app.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class PrettyJson {

	public static void main(String args[]) {
		String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		JsonElement jsonElement = JsonParser.parseString(uglyJson);
		String prettyJsonString = gson.toJson(jsonElement);

		System.out.println(prettyJsonString);
	}

}

 

Output

{
  "name": "Krishna",
  "age": 31
}

 

 

 

Previous                                                    Next                                                    Home