Friday, 9 August 2013

Easy way to convert an XML to JSON with some customization

Here I am going  to discuss an easy way to convert an XML to JSON by applying some customization.
There are lot of way by using this an XML can be converted to JSON , among one easiest way is using XSLT.
XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
XSLT stands for XSL Transformations.Earlier using this an XML document used to convert  to HTML to view the XML in browser with design. Here we will extends the same concept to convert an XML doc to JSON.

Now lets take an example XML doc which we will convert into JSON using XSLT
<Message>

    <books>

        <book price="10">

            <name>Java</name>

            <Author>Krushna</Author>

            <publish>2014</publish>

        </book>

        <book price="40">

            <name>J2EE</name>

            <Author>Krish</Author>

            <publish>2015</publish>

        </book>

        <book price="30">

            <name>Spring</name>

            <Author>Krushna</Author>

            <publish>2015</publish>

        </book>

    </books>

</Message>


We want to convert the above XML to JSON like below with some customization like
We don't want the <Message> part and year of publish in JSON . We wnat to change the some of the attribute name.(We can apply any customization according to requirements) So our JSON should look like.
{
   "books": {
      "book": [
        {
          "p": "10",
          "name": "Java",
          "Author": "Krushna",
          
        },
        {
          "p": "40",
          "name": "J2EE",
          "Author": "Krish",
        },
        {
          "-p": "30",
          "name": "Spring",
          "Author": "Krushna",
        }
      ]
    }
}

So for that we required to write the XSLT  file with the rule and it will be like below.


	
	

	
		 
   	 {
   	  	"Books":[

		
			
			{
			"p":"
			
			",
	   		"name":"
			
			"
	   		,
		"Author":"
			
			"
			
			}
			
			
				
					
		]
				
				
					, 
				
			
		
		}
	

Some explanation about the above xslt.
<xsl:for-each select="Message/books/book">:-Like a for loop to select all book
<xsl:value-of select="@price" />:-to select the attribute price
<xsl:value-of select="name" />:-to select the value of tag.
You can know more about, how to write xslt file for xml from here  with all rule.
Remember the xslt file is responsible for converting the XML to any format. To test it quickly thorugh browser you can save the content of sxlt to a file and including the file in xml  and open the xml in browser and you  browser will convert the xml according to xslt.You can include xslt like below
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="books.xslt"?>
<Message>
    <books>
......

<?xml-stylesheet type="text/xsl" href="books.xslt"?> , here the xslt save in a file called books.xslt.

Now let see how we can write java code to convert it on the fly.

import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

public class XSLTransformation {
	private static Logger log = Logger.getLogger(XSLTransformation.class);
	
	public static void transformation(OutputStream out,  InputStream is, InputStream xsltStream){
		Transformer transformer;
		try {
			TransformerFactory factory = TransformerFactory.newInstance();
			Source xslt = new StreamSource(xsltStream);
			transformer = factory.newTransformer(xslt);
			Source text = new StreamSource(is);
			transformer.transform(text,	new StreamResult(out));
			if(log.isDebugEnabled()){
				log.debug("Conversion completed");
			}
		} catch (TransformerConfigurationException e) {
			log.error("Error "+e);
		} catch (TransformerException e) {
			log.error("Error "+e);
		}
	}

}
In the above class

OutputStream:-to which output json data will be written
InputStream is:-from which it will read the xml data
InputStream xsltStream:-from which it will read the xslt

That is All, Thank you.


Wednesday, 7 August 2013

Some tips on java development



Java debugging tips


Use conditional breakpoint
Eclipse allows you to setup conditional break point for debugging java program, which is a breakpoint with condition and your thread will only stop at specified line if condition matches instead of just stopping on that line like in case of line breakpoint. To setup a conditional breakpoint just double click on any line where you want to setup a breakpoint and then right click --> properties and then insert the condition. Now program will only stop when that particular condition is true and program is running on debug mode.
    Use Exception breakpoint
How many times you have frustrated with a NullPointerException and you don't know the source from where the exception is coming. Exception breakpoints are just made for such situation. Both Eclipse and Netbeans allows you to setup Exception breakpoint. You can setup Exception breakpoint based on java exception like NullPointerException or ArrayIndexOutOfBoundException. You can setup Exception breakpoint from breakpoint window and your program will stop when you start it on debug mode and exception occurs.
    Using logical structure
Logical structure option is very useful for examining contents inside java collection classes like java hasmap or Java Arraylist during java debugging. Logical view will show the contents like key and value of hashmap instead of showing full details of hashmap which we may not be interested, you can enable and disable logical view from variables window.
    Step filtering
When we do Step Into on process debugging java program control goes form one class to other and it eventually go to JDK classes like System or String. Some time we just to remain in our application and don't want to navigate into JDK System classes in that case Step filtering is great you can just filter out JDK class from Step into. You can setup step filtering from preferences àJavaàDebugàStep Filtering and enable and disable it from Debug window.

    Copy Stack
While debugging java program if you want to copy the stack of a thread which hit the breakpoint and suspended you do so by "Copy Stack" option. Just right click on Thread on Debug Window and select "Copy Stack".

http://javarevisited.blogspot.com/2011/07/java-debugging-tutorial-example-tips.html#ixzz2WAHFgy3R



About class path
I have set my classpath environment variable as CLASSPATH=/home/test/first:/home/test/second. Now I have Test class of different version in both first and second directory. When I give a command "java Test" What will happen ? Which Test class would be picked? 

Ans:-
As JVM search directory in the order they have listed in CLASSPATH variable So it will first go to the "first" directory 
and if it finds Test.class then it take it from there and won't go to second directory

So the above trick can be used to patch 
releases as
we used to have a folder called "patch" listed as first element in Java CLASSPATH and any point of time we want to put any debug statement or want to test any bug we just modify Java source file , compile it and generate class file and put that inside patch folder instead of creating JAR file and releasing whole new Java application. This is very handy if you are working in a large project where you don't have development environment setup in Windows and your project only runs on Unix server. This approach is much faster than remote debugging Java application in Eclipse

Here is the reason of these Java classpath errors: 

ClassNotFoundException is an Exception and will be thrown when Java program dynamically tries to load a Java class at Runtime and don’t find corresponding class file on classpath. Two keyword here “dynamically” and “runtime”. Classic example of these errors is whey you try to load JDBC driver by using Class.forname(“driver name”) and greeted withjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver. So this error essentially comes when Java try to load a class using forName() or by loadClass() method of ClassLoader. Key thing to note is that presence of that class on Java classpath is not checked on compile time. So even if those classes are not present on Java classpath your program will compile successfully and only fail when you try to run.

On the other hand 
NoClassDefFoundError is an Error and more critical than ClassNotFoundException which is an exception and recoverable. NoClassDefFoundError comes when a particular class was present in Java Classpath during compile time but not available during run-time. Classic example of this error is using log4j.jar for logging purpose and forgot to include log4j.jar on classpath in java during run-time. to read more about logging in Java see . Keyword here is,  class was present at compile time but not available on run-time.  This is normally occurring due to any method invocation on a particular class which is part of library and not available on classpath in Java. This is also asked as common interview questions as  
What is difference between NoClassDefFoundError and ClassNotFoundException Exception in Java”   or
“When do you see NoClassDefFoundError and ClassNotFoundException Exception in Java”. By the way NoClassDefFoundError can also comes due to various other reason like static initializer failure or class not visible to Classloaders in J2EE environment. read 3 ways to resolve NoClassDefFoundError in Java for complete details.

Classpath in Java is an environment variable used by Java Virtual machine to locate or find  class files in Java during class loading.
    You can override value of Classpath in Java defined by environment variable CLASSPATH by providing JVM command line option –cp or –classpath while running your application.


http://javarevisited.blogspot.com/2011/01/how-classpath-work-in-java.html#ixzz2WA688B4C



Important Points about JVM Options:

1)    Boolean JVM options can be turned on with -XX: + and can be turned off with -XX:-.
2)    Numeric JVM Options can be set with -XX: =. Numbers can include 'm' or 'M' for megabytes, 'k' or 'K' for kilobytes, and 'g' or 'G' for gigabytes (for example, 32k is the same as 32768).
3)    String JVM options can be set by using -XX: =, and usually used to specify a file, a path, or a list of commands.