Wednesday, 2 March 2022

Dozer can do automatic type conversion

Dozer can map an object to other as long as it finds attributes of the same name in both classes. But in case, if the data types of mapped attributes are different, Dozer will perform automatic type conversion wherever it is possible.

 

Let’s see it with an example.

 

 


Type2.java

package com.sample.app.model;

public class Type2 {
	private int a;
	private int b;

	public Type2() {
	}

	public Type2(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type2 [a=" + a + ", b=" + b + "]";
	}

}

 

Type3.java

package com.sample.app.model;

public class Type3 {

	private String a;
	private double b;

	public Type3() {
	}

	public Type3(String a, double b) {
		this.a = a;
		this.b = b;
	}

	public String getA() {
		return a;
	}

	public void setA(String a) {
		this.a = a;
	}

	public double getB() {
		return b;
	}

	public void setB(double b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type3 [a=" + a + ", b=" + b + "]";
	}

}

 

DataTypeConversionDemo.java

package com.sample.app;

import org.dozer.DozerBeanMapper;

import com.sample.app.model.Type2;
import com.sample.app.model.Type3;

public class DataTypeConversionDemo {

	public static void main(String[] args) {

		DozerBeanMapper mapper = new DozerBeanMapper();

		Type3 type3 = new Type3("10", 20.987);
		Type2 type2 = mapper.map(type3, Type2.class);

		System.out.println(type3);
		System.out.println(type2);
	}

}

Output

Type3 [a=10, b=20.987]
Type2 [a=10, b=20]

As you observe the code,  the attribute names are the same but their data types are different.

 

In the Type2 class, a, b are of type int and in Type3 class, 'a' is of type String and 'b' is of type double.

 

 

 

 

 

 


Previous                                                 Next                                                 Home

Dozer: bean mapping: hello world application

In this post, I am going to explain a simple example, where source and destination objects have same properties.

 

In Dozer, Matched property names are automatically handled by Dozer. Two properties with different names can be mapped either progamatically or via xml configuration.

 

Example

<field>
  <a>fName</a>
  <b>firstName</b>
</field>

 

Field ‘fName’ in type ‘a’ is mapped to the field ‘firstName’ in type ‘b’.

 

Step 1: Define Type1.

 

public class Type1 {
	private int a;
	private int b;

	......
	......
}

 

Step 2: Define Type2.

public class Type2 {
	private int a;
	private int b;

	......
	......
}

 

Step 3: Map Type1 data to Type2 object.

DozerBeanMapper mapper = new DozerBeanMapper();
Type1 type1 = new Type1(10, 20);
Type2 type2 = mapper.map(type1, Type2.class);


 

Find the below working application.

 

Type1.java

package com.sample.app.model;

public class Type1 {
	private int a;
	private int b;

	public Type1() {
	}

	public Type1(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type1 [a=" + a + ", b=" + b + "]";
	}

}

 

Type2.java

package com.sample.app.model;

public class Type2 {
	private int a;
	private int b;

	public Type2() {
	}

	public Type2(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type2 [a=" + a + ", b=" + b + "]";
	}

}

 

HelloWorld.java

package com.sample.app;

import org.dozer.DozerBeanMapper;

import com.sample.app.model.Type1;
import com.sample.app.model.Type2;

public class HelloWorld {

	public static void main(String[] args) {
		DozerBeanMapper mapper = new DozerBeanMapper();

		Type1 type1 = new Type1(10, 20);
		Type2 type2 = mapper.map(type1, Type2.class);
		
		System.out.println(type1);
		System.out.println(type2);
	}

}

 

Output

Type1 [a=10, b=20]
Type2 [a=10, b=20]

 

 

 

 

 

 

 

 

  

Previous                                                 Next                                                 Home

Introduction to Dozer

 

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another.

 

Features

a.   Matched property names are automatically handled by Dozer.

b.   Mapping can be specified either Programmatically or with xml configuration.

c.    Implicit data type conversion is automatically performed by Dozer mapping engine. At the time of writing this post, Dozer supports the following types of conversions:

Primitive to Primitive Wrapper

Primitive to Custom Wrapper

Primitive Wrapper to Primitive Wrapper

Primitive to Primitive

Complex Type to Complex Type

String to Primitive

String to Primitive Wrapper

String to Complex Type if the Complex Type contains a String constructor

String to Map

Collection to Collection

Collection to Array

Map to Complex Type

Map to Custom Map Type

Enum to Enum

String to any of the supported Date/Calendar Objects.

Objects containing a toString() method that produces a long representing time in (ms) to any supported Date/Calendar object.

 

 

Dependency used

<!-- https://mvnrepository.com/artifact/net.sf.dozer/dozer -->
<dependency>
    <groupId>net.sf.dozer</groupId>
    <artifactId>dozer</artifactId>
    <version>5.5.1</version>
</dependency>

 

You can download all the working applications from this link.


For more information on dozer library, refer below FAQ section.

http://dozer.sourceforge.net/documentation/faq.html

 

 

Previous                                                 Next                                                 Home

Dozer: Bean mapping library tutorial

 


      Introduction to Dozer
      Dozer: bean mapping: hello world application
      Dozer can do automatic type conversion
      Dozer: Specify bean mappings via xml file
      Dozer: Specify mappings via annotations
      Dozer: Specify bean mapping using BeanMappingBuilder
      Dozer: Specify custom type converter using xml file
      Dozer: Map collection of objects
      Dozer: Exploring xml based mappings
      Dozer: Map only specific fields
            Dozer: Specify xml mappings from input stream
            Dozer: String to date mapping
            Dozer: Specify default date formatting at class mapping level

Previous                                                 Next                                                 Home

Tuesday, 1 March 2022

logback: gzip rolling log files automatically

File compression format can be specified via fileNamePattern property.

 

Example

<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
  <fileNamePattern>${LOG_FILES_HOME}/app-%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>

  <maxFileSize>1MB</maxFileSize>
  <maxHistory>30</maxHistory>
  <totalSizeCap>20GB</totalSizeCap>
</rollingPolicy>

 

Find the below working application.

 

Step 1: Create new maven project ‘logback-zip-log-files’.

 

Step 2: Update pom.xml with maven dependencies,

 

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>logback-zip-log-files</artifactId>
  <version>1</version>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.10</version>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.2.10</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.36</version>
    </dependency>


  </dependencies>
</project>

 

Step 3: Create logback.xml file under src/main/resources folder.

 

logback.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
  <property name="LOG_FILES_HOME" value="/Users/Shared/logback" />

  <appender name="consoleAppender"
    class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <charset>UTF-8</charset>
      <Pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
      </Pattern>
    </encoder>
  </appender>


  <appender name="FILE"
    class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_FILES_HOME}/app.log</file>

    <rollingPolicy
      class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <fileNamePattern>${LOG_FILES_HOME}/app-%d{yyyy-MM-dd}.%i.log.gz
      </fileNamePattern>

      <maxFileSize>1MB</maxFileSize>
      <maxHistory>30</maxHistory>
      <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>


    <encoder>
      <charset>UTF-8</charset>
      <pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n
      </pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="consoleAppender" />
    <appender-ref ref="FILE" />
  </root>
</configuration>

 

Step 4: Define HelloWorld class.

 

HelloWorld.java

 

package com.sample.app;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  private static Logger logger = LoggerFactory.getLogger(HelloWorld.class);

  private static void sleep(int noOfSeconds) {
    try {
      TimeUnit.SECONDS.sleep(noOfSeconds);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {

    while (true) {
      for (int i = 0; i < 10000; i++) {
        logger.trace("Trace message");
        logger.debug("Debug message");
        logger.info("Info message");
        logger.warn("Warning message");
        logger.error("Error message");
      }

      sleep(1);

    }

  }
}

 

Total project structure looks like below.


 


 

Run HelloWorld.java application.

 

You can observe that log files are compressed to .gz format in /Users/Shared/logback folder.

 

$ls -lart
total 2456
drwxrwxrwt  15 root     wheel      480 Feb 25 15:39 ..
-rw-r--r--   1 krishna  wheel     9193 Feb 25 15:45 app-2022-02-25.0.log.gz
-rw-r--r--   1 krishna  wheel     8201 Feb 25 15:45 app-2022-02-25.1.log.gz
-rw-r--r--   1 krishna  wheel     8058 Feb 25 15:45 app-2022-02-25.2.log.gz
drwxr-xr-x   7 krishna  wheel      224 Feb 25 15:45 .
-rw-r--r--   1 krishna  wheel  1215810 Feb 25 15:45 app.log

You can download the complete working application from below link.

https://github.com/harikrishna553/java-libs/tree/master/logback/logback-zip-log-files


Previous                                                 Next                                                 Home