Sunday, November 23, 2014
Java Objects to XML and XML to Java Objects - XStream
import java.io.File;
public static Document readFromXml(String input) throws InvalidDataException {
public static String initializeAndWriteToXml(Object objectToWrite) {
public static <T> T readFromXml(String xmlContent, Class<T> targetObjectClass) {
Thursday, November 20, 2014
JSON to HashMap - Parsing JSON String
Recursivey Parsing JSON String to HashMap
Json String can contain JsonArray, JsonObject etc.
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
public class TestJson{
public static void main(String args[]) throws Exception {
JSONObject jsonObject = new JSONObject(
"{\"A\":\"M1\",\"Data\":[ {\"B\":[{ \"B1\":\"111\",\"B2\":\"Warning \"},{ \"B1\":\"222\",\"B2\":\"Warning \"}],\"C\":[{\"c1\":\"IL2\",\"c2\":\"[0.750183,0.00933380975964486]\"},{\"c1\":\"IL1b\",\"c2\":\"[0.750183,-1.5216938335421]\"}]}]}");
System.out.println(getMap(jsonObject));
}
private static Map getMap(JSONObject object) {
Map<String, Object> map = new HashMap<String, Object>();
Object jsonObject = null;
String key = null;
Object value = null;
try {
Iterator<String> keys = object.keys();
while (keys.hasNext()) {
key = null;
value = null;
key = keys.next();
if (null != key && !object.isNull(key)) {
value = object.get(key);
}
if (value instanceof JSONObject) {
map.put(key, getMap((JSONObject) value));
continue;
}
if (value instanceof JSONArray) {
JSONArray array = ((JSONArray) value);
List list = new ArrayList();
for (int i = 0 ; i < array.length() ; i++) {
jsonObject = array.get(i);
if (jsonObject instanceof JSONObject) {
list.add(getMap((JSONObject) jsonObject));
} else {
list.add(jsonObject);
}
}
map.put(key, list);
continue;
}
map.put(key, value);
}
} catch (Exception e) {
System.out.println(e);
}
return map;
}
}
How to avoid extra POJO's / Classes
package com.package;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
public class Test{
public static void main(String[] args) {
String json = "[{\"givenName\": \"Adrienne H.\",\"surname\": \"Kovacs\"},{\"givenName\": \"Philip\",\"surname\": \"Moons\"}]";
ObjectMapper mapper = new ObjectMapper();
List<Author> list = new ArrayList<Author>();
try {
list = mapper.readValue(json, TypeFactory.defaultInstance().constructCollectionType(List.class, Author.class));
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list);
}
}
So here i do not need to map List<Author> inside any other class.
Tuesday, November 18, 2014
Validate Date against given Date Format
How to validate given Date against Date Format.
SO there are two approaches,
1.) Using SimpleDateFormat
2.) Using Regex.
Basic Example.
SO there are two approaches,
1.) Using SimpleDateFormat
2.) Using Regex.
Basic Example.
SimpleDateFormat
Date date = null; boolean checkformat; try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/dd/MM"); dateFormat.setLenient(false); date = dateFormat.parse("2013/25/09"); } catch (ParseException ex) { ex.printStackTrace(); } if (date == null) { checkformat = false; } else { checkformat = true; } System.out.println(checkformat);
Regex based
public static void main(String[] args) throws ParseException { String input = "2014/12/31"; boolean checkformat; if (input.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) // for yyyy/MM/dd format checkformat = true; else checkformat = false; System.out.println(checkformat); }
Play around the {2}, {2}, {4}
values inside curly braces to prepare regex.
Complexity Increases, let say i have many Date Formats.
public
class
DateUtil {
// List of all date formats that we want to parse.
// Add your own format here.
private
static
List<SimpleDateFormat>;
dateFormats =
new
ArrayList<SimpleDateFormat>() {{
add(
new
SimpleDateFormat(
"M/dd/yyyy"
));
add(
new
SimpleDateFormat(
"dd.M.yyyy"
));
add(
new
SimpleDateFormat(
"M/dd/yyyy hh:mm:ss a"
));
add(
new
SimpleDateFormat(
"dd.M.yyyy hh:mm:ss a"
));
add(
new
SimpleDateFormat(
"dd.MMM.yyyy"
));
add(
new
SimpleDateFormat(
"dd-MMM-yyyy"
));
}
};
/**
* Convert String with various formats into java.util.Date
*
* @param input
* Date as a string
* @return java.util.Date object if input string is parsed
* successfully else returns null
*/
public
static
Date convertToDate(String input) {
Date date =
null
;
if
(
null
== input) {
return
null
;
}
for
(SimpleDateFormat format : dateFormats) {
try
{
format.setLenient(
false
);
date = format.parse(input);
}
catch
(ParseException e) {
//Shhh.. try other formats
}
if
(date !=
null
) {
break
;
}
}
return
date;
}
}
// Test class to test out
public
class
TestDateUtil {
public
static
void
main(String[] args) {
System.out.println(
"10/14/2012"
+
" = "
+ DateUtil.convertToDate(
"10/14/2012"
));
System.out.println(
"10-Jan-2012"
+
" = "
+ DateUtil.convertToDate(
"10-Jan-2012"
));
System.out.println(
"01.03.2002"
+
" = "
+ DateUtil.convertToDate(
"01.03.2002"
));
System.out.println(
"12/03/2010"
+
" = "
+ DateUtil.convertToDate(
"12/03/2010"
));
System.out.println(
"19.Feb.2011"
+
" = "
+ DateUtil.convertToDate(
"19.Feb.2011"
));
System.out.println(
"4/20/2012"
+
" = "
+ DateUtil.convertToDate(
"4/20/2012"
));
System.out.println(
"some string"
+
" = "
+ DateUtil.convertToDate(
"some string"
));
System.out.println(
"123456"
+
" = "
+ DateUtil.convertToDate(
"123456"
));
System.out.println(
"null"
+
" = "
+ DateUtil.convertToDate(
null
));
}
}
Location:
Japan
Java Design Pattern - Factory pattern
Background information
This pattern introduces loose coupling between classes which is the most important principle one should consider and apply while designing the application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations. This not only makes our architecture more flexible but also less fragile.A picture is worth thousand words. Lets see how a factory implementation will look like.
Above class diagram depicts a common scenario using example of car factory which is able to build 3 types of cars i.e. small, sedan and luxury. Building a car requires many steps from allocating accessories to final makeup. These steps can be written in programming as methods and should be called while creating an instance of a specific car type.
If we are unfortunate then we will create instances of car types (e.g. SmallCar) in our application classes and thus we will expose the car building logic to outside world and this is certainly not good. It also prevents us in making changes to car making process because code in not centralized, and making changes in all composing classes seems not feasible.
Implementation
So far we have seen the classes need to be designed for making a CarFactory. Lets hit the keyboard now and start composing our classes.CarType.java will hold the types of car and will provide car types to all other classes
package designPatterns.factory;
public enum CarType {
SMALL, SEDAN, LUXURY
}
Car.java is parent class of all car instances and it will also contain the common logic applicable in car making of all types.
package designPatterns.factory;
public abstract class Car {
public Car(CarType model) {
this.model = model;
arrangeParts();
}
private void arrangeParts() {
// Do one time processing here
}
// Do subclass level processing in this method
protected abstract void construct();
private CarType model = null;
public CarType getModel() {
return model;
}
public void setModel(CarType model) {
this.model = model;
}
}
LuxuryCar.java is concrete implementation of car type LUXURY
package designPatterns.factory;
public class LuxuryCar extends Car {
LuxuryCar() {
super(CarType.LUXURY);
construct();
}
@Override
protected void construct() {
System.out.println("Building luxury car");
// add accessories
}
}
SmallCar.java is concrete implementation of car type SMALL
package designPatterns.factory;
public class SmallCar extends Car {
SmallCar() {
super(CarType.SMALL);
construct();
}
@Override
protected void construct() {
System.out.println("Building small car");
// add accessories
}
}
SedanCar.java is concrete implementation of car type SEDAN
package designPatterns.factory;
public class SedanCar extends Car {
SedanCar() {
super(CarType.SEDAN);
construct();
}
@Override
protected void construct() {
System.out.println("Building sedan car");
// add accessories
}
}
CarFactory.java is our main class implemented using factory pattern. It instantiates a car instance only after determining its type.
package designPatterns.factory;
public class CarFactory {
public static Car buildCar(CarType model) {
Car car = null;
switch (model) {
case SMALL:
car = new SmallCar();
break;
case SEDAN:
car = new SedanCar();
break;
case LUXURY:
car = new LuxuryCar();
break;
default:
// throw some exception
break;
}
return car;
}
}
In TestFactoryPattern.java, we will test our factory code. Lets run this class.
package designPatterns.factory;
public class TestFactoryPattern {
public static void main(String[] args) {
System.out.println(CarFactory.buildCar(CarType.SMALL));
System.out.println(CarFactory.buildCar(CarType.SEDAN));
System.out.println(CarFactory.buildCar(CarType.LUXURY));
}
}
Output:
Building small car
designPatterns.factory.SmallCar@7c230be4
Building sedan car
designPatterns.factory.SedanCar@60e1e567
Building luxury car
designPatterns.factory.LuxuryCar@e9bfee2
As you can see, factory is able to return any type of car instance it is requested for. It will help us in making any kind of changes in car making process without even touching the composing classes i.e. classes using CarFactory.
Advantages of factory pattern
By now, you should be able to count the main advantages of using factory pattern. Lets note down:- The creation of an object precludes its reuse without significant duplication of code.
- The creation of an object requires access to information or resources that should not be contained within the composing class.
- The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
Subscribe to:
Posts (Atom)