Saturday, 7 February 2015

Spring - Introduction

Spring is an open source and  lightweight framework, initial version released in October 2002 by Rod Johnson and his team with following features.

Modular

     We can use the needed spring features in our application. It means like we can use spring IOC alone in our application or spring integration for integrating technique or spring MVC like this.

Non-Intrusive

     Because of Non-Intrusive, the application code need not to be extended with any spring framework class to get the features unlike in struts we should extend the Action class to create our controller class.




Thursday, 15 January 2015

Friday, 9 January 2015

JSF Life Cycles

Restore view phase
Apply request values
Process validations
Update Model values
Invoke application
Render Response

Restore view phase

Here JSF creates the FacesContext object and stores view information in this object.


Apply request values

Sunday, 4 January 2015

Java - SAX - Examples

Example 1


Create one java project in eclipse and add the following program in your project.

The xmlfile1.xml should be placed under project. To do this Right Click on project name and paste the xmlfile1.xml.

SAXParser1

package org.chidams.sax;


import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
class SAXParser1
{
public static void main(String args[])
{
try
{
//javax.xml.parsers
SAXParserFactory spf=SAXParserFactory.newInstance();
//javax.xml.parsers
SAXParser parser=spf.newSAXParser();
MyDefaultHandler1 mdh=new MyDefaultHandler1();
FileInputStream is=new FileInputStream("xmlfile1.xml");
parser.parse(is,mdh);
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}

class MyDefaultHandler1 extends org.xml.sax.helpers.DefaultHandler
{
StringBuffer buffer=new StringBuffer();
public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException
{

System.out.println("startElement="+qName);
buffer.setLength(0);
}

public void characters(char ch[],int start,int end)
{

buffer.append(ch,start,end);
if (buffer.toString().length()!=0)
{
System.out.print("Value="+buffer.toString()+"\n");
}

}

public void endElement(String uri,String localName,String qName)throws org.xml.sax.SAXException
{

System.out.println("endElemnt="+qName);
buffer.setLength(0);
}
}

xmlfile1.xml

<?xml version="1.0"?>
<!--XMLTextWriter Example-->
<products>
<product>
<type>Keyboard</type>
<price>600.00</price>
<company>TVS</company>
</product>
<item>
<type>Monitor</type>
<price>6000.00</price>
<company>Samsung</company>
</item>

</products>

Output

startElement=products
Value=

startElement=product
Value=

startElement=type
Value=Keyboard
endElemnt=type
Value=

startElement=price
Value=600.00
endElemnt=price
Value=

startElement=company
Value=TVS
endElemnt=company
Value=

endElemnt=product
Value=

startElement=item
Value=

startElement=type
Value=Monitor
endElemnt=type
Value=

startElement=price
Value=6000.00
endElemnt=price
Value=

startElement=company
Value=Samsung
endElemnt=company
Value=

endElemnt=item
Value=


endElemnt=products


In output some values are empty and some values have the data. Can you understand why it is.


Java - Document Object Model - Examples

Example 1

Create one java project in eclipse and add the following program in your project.

The xmlfile2.xml should be placed under project. To do this Right Click on project name and paste the xmlfile2.xml.

XMLParserAttributesDemo2

package org.chidams.dom;
import javax.xml.parsers.*;
import java.io.*;
import org.w3c.dom.*;
public class XMLParserAttributesDemo2
{
public static void main(String[] args)
{
try
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
File file=new File("xmlfile2.xml");
Document doc=builder.parse(file);
Element root=doc.getDocumentElement();

//Prints the context node name
System.out.println(root.getNodeName());
System.out.println("============");

//To retrieve the nodes under context node.
NodeList nodelist=root.getChildNodes();

for (int i=0;i<nodelist.getLength();i++)
{
//To check whether the current node is element node or not
if (nodelist.item(i).getNodeType()==Node.ELEMENT_NODE)
{
//If element node, the Node object will cast to Element object.
//Because attributes can be printed by using Element object. So we
//cast Node object to Element object
Node subnode=nodelist.item(i);
System.out.println(subnode.getNodeName());
Element element=(Element)subnode;

//Finds the attributes of current node
NamedNodeMap map=element.getAttributes();
//NameNodeMap is the map of attributes of currentnode
for (int j=0;j<map.getLength();j++)
{
//Prints nodename, node value.
System.out.print(map.item(j).getNodeName());
System.out.print("=");
System.out.println(map.item(j).getTextContent());
}//inner
System.out.println("================");
}//if
}//outer for


}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}

xmlfile2.xml


<?xml version="1.0"?>
<!--XMLTextWriter Example-->
<employeedetails>
<employee name="Ramu" salary="1" dept="A"></employee>
<employee name="Ragav" salary="2" dept="B"></employee>
<employee name="Amar" salary="3" dept="C"></employee>
<employee name="Rani" salary="4" dept="D"></employee>
</employeedetails>

Output

employeedetails
============
employee
dept=A
name=Ramu
salary=1
================
employee
dept=B
name=Ragav
salary=2
================
employee
dept=C
name=Amar
salary=3
================
employee
dept=D
name=Rani
salary=4
================



Java - SAX (Simple API for XML)


SAX provides a different approach to parsing. Rather than creating a tree form an XML document like DOM.
A SAX parser reads through the file and notifies registered listeners when  certain parsing events occur. The events are as follows..
-         The beginning of a document.
-         Reading a start tag at the beginning of a new element
-         Reading an end tag at the end of an element.
-         Reading text in the body of an element.
-         Reading comments
-         Reaching the end of a document.


How SAX works?

If start tag is found in xml file, sax parser calls startElement() and characters().
If end tag is found in xml file, sax parser calls endElement() and characters().



Difference between SAX and DOM

DOM manages tree based technique to handle xml file.
SAX manages xml file, based on events. Whenever the event is occurred the corresponding method of DefaultHandler will be invoked. So developer must create the sub class of DefaultHandler class.



SAX Parser Program using xmlfile1.xml

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
class SAXParser1
{
public static void main(String args[])
{
try
{
//javax.xml.parsers
SAXParserFactory spf=SAXParserFactory.newInstance();
//javax.xml.parsers
SAXParser parser=spf.newSAXParser();
MyDefaultHandler mdh=new MyDefaultHandler();
FileInputStream is=new FileInputStream("xmlfile1.xml");
parser.parse(is,mdh);
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}

class MyDefaultHandler extends org.xml.sax.helpers.DefaultHandler
{
StringBuffer buffer=new StringBuffer();
public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException
{

System.out.println(qName);
buffer.setLength(0);
}

public void characters(char ch[],int start,int end)
{
buffer.append(ch,start,end);
if (buffer.toString().length()!=0)
{
System.out.print(buffer.toString());
}
}

public void endElement(String uri,String localName,String qName)throws org.xml.sax.SAXException
{

System.out.println(qName);
buffer.setLength(0);
}
}

Java - Document Object Model - Concepts

Document Object Model (DOM)

The DOM is the W3C (WWW Consortium) standard. 
DOM represents a XML document as a tree of nodes. 

The Document Object Model (DOM) is an application programming interface (API) which maps out an entire page as a document composed of a hierarchy of nodes. Each part of an HTML or XML page is a derivative of a node.

In java org.w3c.dom, javax.xml packages provide necessary classes and interface to manipulate XML file.

By using DOM to retrieve XML nodes we have to do following steps

1) Create the object for  javax.xml.parsers.DocumentBuilderFactory . It is the abstract class. Use static newInstance() of the DocumentBuilderFactory class to create an object for DocumentBuilderFactory.
2) After creating DocumentBuilderFactory, then you can create DocumentBuilder class object. It is also a abstract class. The object of DocumentBuilderFactory can be used to create DocumentBuilder class object. Use DocumentBuiler newDocumentBuilder() of DocumentBuilderFactory to create DocumentBuilder class object.
3) The final aim is that creating Document class object. Use Document parse(File) in DocumentBuilder class to create the object for Document class.
4) The Document interface is the sub interface of Node interface.

Object creation for Document interface

DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
File file=new File("xmlfile1.xml");            
Document doc=builder.parse(file);

Retrieving context node from xmlfile

Element root=doc.getDocumentElement();
System.out.println(root.getNodeName());


Creating NodeList object to retrieve the child nodes of context node

NodeList nodelist=root.getChildNodes();

Above nodelist refers the elements under context node.\

Consider following xmlfile.

xmlfile1.xml

<?xml version="1.0"?>
<!--XMLTextWriter Example-->
<products>
<product>
<type>Keyboard</type>
<price>600.00</price>
<company>TVS</company>
</product>
<item>
<type>Monitor</type>
<price>6000.00</price>
<company>Samsung</company>
</item>
</products>

Under <products> context node, there are two elements found.
Now NodeList object refers two elements.
How to know the count of children are referred by NodeList? Use int getLength() of NodeList
interface.

Node Interface
The basic unit of DOM is the node. Every thing in an XML document (individual elements, attributes in a start tag, comments, element text, and the document as the whole) is a node.

org.w3c.dom.Node Interface Important methods

NamedNodeMap getAttributes()
     if the node is an element Returns the attributes of this node, otherwise returns null.
NodeList getChildNodes()
         Returns the list of all child nodes.
Node getFirstChild()
         Returns the first child node or null, if this node isn’t an Element.
Node getLastChild()
         Returns the last child node or null, if this node isn’t an Element.
Node getNextSibling()
         Returns the next child of the parent or null if parent node is not an Element.
String getNodeName()
         Returns the name of node for following node types.
         Element
         Attribute
         Entity
       For unnamed types returning values listed below
         Text - #text
         CDataSection - #cdata-section
         Comment - #comment
int getNodeType()
         Returns node type as integer
         Node interface declares the constants to indicate node types.
String getNodeValue()
         For attributes and text type nodes returns the text, otherwise null.
String getTextContent()
         Returns text value associated with the current node.

XMLParserDemo2.java 
import javax.xml.parsers.*;
import java.io.*;
import org.w3c.dom.*;
class XMLParserDemo2
{
public static void main(String args[])
{
try
{
/* *********** Creating Document object ****************** */
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
File file=new File("xmlfile1.xml");             
Document doc=builder.parse(file);
/* *********************************** ****************** */


/* ****** Print context node name by using Element interface object **** */
Element root=doc.getDocumentElement();
System.out.println(root.getNodeName());
/* *********************************** ****************** */


System.out.println();

/* ****** Retrieve the child nodes under context node as NodeList object ** */
NodeList nodelist=root.getChildNodes();
/* *********************************** ****************** */


/* ****** Retrieve the child nodes referred by NodeList object ** */

for (int i=0;i<nodelist.getLength();i++)
{

/* ****** Retrieve the first child node of NodeList object ** */
Node n=nodelist.item(i);
if (n.getNodeType()==Node.ELEMENT_NODE)
{
System.out.println(n.getNodeName());
/* ****** Retrieve the child nodes referred by n. n is Node object ** */
NodeList nodelistchild=n.getChildNodes();

/* ****** to print the tag and values from xml file.** */
for (int j=0;j<nodelistchild.getLength();j++)
{
Node m=nodelistchild.item(j);
if (m.getNodeType()==Node.ELEMENT_NODE)
{
System.out.print(m.getNodeName()+"="); // Prints tag name
System.out.println(m.getTextContent()); // Prints value of tag.
}//inner if
}//inner for
System.out.println();
}//outer if
}//outer for
}//try
catch(Exception e)
{
e.printStackTrace();
}
}
}



Java - XML Handling


In java XML document can be read by using parser applications. The parser has an application programming interface that enables you to extract the elements you need without complexity of interpreting the input stream your self.


JAXP (Java API for XML Processing) is the technology which enables the development of DOM API and SAX API.

XML parsers are