Wednesday, October 7, 2009

First EJB3.0 example, EJB3.0 tutorial, @EJB not working

Here I am putting very easy example for EJB3.0. It has Session Bean, Entity Bean and JPA example. All these examples are in very step wise. I have used glassfish application server. For other application server I was getting error when I used @EJB. So decided to use glassfish application server.

1. Install glassfish-tools-bundle-for-eclipse-1.1.exe
2. start -> All Program -> GlassFish tool bundle for eclipse 1.1 -> GlassFish tool bundle for eclipse
3. File -> New Project -> EJB
4. Put name of Project say school -> click on add project to EAR say SchoolEAR
5. File -> New Project -> Dynamic Web Project -> Put name of Project say schoolWEB -> click on add project to EAR say SchoolEAR
6. Click on SchoolWEB -> Webcontent -> Right click and create one JSP page say search.jsp

search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green"><h1> ABC SCHOOL </h1>
<table align="center">
<tr><td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td><input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</body>
</html>

7. Go to Server Pan and start server (Bundled GlassFish V2.1)
8. Add project SchoolEAR to server
9. Run http://localhost:8082/SchoolWEB/search.jsp (Just for test whether page is coming) now you should able to see the search page in your browser.

Now Add one servlet:
1. Go to School Project -> ejbModule -> create Servlet -> put Package Name: com and classname: SearchServlet -> Finish
2. SearchServlet.java

package com;
import java.io.IOException;
import javax.ejb.EJB;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SearchServlet()
{ super();
System.out.println("SearchServlet IS CALLING");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS DO POST METHOD");
}
}

3. Your web.xml of SchoolWEB should be like this: (Path C:\GlassFish_Workspace\EJB3\Practice_1\SchoolWEB\WebContent\WEB-INF\web.xml)
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SchoolWEB</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>SearchServlet</display-name>
<servlet-name>SearchServlet</servlet-name>
<servlet-class>com.SearchServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SearchServlet</servlet-name>
<url-pattern>/SearchServlet</url-pattern>

</servlet-mapping>
</web-app>

NOTE: One problem with this version of Glassfish that every time when you change code you have to clean your project and restart server. :(

4. Change little bit your JSP code to call this new servlet.
Search.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Search Page</title>
</head>
<body bgcolor="green">
<h1> ABC SCHOOL </h1>
<form action="SearchServlet">
<table align="center"><tr>
<td>Enter Student Roll </td><td><input type="text" name="roll"></td>
</tr><tr><td>
<input type="submit" name="searchStudent" value="Search""></td>
</tr>
</table>
</form>
</body>
</html>

5. Clean your all project and restart the servercall on browser: http://localhost:8082/SchoolWEB/search.jsp
Put some roll number and see the server log file (say entered 110)you should get the output like INFO: THIS IS SEARCH SERVLETINFO: Roll Entered :: 110

Now add Session Bean: [IMPORTANT]
1. Click on School project -> ejbModule -> Right click -> New -> Interface -> package com and class name: ISearchBean

ISearchBean.java
package com;
public interface ISearchBean {
public String search(int roll);
}
2. Click on School project -> ejbModule -> Right click -> New -> SessionBean -> package com and class name: SearchBean
SessionType: StatelessSearchBean.java

package com;
import javax.ejb.Stateless;
@Statelesspublic class SearchBean implements ISearchBean{
public SearchBean() { }
@Override
public String search(int roll) {
if(roll == 110){ return "Binod Kumar Suman"; }
return "Name does not match";
}
}

Note: You used here first EJB annotation @Stateless :)
3. Change servlet to call this session bean with use of @EBJ annotation

SearchServlet.java
package com;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ISearchBean searchBean;

public SearchServlet() {
super();
System.out.println("SearchServlet IS CALLING");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
if(searchBean == null){ System.out.println("SearchBean is still null"); }
else{ System.out.println("Search Bean is working fine");
System.out.println("Result :: "+searchBean.search(roll)); }
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
}

4. Now run the jsp file from browser:http://localhost:8082/SchoolWEB/search.jsp
Put roll number 110and check server output:
INFO: SearchServlet IS CALLINGINFO: THIS IS SEARCH SERVLET
INFO: Roll Entered :: 110
INFO: Search Bean is working fine
INFO: Result :: Binod Kumar Suman

*********** NOW ADD JPA Persistence part *****************
Now we will see how to save data using EJB3.0 JPA (Plesae get introduction of EJB3.0 JPA from this URL http://binodsuman.blogspot.com/2009/10/jpa-introduction-what-is-jpa-java.html)
1. To use JPA in EJB3.0, you have to add persistence.xml in META-INF folder, thatshould have your database connection information.
2. Create one entity class say student
student.java in com.entity folder

package com.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "studentinfo")
public class Student {
private int roll; private String name; private String cell;
@Id
@Column(name="roll",unique=true,updatable=true)
public int getRoll() { return roll; }

public void setRoll(int roll) { this.roll = roll; }
@Column(name="sname",updatable=true)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCell() { return cell; }
public void setCell(String cell) { this.cell = cell; }

}
persistence.xml in (C:\GlassFish_Workspace\EJB3\Practice_1\School\ejbModule\META-INF\persistence.xml)
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0">
<persistence-unit name="student_unit" transaction-type="RESOURCE_LOCAL">
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>com.entity.Student</class>
<properties>
<property name="toplink.logging.level" value="FINEST" />
<property name="toplink.jdbc.driver" value="org.postgresql.Driver" />
<property name="toplink.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="toplink.jdbc.user" value="postgres" />
<property name="toplink.jdbc.password" value="suman" />
</properties>
</persistence-unit>
</persistence>

I have used here postgres sql, you can use any database.Create one table studentinfo
CREATE TABLE studentinfo(
roll int4 NOT NULL,
sname char(100),
cell char(15), CONSTRAINT "studentinfo_PK" PRIMARY KEY (roll)
)

Now change in SearchBean.java

package com;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.entity.Student;
@Stateless
public class SearchBean implements ISearchBean{
private static EntityManagerFactory emf;
private static EntityManager em;
public SearchBean() { }
@Override
public String search(int roll) {
if(roll == 110){ return "Binod Kumar Suman"; }
return "Name does not match";
}

@Override
public void saveStudent(Student student) {
System.out.println("IN SEARCH BEAN TO SAVE STUDENT RECORD");
try{
emf = Persistence.createEntityManagerFactory("student_unit");
em = emf.createEntityManager();
// Begin transaction
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
// Close this EntityManager
em.close();
System.out.println("***** RECORD SAVED SUCCESSFULLY ***************");
}
catch(Exception e){
System.out.println("SOME PROBLEM DURING SAVE STUDENT :: "+e);
e.printStackTrace(); }
}
}
And change in SearchServlet.java

package com;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.Student;

public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private ISearchBean searchBean;
public SearchServlet() {
super();
System.out.println("SearchServlet IS CALLING");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("THIS IS SEARCH SERVLET");
int roll = Integer.parseInt(request.getParameter("roll"));
System.out.println("Roll Entered :: "+roll);
if(searchBean == null){ System.out.println("SearchBean is still null"); }
else{ System.out.println("Search Bean is working fine");
System.out.println("Result :: "+searchBean.search(roll));
Student student = new Student();
student.setRoll(150);
student.setName("Manish");
student.setCell("12345678");
searchBean.saveStudent(student);
System.out.println("******** One record of Student has been saved ********");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("THIS IS DO POST METHOD"); }
}

Now you can http://localhost:8082/SchoolWEB/search.jsp and put any roll number. Onc student record would be saveed in database.
Easy ...................... :)

Sunday, October 4, 2009

JPA Introduction, What is JPA, Java Persistence API tutorial

Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data. One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications.

A fundamental question for many Java developers is "Why JPA? Why do I need to know how to use this API when object-relational mapping tools like Hibernate and Toplink are already available?" The answer is that JPA is not a new technology; rather, it has collected the best ideas from existing persistence technologies like Hibernate, TopLink, and JDO. The result is a standardized specification that helps you build a persistence layer that is independent of any particular persistence provider.

Although it all started with entity beans and is packaged with Java EE 5.0, JPA can be used outside the container in a Java SE environment.

What is JPA?
JPA is just an specification from Sun, which is released under JEE 5 specification. JPA standardized the ORM persistence technology for Java developers. JPA is not a product and can't be used as it is for persistence. It needs an ORM implementation to work and persist the Java Objects. ORM frameworks that can be used with JPA are Hibernate, Toplink, Open JPA etc.

These days most of the persistence vendors are releasing the JPA implementation of their persistence frameworks. So, developers can choose the best ORM implementation according to the application requirement. For example, production can be started from the free versions of ORM implementation and when the needs arise it can be switched to the commercial version of the ORM framework. You can switch the persistence provides without changing the code. So, ORM framework independence is another another big benefit of JPA.

Here are the benefits of JPA
1. Simplified Persistence technology
2. ORM frameworks independence: Any ORM framework can be used
3. Data can be saved in ORM way
4. Supported by industry leaders

ORM frameworks
Here are the list of ORM frameworks that can be used with JPA specification.
Hibernate
Toplink
iBatis
Open JPA

Why JPA?
1. JPA is standardized specification and part of EJB3 specification
2. Many free ORM frameworks are available with can be used to develop applications of any size 3. Application developed in JPA is portable across many servers and persistence products (ORM frameworks).
4. Can be used with both JEE and JSE applications
5. JSE 5 features such as annotations can be used
6. Both annotations and xml based configuration support
source: http://roseindia.net/jpa/jpa-introduction.shtml

The persistence.xml file is a standard configuration file in JPA. It has to be included in the META-INF directory that contains the entity beans. The persistence.xml file must define a persistence-unit with a unique name in the current scoped classloader. The provider attribute specifies the underlying implementation of the JPA EntityManager. In JBoss Application Server, the default and only supported / recommended JPA provider is Hibernate.
You do not have to specify the persistence provider if you’re using the default persistence provider integrated with your Java EE 5 container. For example, if you want Hibernate’s persistence provider in the JBoss Application Server or TopLink Essentials persistence provider with Sun GlassFish or the Oracle Application Server, you don’t have to define the provider element in persistence.xml. But if you decide to go with the EJB 3 persistence provider from the GlassFish project with either JBoss or Apache Geronimo, then you must specify the provider element as follows:

<provider>oracle.toplink.essentials.PersistenceProvider</provider>

Obviously this example specifies Oracle TopLink as the persistence provider; you can specify the provider element for Hibernate as follows:

<provider>org.hibernate.ejb.HibernatePersistence</provider>

This is helpful when using JPA outside the container.


Template of persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="pu1"> <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class>entity.Customer</class> <class>entity.Order</class> <properties> <property name="toplink.jdbc.driver" value="<database driver>"/> <property name="toplink.jdbc.url" value="<database url>"/> <property name="toplink.jdbc.user" value="<user>"/> <property name="toplink.jdbc.password" value="<password>"/> <property name="toplink.logging.level" value="INFO"/> </properties>
</persistence-unit>
</persistence>

Saturday, October 3, 2009

JPA example outside the container, jpa standalone application example

One simple JPA example outside the container

1. Create one java project in Eclipse (Say JAPDEMO)
2. Put toplink-essentials.jar and postgresql-8.1dev-403.jdbc2ee.jar in project (into classpath)
3. put Userinfo.java into JAPDEMO\src folder
4. put Client. java into JAPDEMO\src folder
5. put persistence.xml into JAPDEMO\src\META-INF folder.
6. Setup a database and make sure you can access it with the correct given information. I used Postgres SQL and I have put the jar for this database.I also used a simple "userinfo" table for my testing, columns: id, name, fullName, passwordinfo, email.

Userinfo.java
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Userinfo implements Serializable {
@Id
private int id;
private String email;
private String fullname;
private String passwordinfo;
private String name;
private static final long serialVersionUID = 1L;

public Userinfo() { super(); }
public int getId() { return this.id; }
public void setId(int id) { this.id = id; }
public String getEmail() { return this.email; }
public void setEmail(String email) { this.email = email; }
public String getFullname() { return this.fullname; }
public void setFullname(String fullname) { this.fullname = fullname; }
public String getPassword() { return this.passwordinfo; }
public void setPassword(String password) { this.passwordinfo = password; }
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
}

Client.java
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import oracle.toplink.essentials.ejb.cmp3.EntityManager;

public class Client {
public static void main(String[] args) {
EntityManagerFactory emf; emf = Persistence.createEntityManagerFactory("sumanunit", new java.util.HashMap());
EntityManager entityManager = (EntityManager) emf.createEntityManager(); entityManager.getTransaction().begin();
Userinfo user = new Userinfo();
user.setId(2);
user.setEmail("binod@abc.com");
user.setFullname("Binod Suman");
user.setPassword("minmax");
user.setName("Binod");
entityManager.persist(user);
entityManager.getTransaction().commit(); }
}

persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"> <persistence-unit name="sumanunit" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider>
<class>Userinfo</class>
<properties> <property name="toplink.logging.level" value="FINEST" />
<property name="toplink.jdbc.driver" value="org.postgresql.Driver" />
<property name="toplink.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="toplink.jdbc.user" value="postgres" />
<property name="toplink.jdbc.password" value="suman" />
</properties>
</persistence-unit>
</persistence>

compile the code and see the database with one new entry. :)





Thursday, August 13, 2009

How to convert number to word in java, Number to Word

Just use String().subString() method and you can develop java code to convert number to word. Like 12345678 to
one Crore twenty three Lakh forty five thousand six hundred seventy eight.


import java.text.DecimalFormat;

public class NumberToWord {
public static void main(String[] args) {
System.out.println(convert(12345678));
}
private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty", " fifty", " sixty", " seventy", " eighty", " ninety" };

private static final String[] numNames = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 < 20){ soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10;
soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) return soFar; return numNames[number] + " hundred" + soFar; }
public static String convert(long number) {
// 0 to 999 999 999 999
if (number == 0) { return "zero"; }
String snumber = Long.toString(number);
// pad with "0"
String mask = "000000000000"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number);
int hyndredCrore = Integer.parseInt(snumber.substring(3,5));
int hundredLakh = Integer.parseInt(snumber.substring(5,7));
int hundredThousands = Integer.parseInt(snumber.substring(7,9));
int thousands = Integer.parseInt(snumber.substring(9,12));
String tradBillions;
switch (hyndredCrore) { case 0: tradBillions = ""; break; case 1 : tradBillions = convertLessThanOneThousand(hyndredCrore) + " Crore "; break; default : tradBillions = convertLessThanOneThousand(hyndredCrore) + " Crore "; }

String result = tradBillions;
String tradMillions;
switch (hundredLakh) { case 0: tradMillions = ""; break; case 1 : tradMillions = convertLessThanOneThousand(hundredLakh) + " Lakh "; break; default : tradMillions = convertLessThanOneThousand(hundredLakh) + " Lakh "; }
result = result + tradMillions;
String tradHundredThousands;

switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1 : tradHundredThousands = "one thousand "; break; default : tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " thousand "; }
result = result + tradHundredThousands;

String tradThousand;
tradThousand = convertLessThanOneThousand(thousands);
result = result + tradThousand;return result.replaceAll("^\\s+", "").replaceAll("file://b//s%7B2,%7D//b", " "); }
}

Wednesday, July 8, 2009

How to delete recursively empty folder using java, Recursively Delete Empty Folders

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DeleteEmptyFolder {
public static void main(String[] args) throws IOException {
deleteEmptyFolders("C:\\temp");
}

public static void deleteEmptyFolders(String folderName) throws FileNotFoundException {
File aStartingDir = new File(folderName);
List<File> emptyFolders = new ArrayList<File>();
findEmptyFoldersInDir(aStartingDir, emptyFolders);
List<String> fileNames = new ArrayList<String>();
for (File f : emptyFolders) {
String s = f.getAbsolutePath(); fileNames.add(s);
}
for (File f : emptyFolders) {
boolean isDeleted = f.delete();
if (isDeleted) {
System.out.println(f.getPath() + " deleted");
}
}
}

public static boolean findEmptyFoldersInDir(File folder, List<File> emptyFolders) {
boolean isEmpty = false;
File[] filesAndDirs = folder.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
if (filesDirs.size() == 0) { isEmpty = true; }
if (filesDirs.size() > 0) {
boolean allDirsEmpty = true;
boolean noFiles = true;
for (File file : filesDirs) {
if (!file.isFile()) {
boolean isEmptyChild = findEmptyFoldersInDir(file, emptyFolders);
if (!isEmptyChild) { allDirsEmpty = false; }
}
if (file.isFile()) { noFiles = false; }
}
if (noFiles == true && allDirsEmpty == true) { isEmpty = true; }
} if (isEmpty) { emptyFolders.add(folder); }
return isEmpty;
}
}

How to get recursively listing all files in directory using Java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class AllFilesInFolder {
public static void main(String[] args) throws FileNotFoundException {
String folderName = "C:\\temp";
List<String> fileNames = getAllFiles(folderName);
System.out.println("All Files :: " + fileNames);
}

public static List<String> getAllFiles(String folderName) throws FileNotFoundException {
File aStartingDir = new File(folderName);
List<File> result = getFileListingNoSort(aStartingDir);
List<String> fileNames = new ArrayList<String>();
for (File f : result) {
String s = f.getAbsolutePath();
fileNames.add(s);
}

Collections.sort(result);
Collections.sort(fileNames);
return fileNames;
}

public static List<File> getFileListingNoSort(File aStartingDir) throws FileNotFoundException {
List<File> result = new ArrayList<File>();
File[] filesAndDirs = aStartingDir.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for (File file : filesDirs) {
if (!file.isDirectory()) result.add(file);
if (!file.isFile()) {
List<File> deeperList = getFileListingNoSort(file);
result.addAll(deeperList);
}
}
return result;
}
}

Monday, July 6, 2009

how to unzip file in java; Java Unzip file,

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class MakeUnZip {
public static void main(String argv[]) {
String zipFileName = "src\\myZip.zip";
unZip(zipFileName);
}

public static void unZip(String zipFileName) {
int BUFFER = 2048;
try {
BufferedOutputStream dest = null;
FileInputStream fileInputStream = new FileInputStream(zipFileName);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
ZipEntry zipEntry;
int count=0;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
System.out.println("Extracting File Name :: " + zipEntry);
count++; int length;
byte data[] = new byte[BUFFER];
FileOutputStream fileOutputStream = new FileOutputStream(zipEntry.getName());
dest = new BufferedOutputStream(fileOutputStream, BUFFER);
while ((length = zipInputStream.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, length);
}

dest.flush();
dest.close();
}

zipInputStream.close();
System.out.println("Total "+count+ " Files Unziped Successfully ");
} catch (Exception e) { e.printStackTrace(); }
}
}

Sunday, July 5, 2009

Get contents of a ZIP file in Java, how to get file names in zip file in java

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipFile;

public class ZipContents {
public static void main(String[] args) {
File zipFileName = new File("src\\myZip.zip");
getContentsInZip(zipFileName);
}

public static void getContentsInZip(File zipFileName){
try{ ZipFile zipFile = new ZipFile(zipFileName);
Enumeration em = zipFile.entries();
for (Enumeration enumer = zipFile.entries(); enumer.hasMoreElements();) {
System.out.println(enumer.nextElement());
}
}catch(IOException e){ e.printStackTrace(); }
}
}

How to make Zip file using Java, Creating a ZIP file in Java

To run this tutorial
1. Create one folder src
2. Put test1.txt and test2.txt in src folder.
3. After run this code, you will get myZip.zip file in src folder.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MakeZip {
public static void main(String[] args) {
String[] filesToZip = {"src\\test1.txt","src\\test2.txt"};
//String[] filesToZip = {"src\\test1.txt"};
String ZipedFileName = "src\\myZip.zip";
zipConversion(filesToZip, ZipedFileName);
}

public static void zipConversion(String[] files, String ZipedFileName){
byte[] buffer = new byte[1024];
try{
FileOutputStream outputFile = new FileOutputStream(ZipedFileName);
ZipOutputStream zipFile = new ZipOutputStream(outputFile);
for(int i=0;i<files.length;i++){
FileInputStream inFile = new FileInputStream(files[i]);
zipFile.putNextEntry(new ZipEntry(files[i]));
int length;
while ((length = inFile.read(buffer)) > 0) {
zipFile.write(buffer, 0, length); }

zipFile.closeEntry();
inFile.close();
}

zipFile.close();
System.out.println("Files Ziped Successfully");
}catch(IOException e){ e.printStackTrace(); }
}
}

You can either give one file to zip or any number of files in fileToZip string array.

Thursday, June 25, 2009

AJAX Program for Firefox, Ajax does not work with Firefox, Ajax not working in firefox but works with IE, Ajax for Mozilla

There are many questions are floating on internet that AJAX code doesnot work for Mozilla FireFox. And interesting there is no such exact solution for this. Some days back I have also posted one article on my blog regarding one simple tutorial on Ajax and it was very fine with IE. One day I got one comment that my tutorial is not working for Firefox. I asked this question to one of my friend and she gave the solution. Thanks MP.

Complete Example:

[Please follow my prior posting to setup this tutorial]

1. ShowStudentInfo.jsp (C:\Ajax_workspace\blog_demo\WebContent\ShowStudentInfo.jsp)
2. StudentInfo.java (C:\Ajax_workspace\blog_demo\src\StudentInfo.java) This is a servlet.

ShowStudentInfo.jsp

<html>
<head>
<title>Binod Java Solution AJAX</title>
<script type="text/javascript">
var request; function getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/blog_demo/StudentInfo?roll="+roll;

if(window.ActiveXObject){
request = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}

request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send(null);
}
function showResult(){
if(request.readyState == 4){
if ( request.status == 200 ) {
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
var student = students[0];

document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].childNodes[0].data;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].childNodes[0].data;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].childNodes[0].data;


}
}
}
</script>
</head>
<body>
<h2>GET STUDENT INFO</h2>
<br>
Enter Roll Number
<input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();" />
<br>
Name :
<span id="NamelH1"></span>
<br>
Hostel :
<span id="HostelH1"></span>
<br>
Contact :
<span id="ContactH1"></span>
<br>
</body>
</html>



StudentInfo.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 StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public StudentInfo() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
System.out.println(getResult(roll)); out.println(getResult(roll));
}
public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
} else{ name = "Roll Number not found"; }
String result = "<Students>";
result += "<Student>"; result += "<Name>" + name + "</Name>";
result += "<Hostel>" +hostel + "</Hostel>";
result += "<Contact>" +contact + "</Contact>";
result += "</Student>"; result += "</Students>";
return result;
}
}

This code also work well with IE.

Monday, June 22, 2009

How to read an XML file and extract values for the attributes using ANT script, XML Manipulation using XMLTask, XMLTASK example, Parse XML file in ANT

Parse XML file in ANT using XMLTASK

1. Write one ant script (xmlRead.xml)
2. Write one xml fiel (tests2.xml)
3. Download jar file (xmltask-v1.15.1.jar) from here and put in lib folder (c:\xmltask\lib)

1. xmlRead.xml (c:\xmltask\src)

<?xml version="1.0" encoding="UTF-8"?>
<project name="ReadXML" default="readXML">

<path id="build.classpath"><fileset dir="lib">
<include name="xmltask-v1.15.1.jar" />
</fileset>
</path>

<taskdef name="xmltask"classname="com.oopsconsultancy.xmltask.ant.XmlTask"
classpathref="build.classpath" />

<target name="readXML">
<xmltask source="tests2.xml">

<call path="/CHECK/TESTCASES/TESTCASE">
<param name="val" path="text()" />

<actions><echo>Test Case Details = @{val}</echo></actions>

</call>
</xmltask>

</target>
</project>

2. tests2.xml (c:\xmltask\src)

<?xml version="1.0" encoding="UTF-8"?>

<CHECK>

<TESTCASES>
<TESTCASE>ReceiveImageTest</TESTCASE>
<TESTCASE>ValidateImageTest</TESTCASE>
<TESTCASE>PublishImageTest</TESTCASE>
</TESTCASES>

<TESTCASES>
<TESTCASE>ReceiveImageTest2</TESTCASE>
<TESTCASE>ValidateImageTest2</TESTCASE>
<TESTCASE>PublishImageTest2</TESTCASE>
</TESTCASES>

</CHECK>

After run the build.xml, output would be

Buildfile: C:\xmltask\src\\xmlRead.xml
readXML:
[echo] Test Case Details = ReceiveImageTest
[echo] Test Case Details = ValidateImageTest
[echo] Test Case Details = PublishImageTest
[echo] Test Case Details = ReceiveImageTest2
[echo] Test Case Details = ValidateImageTest2
[echo] Test Case Details = PublishImageTest2
BUILD SUCCESSFULTotal time: 562 milliseconds

Sunday, June 21, 2009

How to parse XML file in ANT Script, read xml file in Ant, how to use <xmlproperty>

Some time we need to parse xml file using Ant script to run the java file or read some property value and more like this.
It is very easy, we can do this with tag called <xmlproperty>. This tag loads the xml file and it convert all the values of xml file in ant property value internally and we can use those value as ant property. For example :

<root>
<properties>
<foo>bar</foo>
</properties>
</root>

is roughly equivalent to this into ant script file as:
<property name="root.properties.foo" value="bar"/> and you can print this value with ${root.properties.foo}.

Complete Example:
1. Create one xml file say Info.xml
2. Create one ant script say Check.xml

Info.xml
<?xml version="1.0" encoding="UTF-8"?>
<Students>

<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<city> Bangalore </city>
</Student>

</Students>

Check.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="Check" default="init">
<xmlproperty file="Info.xml" collapseAttributes="true"/>

<target name = "init">
<echo> Student Name :: ${Students.Student.name} </echo>
<echo> Roll :: ${Students.Student.roll} </echo>
<echo> City :: ${Students.Student.city} </echo>
</target>

</project>

Now after run this (Check.xml) ant script, you will get output

Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Check.xmlinit:
[echo] Student Name :: Binod Kumar Suman
[echo] Roll :: 110
[echo] City :: Bangalore
BUILD SUCCESSFULTotal time: 125 milliseconds

It was very simple upto here, but if you have multiple records in xml (StudentsInfo.xml) then it will show all record with comma seperated like this

Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Check.xmlinit:

[echo] Student Name :: Binod Kumar Suman,Pramod Modi,Manish Kumar
[echo] Roll :: 110,120,130
[echo] City :: Bangalore,Japan,Patna

BUILD SUCCESSFULTotal time: 109 milliseconds

Now if you want to get indiviual data without comma seperation then we have to use <foreach> tag in ant script and for that we have to add one more jar file ant-contrib-0.6.jar in lib folder.

Complete Example:
1. One xml file say StudentsInfo.xml (C:\XML_Workspace\XML_ANT\src\StudentsInfo.xml)
2. One ant script say Binod.xml (C:\XML_Workspace\XML_ANT\src\Binod.xml)
3. Put jar ant-contrib-0.6.jar in C:\XML_Workspace\XML_ANT\lib, you can download from here.

StudentsInfo.xml
<?xml version="1.0" encoding="UTF-8"?>
<Students>

<Student>
<name>Binod Kumar Suman</name>
<roll>110</roll>
<city> Bangalore </city>
</Student>

<Student>
<name>Pramod Modi</name>
<roll>120</roll>
<city>Japan</city>
</Student>

<Student>
<name>Manish Kumar</name>
<roll>130</roll>
<city>Patna</city>
</Student>

</Students>

Binod.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="test" default="for-each">
<xmlproperty file="StudentsInfo.xml" collapseAttributes="true"/>

<target name="init">
<property name="ant-contrib.jar" location="C:/XML_Workspace/XML_ANT/lib/ant-contrib-0.6.jar"/>
<taskdef resource="net/sf/antcontrib/antcontrib.properties" classpath="${ant-contrib.jar}"/>
</target>

<target name="for-each" depends="init">
< echo> TEST FOR EACH </echo>
<foreach list="${Students.Student.name}" target="loop" param="var" delimiter=","/>
</target>

<target name="loop">
<echo message="Name :: ${var}"/>
</target>

</project>

After run the Binod.xml ant script, output will be

Buildfile: C:\XML_ANT_Workspace\XML_ANT\src\Binod2.xmlinit:for-each:
[echo] TEST FOR EACH loop:
[echo] Name :: Binod Kumar Sumanloop:
[echo] Name :: Pramod Modiloop:
[echo] Name :: Manish Kumar
BUILD SUCCESSFULTotal time: 219 milliseconds

How to run java class using ant script, getting started with ANT, ANT easy example with java

It is very easy to compile and run any java file using ANT Script.

1. Write one build.xml (Ant Sciprt)
2. Write one java file First.java
3. Ant jar file should in classpath
4. Java compiler should also in classpath

First.java (C:\AntExample\src\First.java)

public class First {
public static void main(String[] args) {
System.out.println("Fist Data :: "+args[0]);
System.out.println("Second Data :: "+args[1]);
}
}

build.xml (C:\AntExample\build.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project name="check" basedir="." default="execute">
<property name="build_dir" value="build/class"/>
<property name="src_dir" value="src"/>

<target name="init">
<echo> Build folder crateing .......... </echo>
<mkdir dir="${build_dir}"/>
</target>

<target name="build" depends="init">
<echo> Compilation going on .......... </echo>
<javac destdir="${build_dir}" srcdir="${src_dir}"/>
</target>

<target name="execute" depends="init,build">
<echo> Running java class ......... </echo>
<javaclassname = "First" classpath="${build_dir}">
<arg value="10"/>
<arg value="20"/>
</java>
</target>
</project>

Now run the ant scriptc:\AntExample> ant You will get output like this
Buildfile: C:\AntExample\build.xml
init:
[echo] Build folder crateing ..........
build:
[echo] Compilation going on ..........
execute:
[echo] Running java class .........
[java] Fist Data :: 10
[java] Second Data :: 20
BUILD SUCCESSFULTotal time: 468 milliseconds

You will get one build\class folder inside the AntExample folder having First.class file

Monday, June 15, 2009

JMS easy example, Get start with JMS, JMS tutorial, JMS easy code


JMS : Java Messaging Service

I was searching an easy and running example on JMS, but could not. I saw in many tutorial they explained in very hard manner to how to setup the administrative object to run the JSM example. But in real it is very easy.
Here I am using IBM Rational Software Architect (RSA) as Java IDE and WebSphere Application Server V6.1 that comes with RSA. [ Image Source ]
NOTE : If you want to execute this tutorial on RAD [IBM Rational Architect Developer] IDE then plesae click below link.

Just follows these step and your example will run:

1. start the server and go to admin console
2. Service Integration -> Buses -> New -> Give Bus Name: BinodBus ->
Next -> Finish
3. click on BinodBus -> In Topology Section, click on Bus Member -> Add -> next -> Chosse File Store -> next -> next -> Finish -> Save
4. Agin click on BinodBus -> In Destination Resource, click on Destination -> check Queue Type present or not. If not present then click on Next -> Choose Queue -> Next ->
put Identifier QueueDestination -> Next -> Finish -> Save
5. Open Resources Tree from left panel

6. click on JMS -> Connection Factories -> New -> Choose Default messaging provider -> OK -> Name -> BinodConnectionProvider ->
JNDI Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus ->
click on OK -> Save

7. From left side Resources -> JMS -> Queue -> New -> choose Default messaging provider -> OK ->
Name -> BinodQueue -> JNDI -> jms/BinodQueue -> Bus Name ->
BinodBus -> QueueName -> QueueDestination -> OK -> Save

[All the bold latter is Admin object name]

8. Restart the server.
9. Create one Dynamic Web Project (JMSSECOND)and Write two servlet to check the simple example

10. Write first servlet (ProducerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ProducerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("******** THIS IS MESSAGE PRODUCER SERVLET **********");
check();
}

public void check(){
System.out.println("********* Producer check **********");
String destName = "jms/BinodQueue";
final int NUM_MSGS = 5;
Context jndiContext = null;

try { jndiContext = new InitialContext(); }
catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

ConnectionFactory connectionFactory = null;
Destination dest = null;

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName); }
catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); e.printStackTrace(); System.exit(1);
}

Connection connection = null;
MessageProducer producer = null;
try {
connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(dest);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message from JMSSECOND DEMO " + (i + 1));
System.out.println("Sending message: " + message.getText());
producer.send(message);
}

producer.send(session.createMessage());
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

11. Write second servlet (ConsumerServlet.java)

import java.io.IOException;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConsumerServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("********** MESSAGE CONSUMER SERVLET 2 ************");
check();
}

public void check(){
System.out.println("********* Consumer check **********");
String destName = "jms/BinodQueue";
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination dest = null;
MessageConsumer consumer = null;
TextMessage message = null;
System.out.println("Destination name is " + destName);

try {
jndiContext = new InitialContext();
}catch (NamingException e) { System.out.println("Could not create JNDI API context: " + e.toString()); System.exit(1);
}

try {
connectionFactory = (ConnectionFactory) jndiContext.lookup("jms/BinodConnectionProvider");
dest = (Destination) jndiContext.lookup(destName);
} catch (Exception e) { System.out.println("JNDI API lookup failed: " + e.toString()); System.exit(1);
}

try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(dest);
connection.start();
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println("Reading message: " + message.getText()); }
else { break; }
}
}
} catch (JMSException e) { System.out.println("Exception occurred: " + e.toString()); }
finally { if (connection != null) { try { connection.close(); }
catch (JMSException e) { }
}
}
}
}

First run Producer Servlet:
http://localhost:9080/JMSSECOND/ProducerServlet
Output:

Sending message: This is message from JMSSECOND DEMO 1
Sending message: This is message from JMSSECOND DEMO 2
Sending message: This is message from JMSSECOND DEMO 3
Sending message: This is message from JMSSECOND DEMO 4
Sending message: This is message from JMSSECOND DEMO 5

Then run Consumer Servlet:
http://localhost:9080/JMSSECOND/ConsumerServlet
Output:


Reading message: This is message from JMSSECOND DEMO 1
Reading message: This is message from JMSSECOND DEMO 2
Reading message: This is message from JMSSECOND DEMO 3
Reading message: This is message from JMSSECOND DEMO 4
Reading message: This is message from JMSSECOND DEMO 5

Please put your comments. I am able to write this article after a lot struggle.
Source of example.

Saturday, June 13, 2009

How to read Excel file in Java using HSSF Jakarta POI

There are many way to read excel files in java

1. Using jexcelapi API that explained in previous post. (Only for .xls extenstion)
2. Using HSSF Jakarta POI, that will explain in this posting. (Only for .xls extenstion)

STEP1: Download poi-3.0-FINAL.jar from jakarta site or here.
SETP2: Write one Excel file say Binod2.xls
SETP3: Write ReadExcelFile.java
Both excel and java file should be in the same folder. Put poi-3.0-FINAL.jar in workspace.

ReadExcelFile.java

import org.apache.poi.hssf.usermodel.*;
import java.io.*;
import java.util.*;

public class ReadExcelFile {

public static void main(String[] args) throws Exception {
readWorkbook("Binod2.xls");
}

private static void readWorkbook(String filename) throws Exception {
InputStream input = new FileInputStream(filename);
HSSFWorkbook wb = new HSSFWorkbook(input);
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { HSSFSheet sheet = wb.getSheetAt(sheetIndex);
Iterator rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow row = (HSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
while (cellIter.hasNext()) {
HSSFCell cell = (HSSFCell) cellIter.next();
printCellValue(cell); }
}
} input.close();
}

private static void printCellValue(HSSFCell c) {
int cellType = c.getCellType();
if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) { System.out.println(c.getBooleanCellValue()); }
else if (cellType == HSSFCell.CELL_TYPE_STRING) { System.out.println(c.getRichStringCellValue().getString()); }
else if (cellType == HSSFCell.CELL_TYPE_FORMULA) { System.out.println(c.getCellFormula()); } else if (cellType == HSSFCell.CELL_TYPE_NUMERIC)
{ System.out.println(c.getNumericCellValue()); }
else if (cellType == HSSFCell.CELL_TYPE_ERROR)
{ System.out.println(c.getErrorCellValue()); }
}
}

How to read Excel file using Java (.xls extension)

** This tutorial will work only for Excel .xls (MS 2003) extension **

1. Download jexcelapi jxl.jar from here. This download contain full project, just take the jxl.jar file and put in your workspace.
2. Create one excel file say Binod.xls and put some data.
3. Write ExcelReader.java and put ExcelReader.java and Binod.xls both file is same folder.

ExcelReader.java

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ExcelReader {

public static void main(String[] args) throws IOException {
String fileName = "Binod.xls";
File file = new File(fileName);
ExcelReader excelReader = new ExcelReader(); excelReader.read(file);
}

public void read(File inputWorkbook) throws IOException {
Workbook workbook;
try {
workbook = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = workbook.getSheet(0);
// System.out.println("No of Columns :: "+sheet.getColumns());
for (int j = 0; j < sheet.getRows(); j++) {
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
CellType type = cell.getType();
if (cell.getType() == CellType.LABEL) { System.out.print(cell.getContents() + " "); }
else if (cell.getType() == CellType.NUMBER) {System.out.print(cell.getContents() + " "); }
else { System.out.print(cell.getContents() + " "); }
}
System.out.println("\n"); }
} catch (BiffException e) { e.printStackTrace(); }
}
}

Thursday, June 4, 2009

How to get Height and Widht of an Image using JavaScript

I got one problem during my project development. When I click on thumbnails to show image in pop up window, it does not appear in first click but on the second click it works. It only does work when the image exist is browser cache. And we had to show image on sigle click as per the client requirement. I got the solution and want to share with all of you. :)
Second requirement is that if image aspect ration is greater than 500 then reduce to 500.

<script type="text/javascript" language="javascript1.2">

var imgHeight;
var imgWidth;

function findHHandWW() {
imgHeight = this.width;imgWidth = this.width;return true;
}

function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
}
</script>


This is main code to get height and width of an image using javascript.

Now, I am giving complete code to how you will show pop up window after click on thumbnail image.

1. ThumbsNail.jsp

<html><head><title>Binod Java Solution</title></head>
<script type="text/javascript" language="javascript1.2">
var imgHeight;
var imgWidth;
var winHeight;
var winWidth;

function findHHandWW() {
imgHeight = this.width; imgWidth = this.width; return true;
}

function openWin(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
if(imgHeight>=500){imgHeight=500;}if(imgWidth>=500){imgWidth=500;}
winHeight = imgHeight + 60;winWidth = imgWidth + 30;

var url1="Image.jsp?myPath="+imgPath+"&hh="+imgHeight+"&ww="+imgWidth;
window.open(url1,"","width="+winWidth+",height="+winHeight+",status=yes,toolbar=no,
scrollbars=no,left=100,top=100");
}

</script>

<body>
<img src="c:\\Binod.JPG" height="85" width="85" onclick="openWin('c:\\Binod.JPG')" />
</body>
</html>

2. Image.jsp

<html><head><title>Binod Java Solution</title></head>

<script type="text/javascript">
function closeWin(){ window.close(); }
</script><body>

<%
String imagePath = request.getParameter("myPath");
String hh = request.getParameter("hh");
String ww = request.getParameter("ww");
%>

<img src="<%=imagePath%>" height="<%=hh%>" width="<%=ww%>" />
<center><input type="button" value="Close" onclick="closeWin()" /> </center>
</body>
</html>

Saturday, May 30, 2009

Ajax and JSON example, How to use JSON with Ajax

In my previous post, I had explained easy example of JSON. In this post I am explaining how to use JSON with Ajax.
No need to require any other software, just create one dynamic web project and paste below code.

1. StudentInfo.java (This is a Servlet)

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
out.println(getResult(roll));
}

public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
String[] subjects = new String[]{};
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
subjects= new String[]{"C++","JAVA","DataBase"};
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
subjects= new String[]{"C++","QT","Linux"}; }
else{ name = "Roll Number not found"; }

String result = "var student={"; result += "name:'" + name + "', ";
result += "hostel:'" + hostel + "', ";
result += "contact:'" +contact +"',";
result += "subject:[";
for(int i=0;i<subjects.length;i++){
if(i == subjects.length - 1){
result += "'"+subjects[i] + "']";
}
else{
result += "'"+subjects[i] +"',";
}
}
result += "};";
return result;

}
}

2. ShowStudentInfo.jsp

<html><head><
title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; f
unction getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/Ajax_JSON/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}

function showResult(){
if(request.readyState == 4){
var response = request.responseText;
eval(response);
document.getElementById("NamelH1").innerHTML = student.name; document.getElementById("HostelH1").innerHTML = student.hostel; document.getElementById("ContactH1").innerHTML = student.contact; document.getElementById("SubjectH1").innerHTML = student.subject; } }

</script>
</head><body>
<h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/> <br>
<table border=2>
<tr><td>Name</td><td><span id="NamelH1">
</span></td></tr> <tr><td>Hostel</td>
<td><span id="HostelH1"></span></td></tr> <tr><td>Contact</td><td><span id="ContactH1">
</span></td></tr> <tr><td>Subject</td>
<td><span id="SubjectH1"></span></td></tr>
</table>
</body>
</html>

After compile and start the server, open internet explorer and put URL (like http://localhost:8080/Ajax_JSON/ShowStudentInfo.jsp) and put roll no. 110

This is very basic and fundamental tutorial, you can build a good project on Ajax and JSON with the help of this easy example.

Please dont forget put your comment to enhance this blog. :)

How to get client and server side IP address in JSP Page

Please visit my another blog

http://binodjava.blogspot.com/2009/06/how-to-get-client-and-server-ip-address.html

Thanks,
Binod Suman

Thursday, May 28, 2009

Get Current Server Time on Client JSP Page using Ajax

Using AJAX, you can show the server current time on client page. Time would be update on every second. Even you can set the interval of fetching time from server.

For example I am showing one jsp page and servlet.
To use this tutorial, no need to download any jar file or extra files.
Just make one dynamic web project and use this jps and servlet file.

1. ShowServerTime.jsp

<html>
<head>
<title>Binod Java Solution AJAX </title>

<script type="text/javascript">
var request;
function init(){
window.setInterval("getTime()",1000);
}
function getTime(){
var url = "http://localhost:8080/ServerTime/GetServerTime";
if(window.ActiveXObject){
request = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}
request.onreadystatechange = showTime;
request.open("POST",url,true);
request.send();
}

function showTime(){

if(request.readyState == 4){
var response = request.responseText;
document.getElementById("TimeH1").innerHTML = response;
}

}


</script>

</head>
<body onload="init();">
<h1> Server Time :: </h1> <h1 id="TimeH1"/>

</body>
</html>


2. GetServerTime.java (This is a servlet file)

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetServerTime extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print(new Date());
}
}

How to compare two images, check two image are same or not

Please visit my this blog
http://binodjava.blogspot.com/2009/06/how-to-compare-two-images-check-two.html

Thanks,
Binod Suman

Wednesday, May 27, 2009

How to setup JNDI for Postgres SQL Database in RAD (Rational Application Development)

How to setup JNDI in RAD (Rational Application Development)

1. Start the server

2. Run Administrative console

3. Resource -> JDBC Provider -> Select the database type (User-defined) -> Select the provider type (User-defined JDBC Provider) -> Select the implementation type (User-defined)

4. Name : jndipostgresql

5. Class path: c:\jar\postgresql-8.1dev-403.jdbc2ee.jar

6. Native library path : c:\jar\postgresql-8.1dev-403.jdbc2ee.jar

7. Implementation class name : org.postgresql.jdbc2.optional.ConnectionPoolApply

8. Click on Data sources, New-> dspostgresql JNDI name : jndipostgresql

9. Click on "Select a data source helper class" Apply

10. Click on J2EE Connector Architecture(J2C) authenticaiton data entries, New -> Alias -> postgresqluser User ID -> postgres Password -> sumanApply -> save -> Save
Again go to datasource (dspostgresql), component-managed authentication alias -> postgresqluser (2 places) Apply -> Save

11. Click on Custom properties, New -> Name -> databaseName value -> postgresapply -> Save

12. Click on Test Connection, you will get successful if every thing fine.

Sunday, May 24, 2009

JSON an easy example, get start with JSON, how to use JSON

JSON : JavaScript Ojbect Notation.

It contains name/value pairs, array and other object for passing aroung ojbect in java script. It is subset of JavaScript and can be used as object in javascript.

You can use JSON to store name/value pair and array of ojbect.

It has eval() method to assign value to variable.
In below example, I have put all things together.
Just make one html file and you can start your practice on it.

How to use this tutorial:
1. Make one file JSONDemo.html
2. And paste below code

<html>
<head>
<body>
<script language="javascript">
eval("var amount =10;");
alert("Value of amount :: "+amount);

var student = {
name : "Binod",
roll : 110,
subject : ["Java","Database","Networking"]

}
alert("Student Name :: "+student.name);
alert("Student All Subject :: "+student.subject);
alert("Student First Subject :: "+student.subject[0]);
alert("Student No. of Subject :: "+student.subject.length);

for(var i=0;i<student.subject.length;i++){
var value = student.subject[i];
alert(value);
}

var person = {
name : "Ambani",
books : [
{
title : "Java Programming",
author : "Binod Suman"
},
{
title : "XML",
author : "Don Box"
}
]

}

alert("Book Title :: "+person.books[0].title);
alert("Book Author :: "+person.books[0].author);


</script>

Please put your comment on this post for enhance this blog or this tutorial.

Thanks and have a nice day ............ :)

Monday, May 18, 2009

Parse XML file in JavaScript part 2

As one of reader asked about how to handle XML respone if we get more than records or if your XML file have many child nodes.
I gave here one complete example with XML file and JavaScript in JSP.

1. abc.xml

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>

<Student> <Name>Pramod Kumar Modi</Name>
<Hostel>Godawari</Hostel>
<Contact>88888888</Contact>
</Student>

<Student>
<Name>Sanjay Kumar</Name>
<Hostel>Satjal</Hostel>
<Contact>7777777</Contact>
</Student>

<Student>
<Name>Mukesh Ambani</Name>
<Hostel>Rewti</Hostel>
<Contact>6666666</Contact>
</Student>

</Students>

2. StudentInfo.jsp

<html><head><title>Binod Java Solution AJAX </title>
<script type="text/javascript">

function showResult(){

var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false"; xmlDoc.load("abc.xml");
var students=xmlDoc.documentElement;
var student = students.childNodes(0);
var rows = students.childNodes.length; v
ar cols = student.childNodes.length;

var body = document.getElementsByTagName("body")[0];
//var tabl = document.createElement("table");
var tabl = document.getElementById("studentinfo");
var tblBody = document.createElement("tbody");

for (var i = 0; i < rows; i++) {
var row = document.createElement("tr");
student = students.childNodes(i);

for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode(student.childNodes(j).firstChild.text); cell.appendChild(cellText);
row.appendChild(cell);
}

tblBody.appendChild(row);
tabl.appendChild(tblBody);
tabl.setAttribute("border", "2");
}

</script>

</head><body onload="showResult()">
<h2> GET STUDENT INFO </h2><br>

<table id="studentinfo"> <tr bgcolor='red'> <td >Name</td><td>Hostel</td><td>Contact</td> </tr> </table>
</body>
</html>

Now your html table will grow dynamically as per number of records in XML file.

Saturday, May 9, 2009

Get start with Ajax, Ajax simple example with Servlet, Ajax programming with Servlet

I am writing here a very simple ajax program. That will take roll number from jsp page, hit serlvlet, come back with result as XML, parse in javascript and will show on jsp page.

1. ShowStudentInfo.jsp

<html><head>
<title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; function getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/blog_demo/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}
function showResult(){
if(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
var student = students[0];
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}
}
</script>
</head>
<body><h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/>
<br> Name : <span id="NamelH1"></span> <br
> Hostel : <span id="HostelH1"></span> <br
> Contact : <span id="ContactH1"></span> <br>
</body>
</html>

2. Servlet java file StudentInfo.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 StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public StudentInfo() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("**** STUDENT INFO ****");
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
response.setContentType("text/xml");
System.out.println(getResult(roll)); out.println(getResult(roll));
}
public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
} else{ name = "Roll Number not found"; }
String result = "<Students>";
result += "<Student>"; result += "<Name>" + name + "</Name>";
result += "<Hostel>" +hostel + "</Hostel>";
result += "<Contact>" +contact + "</Contact>";
result += "</Student>"; result += "</Students>";
return result;
}
}

Now simple run your JSP page and put the roll number like 110, it will work.
http://localhost:8080/Ajax_Demo/ShowStudentInfo.jsp

If you have any question or suggestion, please put your commnets.

Parse XML response in JavaSript

Some time we get response from server as xml.
This blog will show that how you can handle or parse xml in javascript.
1. Suppose you have xml response like this

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>
</Students>

2. In JavaScript function


function showResult(){
if(request.readyState == 4){
var response = request.responseXML;
var students = response.getElementsByTagName("Student");
document.getElementById("NamelH1").innerHTML = students[0].getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = students[0].getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = students[0].getElementsByTagName("Contact")[0].text;
}
}

Second situation: Suppose you have abc.xml file and you want to parse in javascript

abc.xml

<Students>
<Student>
<Name>Binod Kumar Suman</Name>
<Hostel>Ganga</Hostel>
<Contact>999999999</Contact>
</Student>
</Students>

Then your javascript would be

function getName(){
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
var students=xmlDoc.documentElement;
var student = students.childNodes(0);
document.getElementById("NamelH1").innerHTML = student.getElementsByTagName("Name")[0].text;
document.getElementById("HostelH1").innerHTML = student.getElementsByTagName("Hostel")[0].text;
document.getElementById("ContactH1").innerHTML = student.getElementsByTagName("Contact")[0].text;
}

Your JSP Page:

<h2>GET STUDENT INFO </h2>
<input onclick="getName();" type="button" value="Get Name">
Name : <span id="NamelH1"></span>
Hostel : <span id="HostelH1"></span>
Contact : <span id="ContactH1"></span>

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.