August 26, 2017

A Simple Java Program to Copy one object to Another

Copying one object to another without using getters and setters


Employee POJO Class


/**
 * Employee POJO class
 */
package com.belazy.dozer;

/**
 * @author sachin
 *
 */
public class Employee {

private String employeeFirstName;
private String employeeLastName;
private int employeeAge;

public Employee(String employeeFirstName,String employeeLastName, int employeeAge ) {
// TODO Auto-generated constructor stub
this.employeeAge = employeeAge;
this.employeeLastName = employeeLastName;
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeFirstName
*/
public String getEmployeeFirstName() {
return employeeFirstName;
}
/**
* @param employeeFirstName the employeeFirstName to set
*/
public void setEmployeeFirstName(String employeeFirstName) {
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeLastName
*/
public String getEmployeeLastName() {
return employeeLastName;
}
/**
* @param employeeLastName the employeeLastName to set
*/
public void setEmployeeLastName(String employeeLastName) {
this.employeeLastName = employeeLastName;
}
/**
* @return the employeeAge
*/
public int getEmployeeAge() {
return employeeAge;
}
/**
* @param employeeAge the employeeAge to set
*/
public void setEmployeeAge(int employeeAge) {
this.employeeAge = employeeAge;
}



}


Employee New POJO Class ( The subclass of employee )

/**
 *  Employee New class ( The subclass of employee )
 */
package com.belazy.dozer;

/**
 * @author virat
 *
 */
public class EmployeeNew {
private String employeeFirstName;
private String employeeLastName;
private int employeeAge;
public EmployeeNew() {
// TODO Auto-generated constructor stub
}
public EmployeeNew(String employeeFirstName,String employeeLastName, int employeeAge ) {
// TODO Auto-generated constructor stub
this.employeeAge = employeeAge;
this.employeeLastName = employeeLastName;
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeFirstName
*/
public String getEmployeeFirstName() {
return employeeFirstName;
}
/**
* @param employeeFirstName the employeeFirstName to set
*/
public void setEmployeeFirstName(String employeeFirstName) {
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeLastName
*/
public String getEmployeeLastName() {
return employeeLastName;
}
/**
* @param employeeLastName the employeeLastName to set
*/
public void setEmployeeLastName(String employeeLastName) {
this.employeeLastName = employeeLastName;
}
/**
* @return the employeeAge
*/
public int getEmployeeAge() {
return employeeAge;
}
/**
* @param employeeAge the employeeAge to set
*/
public void setEmployeeAge(int employeeAge) {
this.employeeAge = employeeAge;
}

}

Main class


Main Java Class

/**
 * 
 */
package com.belazy.dozer;

import org.dozer.DozerBeanMapper;

/**
 * @author jadeja
 *
 */
public class MainClass {
public static void main(String[] args) {
DozerBeanMapper mapper = new DozerBeanMapper();
Employee employee = new Employee("Sachin", "tendulkar", 45);
EmployeeNew employeeNew = mapper.map(employee, EmployeeNew.class);
System.out.println(employeeNew.getEmployeeFirstName());
}

}


Output


10 [main] INFO org.dozer.config.GlobalSettings - Trying to find Dozer configuration file: dozer.properties
20 [main] WARN org.dozer.config.GlobalSettings - Dozer configuration file not found: dozer.properties.  Using defaults for all Dozer global properties.
20 [main] INFO org.dozer.DozerInitializer - Initializing Dozer. Version: 5.3.2, Thread Name: main
60 [main] INFO org.dozer.jmx.JMXPlatformImpl - Dozer JMX MBean [org.dozer.jmx:type=DozerStatisticsController] auto registered with the Platform MBean Server
70 [main] INFO org.dozer.jmx.JMXPlatformImpl - Dozer JMX MBean [org.dozer.jmx:type=DozerAdminController] auto registered with the Platform MBean Server
70 [main] INFO org.dozer.DozerBeanMapper - Initializing a new instance of dozer bean mapper.
Sachin


Jar Files Needed


commons-beanutils-1.7.jar
commons-logging-1.1.1-sources.jar
commons-logging-api-1.1.1.jar
dozer-5.3.2.jar
joda-time-2.2.jar
log4j-1.2.16.jar
log4j-over-slf4j-1.6.1.jar
org.apache.commons.lang_2.4.jar
slf4j.api-1.6.1.jar
slf4j-jdk14-1.6.1.jar
slf4j-simple-1.6.1.jar


Issues faced while developing the application

Failed to instantiate [ch.qos.logback.classic.LoggerContext]
Reported exception:
java.lang.NoSuchMethodError: ch.qos.logback.classic.util.ContextInitializer.<init>(Lch/qos/logback/classic/LoggerContext;)V
at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:85)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:56)
at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:189)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:112)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:105)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:235)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:208)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:221)
at org.dozer.DozerBeanMapper.<clinit>(DozerBeanMapper.java:67)
at com.belazy.dozer.MainClass.main(MainClass.java:15)
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.dozer.stats.StatisticsManagerImpl.<init>(StatisticsManagerImpl.java:39)
at org.dozer.stats.GlobalStatistics.<init>(GlobalStatistics.java:29)
at org.dozer.stats.GlobalStatistics.<clinit>(GlobalStatistics.java:24)
at org.dozer.DozerBeanMapper.<clinit>(DozerBeanMapper.java:68)
at com.belazy.dozer.MainClass.main(MainClass.java:15)
Caused by: java.lang.SecurityException: class "org.slf4j.impl.MessageFormatter"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:114)
at ch.qos.logback.classic.Logger.filterAndLog(Logger.java:421)
at ch.qos.logback.classic.Logger.filterAndLog(Logger.java:430)
at ch.qos.logback.classic.Logger.info(Logger.java:494)
at org.dozer.config.GlobalSettings.loadGlobalSettings(GlobalSettings.java:113)
at org.dozer.config.GlobalSettings.<init>(GlobalSettings.java:67)
at org.dozer.config.GlobalSettings.<clinit>(GlobalSettings.java:46)
... 5 more



http://javabelazy.blogspot.in/

August 24, 2017

Copying one POJO object to another without clone

/**
 * MainClass
 */
package com.belazy.dozer;

import org.dozer.DozerBeanMapper;

/**
 * @author nijesh
 *
 */
public class MainClass {

public static void main(String[] args) {
DozerBeanMapper mapper = new DozerBeanMapper();
Employee employee = new Employee("Sachin", "tendulkar", 45);
EmployeeNew employeeNew = mapper.map(employee, EmployeeNew.class);
System.out.println(employeeNew.getEmployeeFirstName());
}

}

/**
 *
 */
package com.belazy.dozer;

/**
 * @author nijesh
 *
 */
public class Employee {

private String employeeFirstName;
private String employeeLastName;
private int employeeAge;

public Employee(String employeeFirstName,String employeeLastName, int employeeAge ) {
// TODO Auto-generated constructor stub
this.employeeAge = employeeAge;
this.employeeLastName = employeeLastName;
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeFirstName
*/
public String getEmployeeFirstName() {
return employeeFirstName;
}
/**
* @param employeeFirstName the employeeFirstName to set
*/
public void setEmployeeFirstName(String employeeFirstName) {
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeLastName
*/
public String getEmployeeLastName() {
return employeeLastName;
}
/**
* @param employeeLastName the employeeLastName to set
*/
public void setEmployeeLastName(String employeeLastName) {
this.employeeLastName = employeeLastName;
}
/**
* @return the employeeAge
*/
public int getEmployeeAge() {
return employeeAge;
}
/**
* @param employeeAge the employeeAge to set
*/
public void setEmployeeAge(int employeeAge) {
this.employeeAge = employeeAge;
}



}




/**
 *
 */
package com.belazy.dozer;

/**
 * @author nijesh
 *
 */
public class EmployeeNew {
private String employeeFirstName;
private String employeeLastName;
private int employeeAge;

public EmployeeNew(String employeeFirstName,String employeeLastName, int employeeAge ) {
// TODO Auto-generated constructor stub
this.employeeAge = employeeAge;
this.employeeLastName = employeeLastName;
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeFirstName
*/
public String getEmployeeFirstName() {
return employeeFirstName;
}
/**
* @param employeeFirstName the employeeFirstName to set
*/
public void setEmployeeFirstName(String employeeFirstName) {
this.employeeFirstName = employeeFirstName;
}
/**
* @return the employeeLastName
*/
public String getEmployeeLastName() {
return employeeLastName;
}
/**
* @param employeeLastName the employeeLastName to set
*/
public void setEmployeeLastName(String employeeLastName) {
this.employeeLastName = employeeLastName;
}
/**
* @return the employeeAge
*/
public int getEmployeeAge() {
return employeeAge;
}
/**
* @param employeeAge the employeeAge to set
*/
public void setEmployeeAge(int employeeAge) {
this.employeeAge = employeeAge;
}





}

Jar files needed

dozer-5.4.0.jar
logback-classic-0.9.jar
logback-core-0.9.6.jar
slf4j.jar
slf4j-log4j13-1.0.1.jar


errors
Failed to instantiate [ch.qos.logback.classic.LoggerContext]
Reported exception:
java.lang.NoSuchMethodError: ch.qos.logback.classic.util.ContextInitializer.<init>(Lch/qos/logback/classic/LoggerContext;)V
at org.slf4j.impl.StaticLoggerBinder.init(StaticLoggerBinder.java:85)
at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:56)
at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:189)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:112)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:105)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:235)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:208)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:221)
at org.dozer.DozerBeanMapper.<clinit>(DozerBeanMapper.java:67)
at com.belazy.dozer.MainClass.main(MainClass.java:15)
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.dozer.stats.StatisticsManagerImpl.<init>(StatisticsManagerImpl.java:39)
at org.dozer.stats.GlobalStatistics.<init>(GlobalStatistics.java:29)
at org.dozer.stats.GlobalStatistics.<clinit>(GlobalStatistics.java:24)
at org.dozer.DozerBeanMapper.<clinit>(DozerBeanMapper.java:68)
at com.belazy.dozer.MainClass.main(MainClass.java:15)
Caused by: java.lang.SecurityException: class "org.slf4j.impl.MessageFormatter"'s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:114)
at ch.qos.logback.classic.Logger.filterAndLog(Logger.java:421)
at ch.qos.logback.classic.Logger.filterAndLog(Logger.java:430)
at ch.qos.logback.classic.Logger.info(Logger.java:494)
at org.dozer.config.GlobalSettings.loadGlobalSettings(GlobalSettings.java:113)
at org.dozer.config.GlobalSettings.<init>(GlobalSettings.java:67)
at org.dozer.config.GlobalSettings.<clinit>(GlobalSettings.java:46)
... 5 more


http://javabelazy.blogspot.in/

August 15, 2017

Gzip compression working Spring MVC

GZIP compression

public static String gzipCompression(String strNew) throws IOException {
    if (strNew == null || strNew.length() == 0) {
        return str;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    gzip.write(str.getBytes());
    gzip.close();
    String outStr = out.toString("UTF-8");
    return outStr;
 }


Using BufferedWriter

public static String compressString(String str) throws IOException{
if (str == null || str.length() == 0) {
    return str;
}

BufferedWriter writer = null;

try{
    File file =  new File("your.gzip")
    GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(file));

    writer = new BufferedWriter(new OutputStreamWriter(zip, "UTF-8"));

    writer.append(str);
}
finally{        
    if(writer != null){
     writer.close();
     }
  }
 }


Using compression filter

package : com.planetj.servlet.filter.compression
spring compression filter


How to enable HTTP response compression

Read 69.18

http://docs.spring.io/spring-boot/docs/1.3.x/reference/htmlsingle/#how-to-enable-http-response-compression

GZip compression in spring

http://www.oodlestechnologies.com/blogs/Gzip-Servlet-Filter-in-Spring-MVC

Handling filters in spring MVC

https://www.mkyong.com/spring-mvc/how-to-register-a-servlet-filter-in-spring-mvc/

Working with @controllerAdvice and ResponseAdvice in spring 4

https://sdqali.in/blog/2016/06/08/filtering-responses-in-spring-mvc/

Interceptors

Interceptors are use to manipulate entities like inputstream and outputstreams. There are two kinds of interceptors ReaderInterceptor and WriterInterceptors


public class GzipWriterInterceptor implements writerinterceptors {
@override
public void aroundwriteto(writerinterceptorcontext context){
outputstream os = context.getoutputstream();
context.setoutputstream(new Gzipoutputsream(os));
context.proceed();
}
}


Using ResponseWrapper

https://stackoverflow.com/questions/25020331/spring-mvc-how-to-modify-json-response-sent-from-controller

@Override
public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);

    chain.doFilter(request, responseWrapper);

    String responseContent = new String(responseWrapper.getDataStream());

    RestResponse fullResponse = new RestResponse(/*status*/, /*message*/,responseContent);

    byte[] responseToSend = restResponseBytes(fullResponse);

    response.getOutputStream().write(responseToSend);

}


using response body advice

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyAdvice.html

@controllerAdvice +  implements ResponseBodyAdvice<Object>

https://mtyurt.net/2015/07/20/spring-modify-response-headers-after-processing/

@ControllerAdvice
public class HeaderModifierAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        response.getHeaders().add("dummy-header","dummy-value");
        return body;
    }
}


Rest Easy spring integration

http://www.concretepage.com/spring-4/spring-4-resteasy-3-jackson-json-integration-example-with-tomcat

August 01, 2017

How dependency Injection is achieved in Spring M V C

How dependency Injection is achieved in Spring M V C




Spring will search for two annotations @autowired and @component to do this job. Inversion of control is easily achievable in spring.

A sample program is given below

public class DependencyInjectionEx{

@Autowired
TestSerivceInf service;


@Test
public void TestFun(){
System.out.println(service.callService());

}

}


The Service class that implemented the interface

@Component
Class TestServiceImpl implements TestSerivceInf {

@Override
public String callService(){
    return "consumerfed liquor shop kozhikode";
}

}


The Interface

public interface TestSerivceInf {

    public String callService()

}

Then if more than two servcieimpl class implements an interface, then we need to specify to which class we are autowiring it, Then only springs component scan will works.

One way to create Object as same name as the class.

@Autowired
TestSerivceInf testServiceImpl ; will search for TestServiceImpl class

The second way is @qualifier(value = "className")

@Autowired
@qualifier(value = "TestServiceImpl")
TestSerivceInf testServiceImpl


if you think this tutorial is really helpful let us know.

Facebook comments