October 19, 2017

Java Real Time currency convertor

import java.io.IOException;



/**
 *
 */

/**
 * @author belazy
 *
 */
public class CurrencyConvertor {

   public float convert(String currencyFrom, String currencyTo) throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://quote.yahoo.com/d/quotes.csv?s=" + currencyFrom + currencyTo + "=X&f=l1&e=.csv");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpGet, responseHandler);
        httpclient.getConnectionManager().shutdown();
        return Float.parseFloat(responseBody);
    }

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

CurrencyConvertor cc = new CurrencyConvertor();
try {
            float current = cc.convert("USD", "AED");
            System.out.println(current);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

}

}

October 17, 2017

Find Mean Mode and Median in Java : Introduction to Data Science

import java.util.Arrays;

/**
 * Introduction to Data science
 * Finding Mean Mode and Median
 */

/**
 * @author belazy
 * Consumerfed triveni supermarket kozhikode
 *
 */
public class DataScienceLessonOne {

Integer[] arraySample = {4,5,3,3,5,6,7,3,1,5};

/**
* @param args
*/
public static void main(String[] args) {

DataScienceLessonOne dataScience = new DataScienceLessonOne();
System.out.println(dataScience.findMean());
System.out.println(dataScience.findMedian());
System.out.println(dataScience.findMode());

}

private char[] findMode() {
// TODO Auto-generated method stub
return null;
}

private float findMedian() {
// TODO Auto-generated method stub
float median = 0;
Arrays.sort(arraySample);

median = (arraySample.length % 2) == 0 ? (arraySample[arraySample.length/2]+arraySample[(arraySample.length/2)-1])/2 :arraySample[arraySample.length/2];


return median;
}

private float findMean() {
int sum = 0;
float mean = 0;
for(int a:arraySample){
sum = sum +a;
mean = sum/arraySample.length;
}
return mean;
}

}

October 03, 2017

Collection list to simple Array convert in java

/**
 * Sample java programs
 */
package com.belazy.misc;

import java.util.ArrayList;
import java.util.List;

/**
 * @author belazy
 *
 */
public class SampleArrays {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

List<Integer> sampleList = new ArrayList<Integer>();

for(int i=0;i<=10;i++){
sampleList.add(i);
}


/**
* Arrays
*/
Integer[] a= new Integer[sampleList.size()];
a= sampleList.toArray(a);
System.out.println("5 th element in the array "+a[5]);

}

}

A small description


Arrays are treated as object in JVM
Type of array - The elementType has to specified (say Integer)
The size of the array should be on the stack before the operation is performed
Example :-
Int[] javaArraySample = new int [12];

September 30, 2017

Most and longest running software developed for consumerfed

Dear readers,

It has been two and a half years since the application is launched at consumerfed kozhikode region and successfully running in the region at 40 trivenis including mobile , godown, neethi medicasl sections and liquor shop.
The whole credit for developing the software goes to the IT section regional office ( Management trainees) But now consumerfed is planning to reduce the size of Management trainees

A great that to I T Section kozhikode.


The project was developed on March 2015 and last updated on September 2017. Report to mobiles are also available now. Backup are automated

E mail report
footer
Tracking the sales , subsidy monitoring, tracking hardware details are other key features of the application. Reports in html , pdf formats are available, video tutorials are available in youtube channel.


You can contact us on 0091-8218808029

Join us at linkedin  follow us  Hangout group

Iphone8 and Iphone 8 plus launched now

September 27, 2017

How to use same method for different objects in java

/**
 *  Main class
 */
package com.belazy.generics;

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

/**
 * @author belazy
 * @param <T>
 *
 */
public class GenericMethodClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericMethodClass g = new GenericMethodClass();

String type ="type";

Employee emp = new Employee();
Student stud = new Student();
g.returnText(emp, type);
g.returnText(stud, type);

}



public <T> String returnText(T element , String type){
String value = null;
try {
Class thisClass = element.getClass();

type = element.getClass().toString();
Method method = thisClass.getMethod("getName");
System.out.println("method with getName "+method.getName());
System.out.println(method.invoke(element));
if(method.invoke(element).toString().equalsIgnoreCase("type")){
System.out.println("inside if ");
Method method2 = thisClass.getMethod("getText");
System.out.println(method2.invoke(element));
value = method2.invoke(element).toString();
}


} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


System.out.println(type);
return value;


}

}

Student class

/**
 *
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Student {

String name = "type";
String text = "Student Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}



}

Employee Class

/**
 * 
 */
package com.belazy.generics;

/**
 * @author belazy
 *
 */
public class Employee {
String name = "type";
String text = "employee Type";
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}

}


September 25, 2017

Difference between maps in java - Hash and Tree map

/**
 *
 */
package com.belazy.misc;

import java.util.HashMap;
import java.util.TreeMap;

/**
 * @author belazy
 *
 */
public class CollectionMaps {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionMaps colMap = new CollectionMaps();
colMap.callHashMap();
colMap.callTreeMap();

}

private void callTreeMap() {
// TODO Auto-generated method stub
System.out.println("Inside Tree Map");
TreeMap<Integer, String> studentDetails = new TreeMap<Integer, String>();
studentDetails.put(10, "sachin");
studentDetails.put(7, "jadeja");
studentDetails.put(5, "dhoni");
studentDetails.put(1, "virat");
studentDetails.put(3, "saurav");
System.out.println("data in map "+studentDetails);
System.out.println("reverse order :"+studentDetails.descendingMap());
System.out.println("descending key sets : "+studentDetails.descendingKeySet());
System.out.println("first Entry "+studentDetails.firstEntry());
}

private void callHashMap() {
// TODO Auto-generated method stub
System.out.println("Inside Hash Map");
HashMap<Integer, String> studentDetails = new HashMap<Integer, String>();

studentDetails.put(10, "sachin");
studentDetails.put(7, "jadeja");
studentDetails.put(5, "dhoni");
studentDetails.put(1, "virat");
studentDetails.put(3, "saurav");

System.out.println(studentDetails);


}

}

September 24, 2017

To Loop all dates between a start date and end date in java

/**
 *
 */
package com.belazy.misc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.ReadableInstant;

/**
 * @author belazy
 *
 */
public class DateManipulation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DateManipulation dateManip = new DateManipulation();
try {
dateManip.printDateBw("2017-10-01","2017-10-10");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void printDateBw(String startDate, String endDate) throws ParseException {

int days = Days.daysBetween(LocalDate.parse(startDate), LocalDate.parse(endDate)).getDays();
System.out.println(days);

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Date stDate = sd.parse(startDate);
System.out.println(" start date :"+stDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(startDate)); // parsed date and setting to calendar

for(int i=1;i<=days;i++){

calendar.add(Calendar.DATE, 1);  // number of days to add
String destDate = sd.format(calendar.getTime());  // End date
System.out.println(destDate);

}

}

}


program 2

/**
 *
 */
package com.belazy.misc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.ReadableInstant;

/**
 * @author belazy
 *
 */
public class DateManipulation {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DateManipulation dateManip = new DateManipulation();
try {
dateManip.printDateBw("2017-10-01","2017-10-10");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void printDateBw(String startDate, String endDate) throws ParseException {

int days = Days.daysBetween(LocalDate.parse(startDate), LocalDate.parse(endDate)).getDays();
System.out.println(days);

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
Date stDate = sd.parse(startDate);
System.out.println(" start date :"+stDate);
Calendar calendar = Calendar.getInstance();
// parsed date and setting to calendar

for(int i=0;i<days;i++){
calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(startDate));
calendar.add(Calendar.DAY_OF_YEAR, i);  // number of days to add
String destDate = sd.format(calendar.getTime());  // End date
System.out.println(destDate);

}

}

}


September 22, 2017

Cfed Price wizdul

Created a price wizdul webservice


September 20, 2017

Hotel Supplier Integration Java Design pattern


Hotel Supplier Integration Java Design pattern


Hotel.java

package com.travelport.hotels;

public class Hotel {

String name;
String code;
String chain;
String description;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the chain
*/
public String getChain() {
return chain;
}
/**
* @param chain the chain to set
*/
public void setChain(String chain) {
this.chain = chain;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}



}

Room.java

package com.travelport.hotels;

public class Room {

private String room;
private String code;
private String ph;
/**
* @return the room
*/
public String getRoom() {
return room;
}
/**
* @param room the room to set
*/
public void setRoom(String room) {
this.room = room;
}
/**
* @return the code
*/
public String getCode() {
return code;
}
/**
* @param code the code to set
*/
public void setCode(String code) {
this.code = code;
}
/**
* @return the ph
*/
public String getPh() {
return ph;
}
/**
* @param ph the ph to set
*/
public void setPh(String ph) {
this.ph = ph;
}
}

Mainclass

/**
 *
 */
package com.travelport.hotels;

/**
 * @author belazy
 *
 */
public class MainHotelsClass {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SearchHotels srcH = new SearchHotels();
srcH.searchHotel();
SearchRoom req = new SearchRoom();
req.searchRoom();

}

}


SearchHotels

/**
 * 
 */
package com.travelport.hotels;

/**
 * @author nijesh
 *
 */
public class SearchHotels extends TravelPortAbstract{



/* private Hotel getHotelProperties(Hotel hotel) {
// TODO Auto-generated method stub
hotel.setName("Mariot hotel");
hotel.setCode("ABC");
hotel.setDescription("hotel Desctiption");
hotel.setChain("CH1");
return hotel;
}*/

public void searchHotel() {
// TODO Auto-generated method stub
Hotel hotel = new Hotel();
hotel = getHotelProperties(hotel);
System.out.println("auth: "+isAuthenticated());
System.out.println("code: "+hotel.getCode());
}



}


SearchRoom

/**
 * 
 */
package com.travelport.hotels;

/**
 * @author belazy
 *
 */
public class SearchRoom extends TravelPortAbstract {

public void searchRoom() {
// TODO Auto-generated method stub
Hotel hotel = new Hotel();
Room room = new Room();
hotel = getHotelProperties(hotel);
room = getRoom(room);
System.out.println("room :"+room.getCode());
System.out.println("hotel :"+hotel.getCode());
}



}


TravelPortAbstract class

/**
 * 
 */
package com.travelport.hotels;

/**
 * @author nijesh
 *
 */
public abstract class TravelPortAbstract {
protected Hotel getHotelProperties(Hotel hotel) {
// TODO Auto-generated method stub
hotel.setName("Mariot hotel");
hotel.setCode("ABC");
hotel.setDescription("hotel Desctiption");
hotel.setChain("CH1");
return hotel;
}
protected boolean isAuthenticated(){
return true;
}
protected Room getRoom(Room room) {
// TODO Auto-generated method stub
room.setCode("R12");
room.setRoom("Single bed");
return room;
}

}

https://support.travelport.com/webhelp/uapi/Content/Hotel/Shared_Hotel_Topics/Hotel%20Payment%20Types_Pre-Pay_and_Post-Pay.htm

https://support.travelport.com/webhelp/uapi/Content/Hotel/Hotel_TRM/TRM%20Synchronous%20Hotel%20Search.htm

https://support.travelport.com/webhelp/uapi/Content/Hotel/Shared_Hotel_Topics/Hotel%20Payment%20Types_Guarantee_%20Deposit_Pre-Pay.htm




http://javabelazy.blogspot.in/

September 19, 2017

commit and rollback - transaction management in dbms

Data Base management system

commit and rollback

Commit and rollback maintain the integrety of the transaction

try to update a table name value using update query

update tblProduct set qtyavailable = 200 where  productid = 1;

This database query is not a part of any transaction, as soon as you execute the query the change is made premenant to the datbase immediatly.

then if you execute the select query

Select * from tblProduct

you can see the change is effected in database

but in case of transaction

begin transaction
update tblProduct set qtyavailable = 300 where  productid = 1;

the following change will be made in database. but if you


try to establish a new connection , and run the above select query ... you can see "Executing query"

that becase you just begin the transaction, but not commited , the other users cannot see the uncommited database


that is because, sql server default isolation level is read commit data

set transaction isolation level read uncommited;









September 05, 2017

How to copy one object from another in Java

Converting one object into another in java


Main class


import org.dozer.DozerBeanMapper; /** * @author belazy * */ public class MainClass { public static void main(String[] args) { DozerBeanMapper mapper = new DozerBeanMapper(); mapper.setMappingFiles(Arrays.asList("dozer_mapping.xml")); Employee employee = new Employee("Sachin", "tendulkar", 45); EmployeeNew employeeNew = mapper.map(employee, EmployeeNew.class); System.out.println(employeeNew.getEmployeeFirstName()); } }

EmployeeTest


/** * */ package com.belazy.dozer; /** * @author belazy * */ public class EmployeeTest { private String firstName; private String lastName; private int age; public EmployeeTest(String firstName, String lastName, int age) { // TODO Auto-generated constructor stub this.firstName = firstName; this.lastName = lastName; this.age = age; } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the age */ public int getAge() { return age; } /** * @param age the age to set */ public void setAge(int age) { this.age = age; } }

EmployeeNew class

/** * */ package com.belazy.dozer; /** * @author belazy * */ 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; } }

Dozer mapping. xml

<mappings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://dozer.sourceforge.net" xsi:schemalocation="http://dozer.sourceforge.net
      http://dozer.sourceforge.net/schema/beanmapping.xsd">
    <mapping>
        <class-a>com.belazy.dozer.EmployeeTest</class-a>
        <class-b>com.belazy.dozer.EmployeeNew</class-b>
        <field>
            <a href="https://www.blogger.com/null">firstName</a>
            <b>employeeFirstName</b>
        </field>
        <field>
            <a href="https://www.blogger.com/null">lastName</a>
            <b>employeeLastName</b>
        </field>
        <field>
            <a href="https://www.blogger.com/null">age</a>
            <b>employeeAge</b>
        </field>
    </mapping>
</mappings>




http://www.java2s.com/Open-Source/Java_Free_Code/Tutorial/Download_travelport_uapi_tutorial_Free_Java_Code.htm

htm
http://testws.galileo.com/GWSSample/Help/GWSHelp/java_sample_step_2__booking_an_air_reservation.htm

https://support.travelport.com/webhelp/GWS/Content/Overview/Getting_Started/Sample_Web_Service_Calls/Java_Sample_Step_1__Air_Availability_Request.htm


http://www.galileo.co.kr/document/Galileo%20Web%20Services%20Product%20Overview.pdf

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.

June 10, 2017

Web Service Definition Language - WSDL tutorial

Working with Web Services in Java





Problems and Its Solutions


The Web service is already in use. Use a class customization to resolve this conflict

use -B-XautoNameResoulution while generating class from wsdl.
wsimport -keep -verbose -B-XautoNameResolution cfedStock.wsdl

http://javabelazy.blogspot.in/

May 14, 2017

Java Technical Question in bayt.com

Ross is an event organizer. He has received data regarding the participation of employees in two different events ( say event One and event Two ). Some employees have participated in only one event and others have participated in both events. Ross now needs to count the number of employees who have taken part in both events. The record received by Ross consist of employee ids, which are unique. Write a program that accepts the employee ids participating in each event ( the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event.

1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005 so the program should give the output as:2

java source code

import java.util.ArrayList;
import java.util.List;

/**
 * solutions for question one
 */

/**
 * @author shimjith consumerfed
 *
 */
public class EventOrganizer {

private List<Integer> eventOne = null;
private List<Integer> eventTwo = null;
private static int count = 0;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EventOrganizer main = new EventOrganizer();
main.getEmployeeDetails();
main.showEmployeeDetails();
main.findEmployeeDetails();
System.out.println("The employee present in both events :"+EventOrganizer.count);

}

// to get employees present in both arrays
private void findEmployeeDetails() {
// TODO Auto-generated method stub
for (int row: eventOne){

if(eventTwo.contains(row)){
count = count +1;
}
}

}

private void showEmployeeDetails() {
// TODO Auto-generated method stub
System.out.println("Employee ids of event one "+eventOne);
System.out.println("Employee ids of event two "+eventTwo);
}

private void getEmployeeDetails() {
// You can use scanner class to get values to event one and two
eventOne = new ArrayList<Integer>();
eventTwo = new ArrayList<Integer>();
eventOne.add(1001);
eventOne.add(1002);
eventOne.add(1003);
eventOne.add(1004);
eventOne.add(1005);
eventTwo.add(1106);
eventTwo.add(1008);
eventTwo.add(1005);
eventTwo.add(1003);
eventTwo.add(1016);;
eventTwo.add(1017);
eventTwo.add(1112);

}

}


out put

Facebook comments