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>