Thursday, April 23, 2009

AJAX Using DOJO Tutorial

It is very simple to develope Ajax application with DOJO. There is no any need to use
ActiveXObject or XMLHttpRequest. Here I am going to show a very simple application.

1. Create one dynamic web project using your Eclipse IDE. (Say Project Name : Ajax_Dojo)
2. Write one servlet in that project (Say AdmissionEnquiry.java)
3. Write one jsp page inside WebContent (Say example1.jsp)
4. Copy dojo.js inside WebContent
5. Add any server like Apache or Jboss to your project
6. Run the application http://localhost:8080/Ajax_Dojo/example1.jsp

AdmissionEnquiry.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AdmissionEnquiry extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public AdmissionEnquiry() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
System.out.println("Entered Roll Number :: "+roll);
PrintWriter out = response.getWriter();
if(roll.equalsIgnoreCase("110")){
out.print("Binod Suman");
}
else if(roll.equalsIgnoreCase("120")){
out.print("Pramod Kumar");
}
else{
out.print("Roll Number not found");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

example1.jsp

<html><body onLoad="onLoad();"
><head>
<title>Ajax Dojo Example</title>
<script language="javascript" src="dojo.js"></script>
<script language="javascript">
dojo.require("dojo.io.*");
dojo.require("dojo.event.*");
function onLoad() {
var buttonObj = document.getElementById("myButton");
dojo.event.connect(buttonObj, "onclick", this, "onclick_myButton");
}
function onclick_myButton() {
var url2 = "http://localhost:8080/Ajax_Dojo/AdmissionEnquiry";
var bindArgs = {
url: url2,
error: function(type, data, evt){
alert(data); },
load: function(type, data, evt){
alert(data); },
mimetype: "text/plain",
formNode: document.getElementById("myForm") };
dojo.io.bind(bindArgs); }
</script>
</head>
<body>

<form id="myForm">
<h1>Find Student Name</h1>
<p> Enter Roll Number <input type="text" name="roll">
<input type="button" id="myButton" value="Submit"/>
</p>
</form>
</body>
</html>

During run the application, you will give roll number as input and you will get student Name.
Very simple ................ :)
Please give your comment to enhance this tutorial. ............ :)

Sunday, April 19, 2009

DOJO Tutorial

Dojo is a toolkit is an open source modular javaScript library. It used to ease the rapid development of Ajax based web application. First you have to download dojo.js from dojotoolkit.org .
1. Create one dynamic web project in Eclipse IDE. (Say Project Name Dojo_Demo)
2. Put the downloaded dojo.js into WebContent folder of project. (Location C:\DOJO_workspace\Dojo_Demo\WebContent\demo.jsp, here C:\DOJO_workspace is project path).
3. Create one demo.jsp in same locatoin i.e. WebContent

demo.jsp

<html>
<head>
<title>Binod Java Solution</title>
<script type="text/javascript">
dojo.require("dojo.event.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.widget.Button");
function buttonCheck() { alert('YOU PRESSED OK BUTTON'); }
function init() {
var helloButton = dojo.widget.byId('button_first');
dojo.event.connect(helloButton, 'onClick')
}
dojo.addOnLoad(init); </script>
</head>
<body bgcolor="#FFFFCC">
<p align="center"><font size="6" color="#800000">Welcome to http://binodsuman.blogspot.com</font></p>
<button dojoType="Button" widgetId="button_first" onClick="buttonCheck();">OK BUTTON</button>
<br>
</body>
</html>

Add any web server (like Tomcat5.5) to your project then add Dojo_Demo project to server and start the server
Run http://localhost:8080/Dojo_Demo/demo.jsp
You will get dojo button, click and get your result. ........ :) So simple
Please give your comment, if you have any idea to enhance this tutorial ........ :)

Sunday, April 12, 2009

XML to PDF tutorial

To transfer xml information to pdf (create pdf file from xml file)
FOP : Formatting Objects Processor is an open source Java API that can convert your XML data into reports in PDF format.
1. Download fop from apache binary version
2. Unzip file and copy any drive say c:\fop-0.95-bin and add this path to your system environment path.
3. student.xml (c:\pdf\student.xml)
4. student.xsl (c:\pdf\student.xsl)
5. use command (c:\pdf> fop -xml student.xml -xsl student.xsl -pdf student.pdf)
You will get one student.pdf file. Very easy

Student.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<StudentRecord>
<Student>
<name>Manish</name>
<roll>130</roll>
<country>India</country>
<company>Infosys</company>
</Student>
<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>
<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>
</StudentRecord>

student.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format%22&gt;
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">

<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format%22&gt;
<fo:simple-page-master master-name="first"
page-height="29.7cm"
page-width="21cm"
margin-top="1cm"
margin-bottom="2cm"
margin-left="2.5cm"
margin-right="2.5cm">

<fo:region-body margin-top="3cm"/>
<fo:region-before extent="3cm"/>
<fo:region-after extent="1.5cm"/>
</fo:simple-page-master>
</fo:layout-master-set>

<fo:page-sequence master-reference="first">
<fo:static-content flow-name="xsl-region-before">
<fo:block line-height="14pt" font-size="10pt"
text-align="end">By Binod</fo:block>
</fo:static-content>
<fo:static-content flow-name="xsl-region-after">
<fo:block line-height="14pt" font-size="10pt"
text-align="end">Page <fo:page-number/>
</fo:block>
</fo:static-content>

<fo:flow flow-name="xsl-region-body">
<fo:block font-size="18pt"
font-family="sans-serif"
line-height="24pt"
space-after.optimum="15pt"
background-color="blue"
color="white"
text-align="center"
padding-top="3pt">
STUDENT EMPLYOEE REPORT
</fo:block>

<fo:block font-size="16pt"
font-family="sans-serif"
space-after.optimum="15pt"
text-align="center">
ADMS JAVA AND CS DEPARTMENT
</fo:block>

<fo:block text-align="start">This is based on the performance. </fo:block>

<fo:table table-layout="fixed" width="100%" border-collapse="separate">
<fo:table-column column-width="50mm"/>
<fo:table-column column-width="50mm"/>
<fo:table-column column-width="50mm"/>
<fo:table-body>
<fo:table-row color="red">
<fo:table-cell><fo:block>NAME</fo:block></fo:table-cell> <fo:table-cell><fo:block>ROLL</fo:block></fo:table-cell> <fo:table-cell><fo:block>COMPANY</fo:block></fo:table-cell> </fo:table-row>
<fo:table-row color="red">
<fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> <fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> <fo:table-cell><fo:block>------------------</fo:block></fo:table-cell> </fo:table-row>

<xsl:for-each select="StudentRecord/Student">
<xsl:sort select="name"/>
<fo:table-row>
<fo:table-cell><fo:block><xsl:value-of select="name"/></fo:block></fo:table-cell>
<fo:table-cell><fo:block><xsl:value-of select="roll" /></fo:block></fo:table-cell>
<fo:table-cell><fo:block><xsl:value-of select="company" />
</fo:block>
</fo:table-cell>
</fo:table-row>
</xsl:for-each>
</fo:table-body>
</fo:table>
</fo:flow>
</fo:page-sequence>
</fo:root>
</xsl:template>
</xsl:stylesheet>

Now you will feel that it is very job to develop PDF from XML. :)

How to backup of your blog

Please visit my other blog
http://binodjava.blogspot.com/2009/05/how-to-backup-of-your-blogger-blog.html

Thanks,

Binod Suman

Monday, April 6, 2009

XSLT tutorial using Java and XML

Extensible Stylesheet Language Transformations (XSLT)
XSLT provides a framework for transforming the structure of anXML document. XSLT combines an input XML document with an XSLstylesheet to produce an output document like HTML, PDF ...........
An XSL stylesheet is a set of transformation instructions for convertinga source XML document to a target output document. It requires an XSLT-compliant processor. The most popular open source XSLTengine for Java is the Apache Software Foundation’s Xalan project.
Here I am going to transform our student record into HTML for rendering purpose.

1. First add jar xml-apis.jar (Google and download)
2. student.xml
3. student.xsl
4. XMLToHTML.java

student.xml
<?xml version="1.0" encoding="ISO-8859-1"?>StudentRecord>
<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>

<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>

<Student>
<name>Manish</name>
<roll>130</roll>
<country>India</country>
<company>Infosys</company>
</Student>

</StudentRecord>

student.xsl

<?xml version="1.0" encoding="ISO-8859-1"? >
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform;
<xsl:template match="/">
<html> <body>
<h2>STUDENT RECORDS</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Name</th>
<th align="left">Roll</th>
</tr>

<xsl:for-each select="StudentRecord/Student">
<tr>
<td> <xsl:value-of select="name" /> </td>
<td> <xsl:value-of select="roll" /> </td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XMLToHTML.java


import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class XMLToHTML {

public static void main(String[] args) throws Exception {
File xmlFile = new File("src\\student.xml");
File xsltFile = new File("src\\student.xsl");
Source xmlSource = new StreamSource(xmlFile);
Source xsltSource = new StreamSource(xsltFile);
TransformerFactory transFact = TransformerFactory.newInstance();
Transformer trans = transFact.newTransformer(xsltSource);
//trans.transform(xmlSource, new StreamResult(System.out));
trans.transform(xmlSource, new StreamResult(new FileOutputStream("test.html")));
System.out.println("** HTML CREATED **");
}
}

After run the application, you will get new test.html file created in root folder of this application.

Interesting Note: Even witthout create html file, you can view xml in html formate in internet explorer. Without change any thing just do double click on student.xml, it will open in internet explorer like xml file.
Now add the XSN file infomation in XML then try to open XML file. You will get html formate.
How to add XSN information in XML file

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<StudentRecord>
<Student>
<name>Manish Kumar</name>
<roll>110</roll>
<country>India</country>
<company>Satyam Computers</company>
</Student>
<Student>
<name>Pramod Kumar</name>
<roll>120</roll>
<country>India</country>
<company>Patni Computers</company>
</Student>
<Student>
<name>Binod Kumar Suman</name>
<roll>130</roll>
<country>India</country>
<company>Satyam Computer Service Ltd</company>
</Student>
</StudentRecord>

Now you try to open this xml, it would be open in html formate as per the xsn.
Both student.xml and student.xsl should be in the same folder.

How to Filter Output in XSLT

You can give condition to the output from XML by adding these conditions :

1. =
2. !=
3. < less than
4. > greater than
5. element

student.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform; <xsl:template match="/"> <html>
<body>
<h2>STUDENT RECORDS</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th align="left">Name</th>
<th align="left">Roll</th>
<xsl:for-each select="StudentRecord/Student[name='Binod Kumar Suman']">
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" />
</td> </tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Now you can run java program, you will get html file. In that file you will get only given student name output.
Second filter : Show only student record, whose roll number is greater than 115.

<xsl:for-each select="StudentRecord/Student">
<xsl:if test="roll > 115">
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" />
</td> </tr>
</xsl:if>
</xsl:for-each>

Now you can also sorting of your output
<xsl:for-each select="StudentRecord/Student">
<xsl:sort select="name"/>
<tr> <td>
<xsl:value-of select="name" />
</td> <td>
<xsl:value-of select="roll" /> </td>
</tr>
</xsl:for-each>

Actually there are many different ways to show xml file in formatted style using xslt
1. Using xsl file reference in xml file and open in internet browser (described above) that file is called XHTML file.
2. Using java Srcipt
How to use Java Script to show xml information in formated way as defined in xsl file
(A.) create xml file (Student.xml) as above
(B.) create xsl file (student.xsl) as above
(C.) create html file (test.htm) as below

test.htm

<html><body>
<script type="text/javascript">
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.load("student.xml")
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.load("student.xsl")
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

Now open test.htm file in internet browser.

Saturday, April 4, 2009

Add Header and Footer to PDF

Before start to work out on this topic. I want to give some concept regarding iText PDF.

1. onStartPage() : It is auto triggerd method when new page started. If pdf has 10 page then it would be execute 10 times. Used this method to initializing variable or setting parameter. But it is not right place add Header and Footer.

2. onEndPage() : It is also auto triggered method during before starting a new page. This is right place to add Header and Footer.


To use these method, class should be extended by com.lowagie.text.pdf.PdfPageEventHelper;


HeaderAndFooter.java


import java.io.FileOutputStream;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfAction;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfWriter;
public class HeaderAndFooter extends PdfPageEventHelper{


protected Phrase header;
protected PdfPTable footer;


public static void main(String[] args) {
new HeaderAndFooter().createPDF();
System.out.println("** PDF CREATED **");
}
public void createPDF() {
Document document = new Document();
try{
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("Header_Footer_Example.pdf"));
writer.setPageEvent(new HeaderAndFooter());
document.open();
for(int i=0;i<1000;i++){
document.add(new Phrase("BINOD KUMAR SUMAN "));
}
document.close();
}catch(Exception e){
}
}
public HeaderAndFooter() {
header = new Phrase("**** THIS IS HEADER PART OF THIS PDF ****");
footer = new PdfPTable(1);
footer.setTotalWidth(300);
footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
footer.addCell(new Phrase(new Chunk("**** THIS IS FOOTER PART OF THIS PDF ****")
.setAction(new PdfAction(PdfAction.FIRSTPAGE))));
}
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(document.right() - document.left()) / 2+ document.leftMargin(), document.top() + 10, 0);

footer.writeSelectedRows(0, -1,(document.right() - document.left() - 300) / 2+ document.leftMargin(), document.bottom() - 10, cb);
}
}


Here one problem is that header will start from first page itself. If you want that header should come from second page. Then you have to put one condition like this

if (document.getPageNumber() > 1) {ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header,(document.right() - document.left()) / 2+ document.leftMargin(), document.top() + 10, 0);}

Friday, April 3, 2009

How to insert IMAGE in PDF using iText

On assuming that you should have one jpg image in the same folder. In this example I kept Binod_Flex.jpg in the same folder where this java file present.
Demo.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document d = new Document (PageSize.A4);
try {
PdfWriter.getInstance(d, new FileOutputStream("sample.pdf"));
d.open ();
d.addCreator("Binod by Demo.java");
d.addAuthor("Binod Suman");
d.addTitle("First PDF By Binod");
Image image = Image.getInstance("Binod_Flex.jpg");
image.scaleAbsolute(300,300);
d.add(image);
d.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}

You can now check that one PDF generated with specify image.

To change PDF page background color, use this

Rectangle pageSize = new Rectangle(400,400);
pageSize.setBackgroundColor(new java.awt.Color(0xDF,0xCC,0xFF));
Document d = new Document (pageSize);
and remaining same.

Insert table in PDF,


PdfPTable table=new PdfPTable(2);
table.addCell("Student Name");
table.addCell("Roll No.");
table.addCell("Binod");
table.addCell("110");
table.addCell("Pramod");
table.addCell("120");
d.add(table);

Insert Header in table in PDF


PdfPTable table=new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Paragraph("Student Details"));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(new Color(20,105,160));
cell.setColspan(2);
table.addCell(cell);
table.addCell("Student Name");
table.addCell("Roll No.");
table.addCell("Binod");
table.addCell("110");
table.addCell("Pramod");
table.addCell("120");
d.add(table);

How to generate PDF report from Java

1. Download iText-2.1.5.jar (You can google and get it)
2. Demo.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class Demo {
public static void main(String[] args) {
new Demo().createPDF();
}
public void createPDF(){
Document d = new Document (PageSize.A4);
try {
PdfWriter.getInstance(d, new FileOutputStream("sample.pdf"));
d.open ();
Paragraph p = new Paragraph ("Binod Kumar Suman,\n Bangalore, India");
d.add (p);
d.close ();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
System.out.println("******** PDF Created ***************");
}
}

Now check, you will get one pdf file sample.pdf

XPATH Java simple example

XPath is used to search any node any element in XML file. ---- very basic defination.

XPath is a fourth generation declarative language for locating nodes in XML documents. This is much more robust than writing the detailed search and navigation code yourself using DOM, SAX, or JDOM. using XPath in a Java program is like using SQL in a Java program. To extract information from a database, you write a SQL statement indicating what information you want and you ask JDBC to fetch it for you. You neither know nor care how JDBC communicates with the database. Similarly with XML, you write an XPath expression indicating what information you want from an XML document and ask the XPath engine to fetch it, without concerning yourself with the exact algorithms used to search the XML document.

1. Suppose I have persons.xml
<?xml version="1.0" ?>
<information>
<person id="1">
<name>Binod</name>
<age>24</age>
<gender>Male</gender>
</person>

<person id="2">
<name>Pramod</name>
<age>22</age>
<gender>Male</gender>
</person>

<person id="3">
<name>Swetha</name>
<age>19</age>
<gender>Female</gender>
</person>
</information>

2. XPathJavaExample.java

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathJavaExample {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//person/*/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
}
}

The output of this xpath query ("//person/*/text()");
Binod
24
Male
Pramod
22
Male
Swetha
19
Female

XPathExpression expr = xpath.compile("//person[last()]/*/text()"); This will be give the last record
Swetha
19
Female

XPathExpression expr = xpath.compile("//person/name/text()"); Here name is mentioned instaed of *. * means all the attribute. The output
Binod
Pramod
Swetha
Only name shows here.

XPathExpression expr = xpath.compile("//person[1]/*/text()"); Retrive first record
Binod
24
Male

XPathExpression expr = xpath.compile("//name/text()"); It will show all the name tag, that would be anywhere in xml. The output
Binod
Pramod
Swetha

XPathExpression expr = xpath.compile("//person[age>20]/*/text()"); Output would be
all age that is greater than 20
Binod
24
Male
Pramod
22
Male


There are numbers of xpath expression. You can get from google. Here I showed only few of them. But it is easy to understand .......... :)