Wednesday, September 29, 2010

~~Java Object to Json and Vice Versa Using gson~~

A recent piece of work I completed took about three days of dreading. I wasn't sure how reflection in java could help me out.

Thanks to the connected world we live. All I had to get is a package called "gson" put out by google code community.

As I said, it was about three days of dreading and when the time came to finish it, I sat down and coded for exactly few minutes.

I had to send a json string built out of a list of custom object and to do it I wrote code similar to below:

//you can fill up the list with your custom objects
List<Object> customObjectList = new ArrayList<Object>();
//used gson-1.4.jar(freely available, no license needed)
Gson gson = new Gson();
//just one line as below, feed the list of your object and that's it
String internalOrderJSON = gson.toJson(objectList);

//it is just a simple string with json structure, still a string
//so it can be sent just like string to a server as in below
response.setContentType("text/plain");
response.getWriter().write(internalOrderJSON);

Ok..so the above was the easy part. Very plain and simple. But you know the world we live in, we give crap to somebody and lets say they put up with it, well the bad news is they will crap you back :)

Similarly, now whosoever I handed the json to, sent it back to me on the server side to convert it back to objects, to my persistant object and then persist it!!!

Oh well this is the part that I had dreaded originally.

But life was glorious again when I searched to find if java reflection was supported by the gson stack and Yes!! it was.

Ok, so implementation wise here is how you can do it.

//lets say the origin of the json string that you have is a http call
String jsonStringReceived = request.getParameter("someName");

//again get a reference to the Gson API.
Gson gson = new Gson();
//this one line is the magic, you tell Gson what type using reflection at run time
Type collectionType = new TypeToken<List<Object>>() {}.getType();
//and the following is not almost same as before
List<Object> yourCustomObjectList = gson.fromJson(jsonStringReceived, collectionType);
//your code to use the list of your object can go here


So, to summarize: all you need is a jar called gson-1.4.jar (at the time of this writing, gson-1.4.jar did the trick for me)

In addition to importing java's "reflection" package in your java class, you will need to import some other specific gson packages, but the following should be all you need if you plan to use the above technique:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
get a copy of gson-1.4.jar for the above imports.

Thanks for stopping by and Happy Coding!
~Nirmal


Build a better mousetrap, and the world will beat a path to your door...
~Emerson

Friday, April 23, 2010

grep: global regular expression print

Some of the most useful unix tools and commands for daily use in a day's life of a system admin...(more to be added, keep checking)

printenv --prints all system and user created env. vairables.

cd ~directory_name -takes you directly to that directory

id --display system id number

tail --display last 10 lines. if tail -20 then display last 20 lines

grep string fileName --display lines with the "string" in the fale called "fileName"

cd ~ --go to home directory

diff {file1} {file2} -- show the differences in file1 and file2

sdiff {file1} {file2} --show files side by side

wc {file} --cound words in a file

df --system disk capacity

du --system disk usage

\\10.5.109.104\c$ to remote access unshared

ps ux --display processes owned by the current user.

kill -9 process_id --will kill the process, -9 here ensures execution.

du -sc * | sort -n | tail -- list size of all the names and sizes of all files and directories, sort in increasing size order, print the last few lines

uname -aspi --enlist the osx kernel etc

grep -r -i somethingtosearchfor ./ --recursively search all files and directories for the string.

find . -exec grep "boo" {} \; --search for string "boo" in every directory below the current directory

tail -n8 fileName | grep "boo" --performs a grep on the last 8 lines of file called "a_file"

find | grep "hello" --will print out the file that find returns that contain the text "hello"

find . -exec grep "boo" {} \; --search for the string "boo" in every directory below the current directory.

grep -c "boo" fileName --will print an integer indicating the number of lines that matched the string "boo"

grep -l "boo" * --searching through multiple files for the same string

grep -x "boo" a_file --searching for eXact matches only.

grep "e$" a_file --search in all lines containg words having the letter "e" as the last letter

Sunday, December 20, 2009

Why use ArrayList implementation of List?

Using ArrayList as a choice List implementation is like second nature in case of a lot of developers. We are so gotten used to picking ArrayList that we sometime forget why exactly we use the ArrayList implementation.

Here is an example of a driver program which uses ArrayList to add different objects in List and then display them.

This program's purpose is to demo the fact that ArrayList is used for the purpose of being able to add and maintain a list of different type of objects.

A couple other benefit of using ArrayList is
1. We don't need to know the total number of elements to be stored in advance.
2. The elements are accessible for any of the add/delete etc operations from anywhere in the list. In other words, each element in the ArrayList are directly accessible with an index number.

/**
* @author nsingh
*
*/

public class ListDifferentObjectTypes {
public static void main(String args[]){
List<Object> listObj = new ArrayList<Object>();
for(int i=0;i<4;i ){
AnotherObject anotherObject = new AnotherObject();
OneObject oneObject = new OneObject();
anotherObject.setLocatinType("someType" i "");
oneObject.setMessage("Message #" i "");
oneObject.setMessageId("MessageId" i "");
listObj.add(oneObject);
listObj.add(anotherObject);
}
for (Iterator iterator = listObj.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
if(object instanceof OneObject){
OneObject oneObj= (OneObject)object;
System.out.println(oneObj.getMessageId());
System.out.println(oneObj.getMessage());
}
if(object instanceof AnotherObject){
AnotherObject anotherObj = (AnotherObject)object;
System.out.println(anotherObj.getLocatinType());
System.out.println(anotherObj.getLocatinType());
}
}
}
}


//one of the objects


/**
* This class is used set a string message,
* and convert object of this type to json.
* @author nsingh
*
*/

public class OneObject {

private String messageId;
private String message;
/**
* @return the messageId
*/
public String getMessageId() {
return this.messageId;
}
/**
* @param messageId the messageId to set
*/
public void setMessageId(String messageId) {
this.messageId = messageId;
}
/**
* @return the message
*/
public String getMessage() {
return this.message;
}
/**
* @param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}

}


//another object
/**
* @author nsingh
*
*/

public class AnotherObject {

private String locatinType;

/**
* @return the locatinType
*/
public String getLocatinType() {
return this.locatinType;
}

/**
* @param locatinType the locatinType to set
*/
public void setLocatinType(String locatinType) {
this.locatinType = locatinType;
}
}

Sunday, September 27, 2009

XSD simple type/user defined type



Lets say that you are at receiving end of a data which has certain format. To interpret that, we can create our own type for reading such document.

For example lets say that the user telephone number sent in an xml document is in US telephone number format as in:
304-657-6062, or lets say that the data expected is a ss number with format like: xxx-xx-xxxx, in such case we have to create a simple type with our own name of the type which we can use directly in the definition of complexType, but if you are looking for how you can put certain format for the expected type, here is your answer:

in case the data expected is a telephone number, then the simple type xsd definition is as in the image above:




Thanks for reading,

~nirmal

Monday, July 27, 2009

system.out.println made easy

If you find yourself using too much System.out.println("something") a lot, here is a savior, it got into my head deep down the first time I clamped my eyes on this beast:

public class SomeClass{
private methodName1(params){
doSomething();
log("print whatever on console...");
}
}

public methodName2(params){
log("print waterver2 on console...");
}
}

private static void log(String aMessage){
System.out.println(aMessage);
}
}

---------------
so just using
private static void log(String aMessage){
System.out.println(aMessage);
}

at one place, you can replace all your System.out.println() statements by simply this:

log("some message");

Saves a lot of time and space.

cheers,

~nirmal

Sunday, July 26, 2009

Math.Random()

math.random() generates a number between 0 and 1. If you do *X(x=any integer), it changes the math.random() to 0-9, then you can do +1 to change it to 1-10.

Eg. For generating random values in the range 35 - 55, look at the following example:
Math.floor((math.random() * 35) + 55)

~nirmal

Thursday, August 7, 2008

get around Date, blow your date's mind, Customize

This is one sweet utility that I have used over and over again. Honestly I keep forgetting the exact way everytime I need to format date(the java type ;)

Nice to keep it in a little utility program inside the utility package of your project


Example 1:
Date exampleDate;
exampleDate = formatDateTime(useFormat);
private Date formatDateTime(String dateStr){
Date newDate = null;
DateFormat outdfm = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");//"MM-dd-yy HH:mm:ss"//MMM dd hh:mm:ss yyyy
try{
newDate = outdfm.parse(dateStr);
}
catch (ParseException e){
e.printStackTrace();
}
return newDate;
}

Example 2:
Date curDate = new Date();
Calendar cal = Calendar.getInstance();
String dateStr = "2009-03-19T10:10:51";
curDate = formatDateTime(dateStr);
cal.setTime(curDate);
private static Date formatDateTime(String dateStr){
Date newDate = null;
//DateFormat outdfm = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss");//"MM-dd-yy HH:mm:ss"//MMM dd hh:mm:ss yyyy
DateFormat outdfm = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss");// 2009-03-19T10:10:51//"yyyy.MM.dd G 'at' hh:mm:ss z"->> 1996.07.10 AD at 15:08:56 PDT
try{
newDate = outdfm.parse(dateStr);
}catch (ParseException e){
e.printStackTrace();
}
return newDate;
}


Thanks for reading, and Thanks for stopping by!!

~Nirmal

Today is the Tomorrow we worried about yesterday
~from somebody's email signature