Thursday, October 11, 2012

How to get Current Time based on Time Zone using java

 import java.util.*;
 import java.text.*;
 public class time_Zone {
     public static void main(String[] args) {
         TimeZone tz = Calendar.getInstance().getTimeZone();
         System.out.println("TimeZone: "+tz.getDisplayName());
         System.out.println("ID: "+tz.getID());

        final Date currentTime = new Date();

        final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

        // Give it to me in US-Pacific time.
        sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        System.out.println("LA time: " + sdf.format(currentTime));

        // Give it to me in GMT-0 time.
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        System.out.println("GMT time: " + sdf.format(currentTime));

        // Or maybe Zagreb local time.
        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Zagreb"));
        System.out.println("Zagreb time: " + sdf.format(currentTime));

        // Even 10 hours and 10 minutes ahead of GMT
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0010"));
        System.out.println("10/10 ahead time: " + sdf.format(currentTime));

        System.out.println("INDIA ");

        sdf.setTimeZone(TimeZone.getTimeZone(tz.getID()));
        System.out.println("10/10 ahead time: " + sdf.format(currentTime));

        /*Date date = new Date();
          String TimeZoneIds[] = TimeZone.getAvailableIDs();
          for(int i = 0; i < TimeZoneIds.length; i++){
              TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]);
              String tzName = tz.getDisplayName(tz.inDaylightTime(date), TimeZone.LONG);
              System.out.print(TimeZoneIds[i] + ": ");
              // Get the number of hours from GMT
              int rawOffset = tz.getRawOffset();
              int hour = rawOffset / (60*60*1000);
              int minute = Math.abs(rawOffset / (60*1000)) % 60;
              System.out.println(tzName + " " + hour + ":" + minute);
          }*/
       
      }
}

Advantage and disadvantage of servlet

Servlet Advantage
  • Servlets provide a way to generate dynamic documents that is both easier to write and faster to run.
  • provide all the powerful features of JAVA, such as Exception handling and garbage collection.
  • Servlet enables easy portability across Web Servers.
  • Servlet can communicate with different servlet and servers.
  • Since all web applications are stateless protocol, servlet uses its own API to maintain  session
Servlet Disadvantage
  • Designing in servlet is difficult and slows down the application.
  • Writing complex business logic makes the application difficult to understand.
  • You need a Java Runtime Environment on the server to run servlets. CGI is a completely language independent protocol, so you can write CGIs in whatever languages you have available (including Java if you want to).

Tuesday, October 9, 2012

XPATH Java simple example

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

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

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

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

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

2. XPathJavaExample.java

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

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

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

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

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

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

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

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


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

How to backup of your blogger blog

There are many ways to take your blog backup. Even some tools are also available in market. But here I explain two ways:

1. Write one simple java program and take many blog backup together with timestamp.
2. Use Export and Import facility of blogger

1. Write one simple java code (BlogBackup.java)


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BlogBackup {
public static String repo = "E:\\Blog_BACKUP\\";
public static String ext = ".xml";
public static String url1 = "http://your_blogName _1.blogspot.com/feeds/posts/default?max-results=1000";
public static String url2 = "http://your_blogName _2.blogspot.com/feeds/posts/default?max-results=1000";
public static String url3 = "http://your_blogName _3.blogspot.com/feeds/posts/default?max-results=1000";

public static void main(String[] args) {
takeBackup();
}
public static void takeBackup(){
String folderName = createFolder();
String[] url = {url1,url2,url3};
try {
for(int i=0;iString fileName = folderName+"\\"+getFileName(url[i]);
doDownload(url[i],fileName);
System.out.println("Completed :: "+fileName);
}
} catch (IOException e) {e.printStackTrace();}
}
public static String getFileName(String url){
String fileName = url.substring(url.indexOf("//")+2,url.indexOf("."));
Format formatter = new SimpleDateFormat("MMM-dd-yyyy-HH-mm");
String now = formatter.format(new Date());
return fileName+"_"+now+ext;
}
public static String createFolder(){
Format formatter = new SimpleDateFormat("MMM-dd-yyyy");
String folderName = repo + formatter.format(new Date());
System.out.println("Folder Name :: "+folderName);
File file = new File(folderName);
if(!file.exists()){
file.mkdir();
}
return folderName;
}
public static void doDownload(String blogURL, String fileName) throws IOException {
String charset = "utf-8";
URL url = new URL(blogURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream inputStream = null;
inputStream = url.openStream();
StringBuffer s = new StringBuffer();
if(charset==null"".equals(charset)){
charset="utf-8"; }
String rLine = null;
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream,charset));
PrintWriter printWriter = null;
FileOutputStream fo = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(fo, "utf-8");
printWriter = new PrintWriter(writer);
while ( (rLine = bReader.readLine()) != null) {
String line = rLine;
int str_len = line.length();
if (str_len > 0) {
s.append(line);
printWriter.println(line);
printWriter.flush();
}
line = null;
}
inputStream.close();
printWriter.close();
}
}

You can change the repository folder name, I used here "E:\\Blog_BACKUP\\";
Whenever you will run this java code, it will create folder as running date and inside that folder your all blog backup will come with timestamp.

Please share your comments with me ........... :)

2. Another way
Step1 : Login to your blog (http://www.blogger.com)
Step2: Go to Setting tab
Step3: You will get Blog Tools (Upper left side)
Others-->blog tools
import blog,export blog, delete blog

How to generate PDF report from Java

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

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

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

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

How to insert IMAGE in PDF using iText

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

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

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

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

To change PDF page background color, use this

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

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

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

Add Header and Footer to PDF

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

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

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


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


HeaderAndFooter.java


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

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

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

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

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>

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

Parse XML file in JavaScript

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>

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>

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.

How to get client and server IP address in JSP page

Some time we have to show the server IP address on JSP page and some time we need to store client IP address to next visit purpose.
Using very few lines of code, you can get both server side and client side (browsing) IP address.

GetIPAddress.jsp

<h3> Server Side IP Address </h3><br>
<%@page import="java.net.InetAddress;" %>
<%String ip = "";
InetAddress inetAddress = InetAddress.getLocalHost();
ip = inetAddress.getHostAddress();
out.println("Server Host Name :: "+inetAddress.getHostName());%><br>
<%out.println("Server IP Address :: "+ip);%>

<h3> Client Side IP Address </h3><br>
<%out.print( "Client IP Address :: " + request.getRemoteAddr() ); %><br>
<%out.print( "Client Name Host :: "+ request.getRemoteHost() );%><br>

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 show Image on Pop Up Window using Servlet

When you want to show the image on pop up using JSP from your local drive, then you will feel the problem. Actually you can not show any file from local drive in pop up due to security reason. Then you have the servlet option to show the image on pop up window from local drive location.
I am giving step by step solution:

1. create one servlet MyServletImage.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServletImage extends HttpServlet implements Servlet {
public MyServletImage() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.reset();
String imagePath=request.getParameter("myPath");
System.out.println("Image File Name :: "+imagePath);
response.setHeader("Content-Disposition", "inline" );
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires","0");
response.setContentType("image/tiff");
byte[] image = getImage(imagePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);outputStream.close();
System.out.println("DO GET METHOD");
}

private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws
ServletException, IOException { }
}

2. ImageSource.jsp

<html>
<head>
<title>First Spring App</title>
</head>
<body>
<script language="JavaScript">
function myPage(fileLocation){
var url1="ImagePopUp.jsp?myPath="+fileLocation;
window.open(url1,"","width=550,height=400,status=yes,toolbar=no,menubar=no");
}
</script>
<input type="button" value="Get Picture First " onclick="myPage('e:\\Camera_Size_Reduced\\binod\\Binod_Apr08.jpg')"/> <br>
<input type="button" value="Get Picture Second" onclick="myPage('e:\\Camera_Size_Reduced\\binod\\DSC00072.JPG')"/> <br>
</body>
</html>

3. ImagePopUp.jsp

<h1 TO SHOW THE PICTURE HERE 3 </h1>
<%
String path1 = request.getParameter("myPath");
%>
<img src="http://localhost:9080/HSQLDB_TEST1/MyServletImage?myPath=<%=path1%>/>

How to make servlet for dowload image option

Suppose you have to write one serlvet, who would be give the download the image as save or open option.

This servelt should pick up the image as per the URL parameter from local drive and give the option of save or option image on your disk.

1. Make one Servlet SendImage

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

private SendImageHelper sendImageHelper;

public SendImage() {
super();
sendImageHelper = new SendImageHelper();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendImageHelper.sendImage(getServletContext(),request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}
2. One java file SendImageHelper.java

package com.tgt.image.sendimage.service;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendImageHelper {

String image_name = "";
List imageTypes = new ArrayList();
List numbers = new ArrayList();
ResourceBundle props = null;
String filePath = "";

private static final int BUFSIZE = 100;
private ServletContext servletContext;

public void sendImage(ServletContext servletContext,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
this.servletContext = servletContext;
String reqUrl = request.getRequestURL().toString();
StringTokenizer tokens = new StringTokenizer(reqUrl,"/");
int noOfTokens = tokens.countTokens();
String tokensString[] = new String[noOfTokens];
int count=0;
while(tokens.hasMoreElements()){
tokensString[count++] = (String)tokens.nextToken();
}

String folderName = tokensString[noOfTokens-2];
image_name = tokensString[noOfTokens-1];
filePath="/"+folderName+"/"+image_name;
fullFilePath = "c:/ImageFolder"+filePath;
//doShowImageOnPage(fullFilePath, request, response);
doDownload(fullFilePath, request, response);
}

private void doShowImageOnPage(String fullFilePath,HttpServletRequest request, HttpServletResponse response) throws IOException {
response.reset();
response.setHeader("Content-Disposition", "inline" );
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires","0");
response.setContentType("image/tiff");
byte[] image = getImage(fullFilePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);outputStream.close();
}

private void doDownload(String filePath,HttpServletRequest request, HttpServletResponse response) throws IOException {
File fileName = new File(filePath);
int length = 0;
ServletOutputStream outputStream = response.getOutputStream();
//ServletContext context = getServletConfig().getServletContext();
ServletContext context = servletContext;
String mimetype = context.getMimeType(filePath);

response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
response.setContentLength( (int)fileName.length() );
response.setHeader( "Content-Disposition", "attachment; filename=\"" + image_name + "\"" );

byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(fileName));
while ((in != null) && ((length = in.read(bbuf)) != -1)){
outputStream.write(bbuf,0,length);
}

in.close();
outputStream.flush();
outputStream.close();
}

}

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>

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(); }
}
}

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()); }
}
}

JMS easy example in RAD, Get started with JMS on RAD

This tutorial is based on RAD (Rational Architect Development) that uses the WebShpere Application Server V6.0.

1. start the server and go to admin console
2. Service Integration -> Buses -> New -> Give Name: BinodBus -> Apply -> save -> save
3. click on BinodBus -> In Additional Properties Section, click on Bus Member -> Next -> Finsh -> Save -> save
4. Again click on BinodBus -> In Additional Properties Section, click on Destination -> check Queue Type present or not. If
not present then click on New -> Choose Queue -> Next -> put Identifier QueueDestination -> Next -> Finish -> Save -> Save

5. Open Resources Tree from left panel
6. click on JMS Providers -> Default Messaging -> JMS Connection Factory -> New -> Name -> BinodConnectionProvider -> JNDI
Name -> jms/BinodConnectionProvider -> Bus Name -> BinodBus -> click on Apply -> Save -> Save

7. click on JMS Providers -> Default Messaging -> Go to Right side Destination -> JMS Queue -> New -> Name -> BinodQueue ->
JNDI -> jms/BinodQueue -> Bus Name -> BinodBus -> QueueName -> QueueDestination -> OK -> Save -> Save

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

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.
http://completejavaj2ee.blogspot.in/2012/10/jms-easy-example-in-rad-get-started.html

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.

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

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

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 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

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.

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.

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.

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 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(); }
}
}

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;
}
}

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 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", " "); }
}

Spring Integration Messaging tutorial, Spring Integration in 10 Minutes

There are many things in Spring Integration:

1. Messaging
2. Routing
3. Mediation
4. Invocation
5. CEP (Complex Event Processing)
6. File Transfer
7. Shared database
8. Remote Procedure call

Here I am posting Spring Integration Messaging (Kind of JMS) example here:

Create one project in Eclipse say SpringIntegrationDemo and add these below jar file to that project:

1. spring-core-3.0.5.RELEASE.jar
2. spring-integration-core-2.0.0.BUILD-SNAPSHOT.jar
3. jar/commons-logging-1.1.jar
4. spring-context-3.0.5.RELEASE.jar
5. spring-beans-3.0.5.RELEASE.jar
6. spring-asm-3.0.5.RELEASE.jar
7. spring-expression-3.0.5.RELEASE.jar
8. spring-aop-3.0.5.RELEASE.jar
9. aopalliance-1.0.jar

In src folder, create these three files:
1. MyService.java
2. myServiceDemo.xml
3. MyServiceDemo.java

MyService.java

public class MyService {

 public String sayHello2(String name) {
  return "Suman Hello :  " + name;
  }

}

myServiceDemo.xml

<?xml version="1.0" encoding="UTF-8"?>
&it;beans:beans xmlns="http://www.springframework.org/schema/integration"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/integration
   http://www.springframework.org/schema/integration/spring-integration.xsd" >

 <channel id="inputChannel"/>
 <channel id="outputChannel">
  <queue capacity="10"/>
 </channel>

 <service-activator input-channel="inputChannel"
                    output-channel="outputChannel"
                    ref="myService"
                    method="sayHello2"/>
 <beans:bean id="myService" class="MyService"/>
</beans:beans>

MyServiceDemo.java

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.message.GenericMessage;
public class MyServiceDemo {

 public static void main(String[] args) {
  AbstractApplicationContext context = new ClassPathXmlApplicationContext("myServiceDemo.xml", MyServiceDemo.class);

  MessageChannel inputChannel =  context.getBean("inputChannel", MessageChannel.class);
  PollableChannel outputChannel =  context.getBean("outputChannel", PollableChannel.class);

// Just senging messages into message channel.
  for(int i=0;i<10;i++){
     inputChannel.send(new GenericMessage<String>("World : "+(i+1)));
  }

  // Getting message from message channel
  System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
  System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
  System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
  System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());
  System.out.println("==> Returning from MyService : " + outputChannel.receive(0).getPayload());

 }
}

Now you can run MyServiceDemo file, will get result. :)

Spring RowMapper Example, Use of RowMapper, RowMapper Tutorial, jdbcTemplate Example with RowMapper

Interface RowMapper:

org.springframework.jdbc.core.RowMapper
An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object. One very useful thing is that you can collect all the column of one recrod into java collection.

public class Student {
  private Map data = new HashMap();
  int roll;
}

Means, all the data will be there in map and only one primary column be there outside.

Example here:

Student.java


package binod.suman.rowmapper.domain;
import java.util.HashMap;
import java.util.Map;
public class Student {
 private Map data = new HashMap();

 int roll;

 public void putObject(String key, Object value) {
  data.put(key, value);
 }

 public Object getObject(String key) {
  return data.get(key);
 }

 public Student(int roll) {
  super();
  this.roll = roll;
 }
 public int getRoll() {
  return roll;
 }
 public void setRoll(int roll) {
  this.roll = roll;
 }
 @Override
 public String toString() {
  return "Name : "+data.get("sname")+" \nCity : "+data.get("city")+" \nRoll Number : "+roll;
 }


}

StudentResultSetReader.java

package binod.suman.rowmapper.dao;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import binod.suman.rowmapper.domain.Student;
public class StudentResultSetReader implements RowMapper {
 public StudentResultSetReader() {
 }

 public Student read(ResultSet rs) throws SQLException {
  Student t = new Student(rs.getInt("roll"));
  ResultSetMetaData md = rs.getMetaData();
  int numCols  = rs.getMetaData().getColumnCount();
  for (int i = 1; i <= numCols; i++) {
   t.putObject(md.getColumnName(i), rs.getObject(i));
  }
  return t;
 }
 @Override
 public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
  return read(rs);
 }
}

StudentDAO.java

package binod.suman.rowmapper.dao;

import java.util.List;
import binod.suman.rowmapper.domain.Student;
public interface StudentDAO {
// public void insertStudent(Student s);
 public Student selectStudent(int roll);
 public List selectAllStudent();
}

beanx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans"
 http://www.springframework.org/schema/beans/spring-beans.xsd"/ >

 <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost/suman"/>
        <property name="username" value="root"/>
        <property name="password" value="mysql"/>
    </bean>

 <bean id="studentDAO" class="binod.suman.rowmapper.dao.StudentDAOImpl">
  <property name="dataSource" ref="dataSource"/>
 </bean>

</beans>
Main.java

package binod.suman.rowmapper.dao;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import binod.suman.rowmapper.domain.Student;

public class Main {
 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  StudentDAO studentDAO = (StudentDAO) context.getBean("studentDAO");
//  Student student = new Student(251,"Binod Suman", "Espoo");
//  studentDAO.insertStudent(student);
  Student ss = (Student)studentDAO.selectStudent(150);
  System.out.println(ss);

  List ssList = studentDAO.selectAllStudent();
  System.out.println("Total Record :: "+ssList.size());
  for(Student s : ssList){
   System.out.println("******************");
   System.out.println(s);
   }
  }
}

Jar files required:
org.springframework.asm-3.0.0.M3.jar
org.springframework.beans-3.0.0.M3.jar
org.springframework.context-3.0.0.M3.jar
org.springframework.context.support-3.0.0.M3.jar
org.springframework.core-3.0.0.M3.jar
org.springframework.expression-3.0.0.M3.jar
org.springframework.jdbc-3.0.0.M3.jar
org.springframework.transaction-3.0.0.M3.jar
mysql-connector-java-3.1.12-bin.jar
antlr-runtime-3.0.jar
commons-dbcp.jar
commons-logging-1.0.4.jar
commons-pool.jar
hsqldb.jar

You need to create one database schema with name suman and one student table shoule be there:

CREATE TABLE student (
  sname varchar(100) default NULL,
  roll int(4) NOT NULL,
  city varchar(100) default NULL,
  PRIMARY KEY  (`roll`)
)

and some data should be there:
insert into student ('Binod',150,'Helsinki');

Details documentation on RowMapper.