Saturday, July 26, 2014

JDOM (Java based Document Object Model)



In previous post, you have learnt about SAX and DOM. JDOM is related to DOM, but JDOM is very efficient in reading, manipulating and writing than DOM. This is very simple to implement.


What is JDOM ?



JDOM is simplistic method to parse XML files than DOM. This is specially designed for Java (Java based DOM), so it has many features that can be used with Java. You have learnt something called node in DOM. JDOM is not talking about node. They are referenced in their own types. In JDOM,

  • XML element is an instance of element
  • XML attribute is an instance of attribute.
  • XML document itself is an instance of document.

Advantages of JDOM


  • Lightweight and fast.
  • More efficient than SAX or DOM.
  • Implementation is easy.
  • Can be integrated with SAX or DOM.


How to add JDOM Library ?


JDOM is not provided in JDK like SAX or DOM. You need to download the latest JDOM library from www.jdom.org


Right click on Libraries and click Add Library


Provide a name for JDOM library

Click Add JAR/Folder


Browse jdom.jar file and add it


Finally you have done adding JDOM library


How to use JDOM ?

Students.xml


<?xml version="1.0" encoding="UTF-8"?>
<school>   
  <student id="1">
    <firstname>John</firstname>
    <lastname>Lodne</lastname>
    <age>20</age>
    <city>A</city>
  </student>
  <student id="2">
    <firstname>Ann</firstname>
    <lastname>Linda</lastname>
    <age>23</age>
    <city>B</city>
  </student>
</school>



JDOMTest.java


package JD;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
 
public class JDOMTest {
  public static void main(String[] args) {
    Scanner scn = new Scanner(System.in); //Create Scanner object to get file path as a String
    SAXBuilder builder = new SAXBuilder();//Create SAX builder object

    System.out.print("Enter the path of xml file: ");
    String fileName = scn.nextLine();

    try {
      Document documentObj = (Document) builder.build(fileName);//Convert file to document object
      Element rootNode = documentObj.getRootElement();//Get the root element
      List list = rootNode.getChildren("student");//List down all xml elements

      for (int i = 0; i < list.size(); i++) {
          
        Element node = (Element) list.get(i);

        System.out.println(" ");
        System.out.println("First name : " + node.getChildText("firstname"));
        System.out.println("Last name : " + node.getChildText("lastname"));
        System.out.println("Age : " + node.getChildText("age"));
        System.out.println("City : " + node.getChildText("city"));
        System.out.println("---------------------");
      }
    }catch (IOException io) {
       System.out.println(io.getMessage());
    }catch (JDOMException jdomex) {
       System.out.println(jdomex.getMessage());
    }
  }
}



Display


There is a link to download the NetBeans project file.



Friday, July 25, 2014

DOM (Document Object Model)


What is DOM ?


DOM (Document Object Model) is another way that can be used to get information from XML file. You have seen what are the differences between SAX and DOM, in previous post. So no need to mention again. There are other ways called JDOM, DOM4J...etc. They are much easier than DOM. But you have to add their libraries into your project. We will discuss them later.


What is the tree structure of DOM ?


One of special things in DOM is, it uses tree structure of the XML document known as DOM tree to read data.

<?xml version="1.0" encoding="UTF-8"?>
<company>   
    <staff id="1">
        <firstname>John</firstname>
        <lastname>Lodne</lastname>
        <nickname>JL</nickname>
        <salary>100000</salary>
    </staff>
    <staff id="2">
        <firstname>Ann</firstname>
        <lastname>Linda</lastname>
        <nickname>Lin</nickname>
        <salary>200000</salary>
    </staff>
</company>


Here you can see the corresponding DOM tree according to above XML file.




This is the DOM tree, it consist of nodes and you can traverse using this thinking about normal tree structures (Binary tree, B tree, Multiway tree...etc) in Data structures. DOM is a huge part which has so many theories. But this post is about, How to use DOM with Java.


DOM API Packages

  • org.w3c.dom
  • javax.xml.parsers

org.w3c.dom Package

  • This package consist of a set of interfaces defined by W3C.

javax.xml.parsers Package

  • This package contains DocumentBuilderFactory and DocumentBuilder classes which are specific to DOM.
  • Other SAX specific classes are also there.


    Node types in DOM


    Everything in XML document is a node. There are so many node types in DOM. Go to W3 resource. But in this post I use mainly two types.
    • Element node : Represent an element
    • Text node : Represent text content in a element


      How DOM works ?

      1. DOM parser parses entire XML document.
      2. Then it loads into the memory.
      3. Build the tree.


        Disadvantages of DOM

        1. Memory consuming method (SAX use less memory).
        2. Slower than SAX.

        How to read XML file using DOM

        Students.xml


        <?xml version="1.0" encoding="UTF-8"?>
        <school>   
            <student id="1">
                <firstname>John</firstname>
                <lastname>Lodne</lastname>
                <age>20</age>
                <city>A</city>
            </student>
            <student id="2">
                <firstname>Ann</firstname>
                <lastname>Linda</lastname>
                <age>23</age>
                <city>B</city>
            </student>
        </school>
        
        

        DomTest.java


        package DomPkg;
        
        import javax.xml.parsers.DocumentBuilderFactory;
        import javax.xml.parsers.DocumentBuilder;
        import org.w3c.dom.*;
        import java.util.Scanner;
        
        public class DomTest {
            
          public static void main(String args[]){
                
            try{
              Scanner scn = new Scanner(System.in);
              System.out.print("Enter your file path: ");
              String filePath = scn.nextLine();
                    
              DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
              DocumentBuilder db = dbFactory.newDocumentBuilder();
              Document document = db.parse(filePath);
              document.getDocumentElement().normalize();
                   
              System.out.println("-----------------------");
              System.out.println("Root element: " + document.getDocumentElement().getNodeName());
              System.out.println("-----------------------");
              NodeList list = document.getElementsByTagName("student");
                    
              for(int i=0; i<list.getLength(); i++){            
                Node node = list.item(i);
                System.out.println("Current Element: " + node.getNodeName());
                        
                if(node.getNodeType() == Node.ELEMENT_NODE){
                   Element element = (Element)node;
                           
                   System.out.println("Firstname: " + element.getElementsByTagName("firstname").item(0).getTextContent());
                   System.out.println("Lastname: " + element.getElementsByTagName("lastname").item(0).getTextContent());
                   System.out.println("Age: " + element.getElementsByTagName("age").item(0).getTextContent());
                   System.out.println("City: " + element.getElementsByTagName("city").item(0).getTextContent());
                   System.out.println("-----------------------");
                }
              }       
            }catch(Exception e){
                e.printStackTrace();
            }
          }   
        }      
        
        


        Here is the link to download the NetBeans project file. You can download it and run.


        You will be able to see this output.



        There are so many methods that can use DOM to read XML file. Here is another method that can be used to get data from an entire XML file with the Node types. This is recommended by Oracle site.




        Hope you enjoy, lets meet in next post.

        Friday, July 18, 2014

        SAX (Simple API for XML)

        What is SAX ?


        • SAX is very simple API which is used to read XML data in simple way. The result of SAX is event based.
        • This takes one pass over the document from start to finish. 
        • Once SAX starts, it goes through all the way to the end. 

        SAX Processing steps

        1. Create an event handler.
        2. Create the SAX parser.
        3. Assign the event handler to the parser.
        4. Parse the document while sending each event to the handler.



        SAX vs DOM

        SAX API Packages


        Mainly SAX API consist of following packages.

        • org.xml.sax
        • org.xml.sax.ext
        • org.xml.sax.helpers
        • javax.xml.parsers

        org.xml.sax Package


        This package contains the basic interfaces of SAX API. There are four interfaces.

        • ContentHandler
        • ErrorHandler
        • DTDHandler
        • EntityHandler

        The ContentHandler Interface

        This interface provides various call back methods that are invoked when a SAX parser parses an XML file. You can use this interface to receive parsing event notifications. It consist of following methods.

        • startDocument() - Get invoked when the parser starts parsing.
        • endDocument() - Get invoked when the parser ends parsing.
        • startElement() - Get invoked when the parser encounters a start element.
        • endElement() - Get invoked when the parser encounters an end element.
        • characters() - Get invoked when the parser encounters character data.
        • ingorableWhitespaces() - Get invoked when the parser encounters white spaces.

        The ErrorHandler Interface

        This interface defines the methods to handle any error that might occur during parsing. Mainly there are three methods.

        • warning() - Gives notifications of warnings might occur during processing
        • error() - Gets invoked when a recoverable error occurs while parsing XML
        • fatalError() - Gets invoked when fatal error occurs while parsing XML

        The DTDHandler Interface

        This interface defines methods to receive notification when a parser process the DTD (Document Type Definition) of XML file. Notations represent the binary format cannot be parsed.

        • notationDecl() - Gives notifications about an entity being declared as a notation
        • unparsedEntityDecl() - Gives notifications about the entity of an XML that cannot be parsed. 

        The EntityHandler Interface

        This method is invoked when the parser must identify data identified by a URI (Uniform Resource Identifier). URI is either URL (Uniform Resource Locator) or URN (Uniform Resource Name). URL specify the location of a file while URN identify the name of a document.


        org.xml.sax.ext Package

        This package defines SAX extensions that can be used to advanced SAX processing such as accessing DTD or lexical information of an XML document. It defines two interfaces.

        • DeclHandler - Declares methods that provide notification about DTD.
        • LexicalHandler - Declares methods that provide notification about lexical events.

        org.xml.sax.helpers Package


        This package contains helper classes of SAX API. The default handler class of this package implements the ContentHandler, DTDHandler, EntityHadler and ErrorHandler interfaces. So you only need to override the required method once you need it.

        javax.xml.parsers Package

        This is another important package that has collection of classes that enable Java applications to process with XML documents. It can use either SAX or DOM to do it.

        • SAXParser - Allows parsing of XML file
        • SAXParserFactory - Enables you to retrieve an object of SAXParsers.

        How to read XML file using SAX ?


        This can be done in many ways. You can read and print either whole XML file or the custom things that you need to print. Following example shows you to read and print the information as a list.

        Employee.xml


        <?xml version="1.0" encoding="UTF-8"?>
        <company>   
            <staff id="1">
                <firstname>John</firstname>
                <lastname>Lodne</lastname>
                <nickname>JL</nickname>
                <salary>100000</salary>
            </staff>
            <staff id="2">
                <firstname>Ann</firstname>
                <lastname>Linda</lastname>
                <nickname>Lin</nickname>
                <salary>200000</salary>
            </staff>
            <staff id="3">
                <firstname>Donna</firstname>
                <lastname>Flor</lastname>
                <nickname>Don</nickname>
                <salary>150000</salary>
            </staff>
        </company>
        
        

        SaxXmlRead.java


        package SaxTest;
        
        import org.xml.sax.Attributes;
        import org.xml.sax.SAXException;
        import org.xml.sax.helpers.DefaultHandler;
        import javax.xml.parsers.SAXParser;
        import javax.xml.parsers.SAXParserFactory;
        
        public class SaxXmlRead extends DefaultHandler{
         
          public void readXml(){
            try {
              SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();   
              SAXParser saxParser = saxParserFactory.newSAXParser();
        
              DefaultHandler defaultHandler = new DefaultHandler(){
        
                 /*cTag = closeTag 
                   oTag = openTag
                   fnTag = firstNameTag
                   lnTag = lastNameTag*/
                
                String fnTag="cTag";
                String lnTag="cTag";
                String nnTag="cTag";
                String sTag="cTag";
        
                public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException{
                  if (qName.equalsIgnoreCase("firstname")) {
                    fnTag = "oTag";
                  }
                  if (qName.equalsIgnoreCase("lastname")) {
                    lnTag = "oTag";
                  }
                  if (qName.equalsIgnoreCase("nickname")) {
                    nnTag = "oTag";
                  }
                  if (qName.equalsIgnoreCase("salary")) {
                    sTag = "oTag";
                  }
                }
        
                public void characters(char ch[], int start, int length)throws SAXException {
                  if (fnTag.equals("oTag")) {
                    System.out.println("First Name : " + new String(ch, start, length));
                  }
                  if (lnTag.equals("oTag")) {
                    System.out.println("Last Name : " + new String(ch, start, length));
                  }
                  if (nnTag.equals("oTag")) {
                    System.out.println("Nick Name : " + new String(ch, start, length));
                  }
                  if (sTag.equals("oTag")) {
                    System.out.println("Salary : " + new String(ch, start, length));
                    System.out.println("----------------------");
                  }
                }
        
                public void endElement(String uri, String localName, String qName)throws SAXException {
                  if (qName.equalsIgnoreCase("firstName")) {
                    fnTag = "cTag";
                  }
                  if (qName.equalsIgnoreCase("lastName")) {
                    lnTag = "cTag";
                  }
                  if (qName.equalsIgnoreCase("nickname")) {
                    nnTag = "cTag";
                  }
                  if (qName.equalsIgnoreCase("salary")) {
                    sTag = "cTag";
                  }
                }
              };
        
              saxParser.parse("C:\\Users\\Ravi\\Documents\\NetBeansProjects\\Sax\\src\\SaxTest\\Employee.xml", defaultHandler);
                
            }catch (Exception e) {
               e.printStackTrace();
            }
          }
        }
        
        
        
        

        SaxXmlImp.java


        package SaxTest;
        
        public class SaxXmlIpm {
            public static void main(String args[]){
                SaxXmlRead xml = new SaxXmlRead();
                xml.readXml();
            }
        }
        
        

        I have created package called SaxTest and imported all these three code into it as follows. You need to change the file path of the XML file in SaxXmlRead.java file. (You can find the path by right clicking on XML file and go to properties and then you can find the path.)



        Then you need to run SaxXmlIpm.java file and then you will be able to following result.






        Here you can download the NetBeans project file also, you can import it to NetBeans and run easily. 




        Now you have a idea about get information from XML file as a list or ordered script. Here is another project file that shows you, how  to print whole XML file using SAX. You can download it and run.







        Tuesday, July 15, 2014

        Introduction to JAXR, JAX-RPC, SAAJ and JAXB

        JAXR (Java API for XML Registries)


        JAXR provides standard Java API for accessing web service registries such as UDDI (Universal Description, Discovery and Integration), ebXML (Electronic Business XML) and others. JAXR allows clients to find information about published web services through those registries. Service provides also can publish their services in the registries using JAXR.



        JAX-RPC (Java API for XML-based Remote Procedure Calls)


        This Java API is used to create web services and web clients that performs remote procedure calls to access the web service. RPC model enables the clients  to use services on remote systems. 

        Source : docs.oracle.com

        How it works

        1. A Java method executes on a stub.
        2. The stub executes routines in the JAX-RPC Runtime System (RS).
        3. That RS converts the request into a SOAP message.
        4. RS transmit the message as an HTTP request.

        Advantages of JAX-RPC

        1. Can be used any language (Platform independent)
        2. Java or non-Java clients can access the web service.
        3. Hides the complexity of SOAP messages from developer.
        4. Highly flexible, because JAX-RPC uses technologies defined by W3C.

        SAAJ (SOAP with Attachment API for Java)


        This is used to transport SOAP messages over the internet. Developers can send and receive SOAP messages in the Java platform using SAAJ. Developers can use it to write SOAP messaging applications instead of using JAX-RPC.


        JAXB (Java API for XML Binding)


        This API is used to map XML document to Java object. This allows you to develop applications that creats Java object which map to an XML document. This allows you to work with XML data using OO (Object Oriented) technologies without knowing the underlying structure of XML document.









        Introduction to JAXP

        What is JAXP ?


        JAXP, "Java API for XML Processing" is a one of Java APIs. This is used to to process XML data which is used by applications written in Java. Using JAXP, you can define your data as a stream  of events using SAX (Simple API for XML) or as a tree of objects using DOM (Document Object Model). JAXP also supports the XSLT (XML Style sheet Transformation) standards. This allows you to transform XML data into other data formats like HTML (Hyper Text Markup Language) or WML (Wireless Markup Language). 





        As you can see JAXP consist of three APIs
        1. SAX
        2. DOM
        3. StAX
        Later on we discuss about these three APIs.

        Packages of JAXP

        There are five libraries defined by XML-DEV group and W3C.

        1. javax.xml.parsers     - Provide a common interface for diffrent vendor's SAX & DOM parses
        2. org.w3c.dom           - Define the document and other classes for DOM
        3. org.xml.sax              - Defines the basic SAX APIs 
        4. javax.xml.transform - Defines the XSLT APIs
        5. javax.xml.stream     - Provides StAX-specific transformation APIs.







        Monday, July 14, 2014

        Translation process

        Now you are getting into the core of JSP. I think you have a little bit of idea about JSP life circle. In the processing time it is converted to the servlet and do the task and again converted to the JSP file. In this case you have to understand some translation parts of that process. 




        Order of declaration 

        In other programming language you have to think about the order of variables and methods. You are not allowed to use variable without any initialization. But in JSP you need not to worry about the order. Because it changes to servlet during the process. 

        <html>
        <body>
        
        Now your age : <%=age%>
        <br>
        After five years you age : <%=age + 5%>
        
        <%! int age=20; %>
        
        </body>
        </html>
        
        

        Variable initialization 

        In JSP you need not to worry about initialize variables. If you declare them in declaration tag, these variables are initialized to their default values. But if you declare these variables in scriptlet tag, you must initialized them before use. Look at the following example.

        <html>
        <body>
        
        <%! int x; %>
        <%  int y; %>
        
        i : <%= x+1 %>
        j : <%= j+1 %>
        
        </body>
        </html>
        
        

        When you run this, you will be able to see a error message like this. Because I have declare x in declaration tag. But j in scriptlet tag.


        Then you can comment 8th line (j : <%= j+1 %>) and run this. It works.


        Flow control


        In JSP it allows you to get easier your code with conditional and iterative statements. You can use HTML codes within JSP codes instead of using multiple out.println() statements. Look at the following programs to understand.

        First program

        <html>
        <body>
        
        <%  int x = 10;
         if(x==10){
        %>
          <h1>Success</h1>
        <% 
         }
         else{
        %>
          <h1>Fail</h1>
        <%
         }
        %>
        </body>
        </html>
        
        

        Second program

        <html>
        <body>
        
        <%  int x = 10;
         if(x==10){
          out.println("<h1>Success</h1>");
         }
         else{
          out.println("<h1>Fail</h1>");
         }
        
        %>
        </body>
        </html>
        
        



        As you can see both of the programs are doing same thing using IF-ELSE statement. In this program you need to worry, because it has a simple code. But if you have a big code(multiple HTML codes) to execute, it is not easy to use multiple out.println() statements. At that time you can use HTML codes within JSP syntax.


        Escape characters 


        In JSP you can have several places that escape characters are used.  

        1. Within attribute
        2. Within scriptlet field
        3. Within text field
        If you know how to use escape characters in Java, this is also very simple to understand. Following example demonstrate how to use escape characters in mentioned three types.

        Within attribute

        <%@ page info="Using ', \", \\, <\%, and %\> in JSP. " %>
        <html><body>
        <%= getServletInfo() %>
        </body></html>
        
        

        Within scriptlet field

        <html><body>
        <%= "Opening tag of a scriptlet <%" %>
        </br>
        <%= "Closing tag of a scriptlet %\>" %>
        </body></html>
        
        
        Within text field

        <html><body>
        The opening tag of a scriptlet <\%
        </br>
        The closing tag of a scriptlet %>
        </body></html>
        
        
















        Saturday, July 12, 2014

        SOAP ( Simple Object Access Protocol )





        In this post I'm going through SOAP web service with a quick introduction and basics about SOAP.


        What is a web service ?

        Web services are services which are used to communicate over HTTP(Hyper Text Transfer Protocol). These web services are used to communicate between different programs in different platforms which are developed by using different languages. So Web services are very important now a days.

        What is SOAP ?

        • Simple Object Access Protocol (Protocol is a set of rules & regulations).
        • SOAP is a communication protocol.
        • The base of SOAP is; make data available as services. 
        • SOAP is based only on XML.
        • This is platform / language independent.
        • SOAP is designed for data communication via internet.

        Image resource - http://feather.elektrum.org/

        Versions of SOAP

        • 1.1 version (default version)
        • 1.2 version (current version)

        Why SOAP 1.2 ?

        • SOAP version 1.2 is much faster that 1.1 version.
        • Cleaner than 1.1 version
        • Better web integration
        • More versatile (More about SOAP 1.2)

        SOAP Message

        SOAP message is simply like a ordinary XML document. It consist of four parts.
        1. Envelope (mandatory) - Define the scope of the SOAP message
        2. Header (optional) - Optional attributes used in processing the message
        3. Body (mandatory) - XML data
        4. Fault (optional) - Optional fault element provide information about errors
        You can understand about the syntax from following example code. It is just like a envelop with a letter.

        <?xml version="1.0"?>
        <soap:Envelope
        xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
        soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
        
        <soap:Header>
        ...
        </soap:Header>
        
        <soap:Body>
        ...
          <soap:Fault>
          ...
          </soap:Fault>
        </soap:Body>
        
        </soap:Envelope>
        

        xmlns:soap Namespace

        This should be definitely http://www.w3.org/2001/12/soap-envelope 

        soap:encodingStyle

        This attribute defines the data type which is used in the document


        Example SOAP message

        SOAP request 

        POST /InStock HTTP/1.1
        Host: www.website.com
        Content-Type: application/soap+xml; charset=utf-8
        Content-Length: nnn
        
        <?xml version="1.0"?>
        <soap:Envelope
        xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
        soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
        
        <soap:Body xmlns:m="http://www.website.com/user">
          <m:GetUsername>
            <m:userName>Ann</m:userName>
          </m:GetUsername>
        </soap:Body>
        
        </soap:Envelope>
        
        


        SOAP Response 


        HTTP/1.1 200 OK
        Content-Type: application/soap+xml; charset=utf-8
        Content-Length: nnn
        
        <?xml version="1.0"?>
        <soap:Envelope
        xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
        soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
        
        <soap:Body xmlns:m="http://www.website.com/user">
          <m:GetUsernameResponse>
            <m:surName>Carolyn</m:surName>
          </m:GetUsernameResponse>
        </soap:Body>
        
        </soap:Envelope>
        
        

        Advantages of SOAP

        • Well structured and formal
        • Work with any communication protocol
        • Integrated security and authentication. 

        Disadvantages of SOAP

        • SOAP is slow, because it uses XML meta data. Then it gets a lot of time to read them.
        • Uses a lot of bandwidth.
        • You can use XML only

        When to use SOAP ?

        • Payment gateways
        • Commercial and financial services
        • Telecommunication services 

        SOAP clients

        • PayPal SOAP API