Pages

Saturday, August 25, 2012

NoClassDefFoundError

This is a very common error which causes headache for most of the beginners when they try to execute their first java program,it compiles without any error, class file is also generated but when you try to run the program 
the most frustrating error pop up,that is:

Exception in thread "main" java.lang.NoClassDefFoundError

Note: don't misunderstand this with ClassNotFoundException,i'll mention the difference between the two similar looking exceptions at the end of this post.


I have faced it a lot of times in the beginning,so i want to share it here
what is the reason behind this error and how to rectify 
here is the reason:
you should know that when we try to run a program like this 
command prompt:/java classname
the JVM searches the classpath to locate the class name you provide to it.
If JVM doesn't find definition of a class in the CLASSPATH which was available at the time of compilation it generates the error 

Exception in thread "main" java.lang.NoClassDefFoundError
So you can easily understand that the problem is not with the code but it is because the JVM is unable to locate the class file,so to rectify the problem you need to :

 >> identify the class which is creating the problem, you can easily find out it from the error message

take an example 

//hello.java
class SayHello
{
 public static void main(String[] args) 
 {
  System.out.println("Hello World!");
 }
}
in the above program there is only one class i.e SayHello after compiling this program 
promt:/javac hello.java
a class "SayHello.class" will be automatically generated. and when you try to run your program from the same directory like this 
prompt:/java SayHello
you get the error Exception in thread "main" java.lang.NoClassDefFoundError
the only reason behind this is you haven't provided the classpath for you class. Provide the class path for you class file and the error will go away automatically.
there are two options 
1> declare the CLASSPATH environment variable 
"Control Panel\System --> advanced system settings -->environment variables"   which sets the classpath permanently. or
2> run your program like this 
prompt:/java -cp . SayHello.java
the -cp argument stands for classpath and "." for the current directory,it tells JVM to look in current directory for the class file. 
this is all you need to do,to get rid of this error.

difference between

ClassNotFoundExceptionNoClassDefFoundError
Occurs when a class is not found which is referenced in the program you are trying to executeOccurs when a class is unavailable to JVM at the time of execution which was there at the time of compilation
Reason may be a missing package or jar file which contains the classonly possible reason is problem with CLASSPATH which is explained above
Problem may be in manifest file which may not have mentioned some jar file which is the source of the class


Friday, August 3, 2012

Interface

An Interface is collection of methods with empty bodies.
Interface contains only

  • static and final fields.
  • abstract methods.

Interface is declared as

interface abc
{
     //static & final fields
     //empty body methods are declared here.
}

Constraints:

  • An interface can contain only abstract methods and any class implementing the interface thereby inherits the abstract methods of the interface.
  • Unless the class that implements the interface is abstract,all the methods of the interface must be defined in the class. 
Comparison between a normal class and interface:

classinterface
can have constructorsdon't have any constructor
can be instantiatedcan't be instantiated
is extendedis implemented

how to implement an interface ?

here is a sample code

interface Vehicle
{
         public static final int speed;
         public void displayInfo();
}
class Car implements Vehicle
{
         speed=150;
         public void displayInfo()
         {
               System.out.println("it's a car");
          }
}

Abstract Class

Abstract class is a class which contains methods without implementation.
If a class contains even a single abstract method you need to declare your class as abstract
like this
abstract class <classname>                          
{                                                                  
       //abstract methods                                
}                                                                  
Abstract class can't be instantiated because an abstract class contains abstract methods without definitions so creating object for such a class is meaningless.
Any subclass of an abstract class must provide the definition for the all the abstract methods of it's super class or declare itself also as abstract.

Now the question is
Q) Why we need an Abstract method  ?
Answer:
If you are unable to decide the exact definition of a method,lets take an example like if there is a method area() in your class,i bet you will get confused while providing definition for this method.you will definitely think whose area you are going to compute in this method either rectangle,triangle or circle ?
and finally you will come up with abstract area() so that any subclass of your abstract class will provide the definition of area() according to the requirement.

i am taking an example of an Automobile class


abstract class Car
{
int price;
String manufacturer;
public void display()
{
        System.out.println("its a car");
}
abstract public String getPrice();

}

class Bmw extends Car
{
        public String getPrice()
        {
                return "40 lacs";
         }

}
class Hyundai extends Car
{

        public String getPrice()
        {
                return "10 lacs";
         }
}

public class mainclass
{
         public static void main(String args[])
         {
                  Bmw car1=new Bmw();
                  Hyundai car2=new Hyundai();
                  car1.display();
                  car1.getPrice();
                car2.display();
                  car2.getPrice();
          }
}


in this example getPrice() method is abstract method in the Car class which is abstract itself.
getPrice() is overrided in the subclasses Bmw and Hyundai.


Saturday, July 28, 2012

Adapter Class

In this article you will learn about adapter classes their use and how to write adapter classes manually.
Before going for adapter classes you need to have an idea about Abstract classes and Interfaces.

as we know if we declare an interface all its methods must be abstract and need to be override in the sub class which implements that interface.
>> So whats the problem here ? 
Its very time consuming and difficult task to provide definitions for each and every method of interface in the sub-classes.
>> what is the need of adapter classes ?
If you are not interested to override all the methods of interface you can make use of adapter classes.

Adapter class: it is an abstract class implementing any interface and it contains definitions of some of the methods of the interface it is implementing.this Adapter class can be inherited now by any class without any bounds of  overriding  all the methods of the interface because the adapter class contains the definitions of that methods.
Note: if a method isn't overridden  in the adapter class then it is necessary to be overridden it in the sub class otherwise compiler will give an error.

here is an example showing adapter class :

import java.io.*;
import java.util.*;
interface iface  
{
public void input(int x,int y);
public void biggest();
public void display();
}

abstract class adapter implements iface
{
int d,e;
public void input(int x,int y)
{
d=x;
e=y;
}
}
class big extends adapter
{
int c;
public void biggest()
{
if(d>e)
{
c=d;
}
else
{
c=e;
}
}
public void display()
{
System.out.println("biggest number is :"+c);
}

}
public class main
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
big a=new big();
int g=sc.nextInt();
int h=sc.nextInt();
a.input(g,h);
a.biggest();
a.display();
}
}

In the above example the input() method is optional to override in the subclass because it is already overridden in the adapter class.
This example is just my attempt to make the concept clear,you may not find adapter classes much useful here in this example but in real time where interfaces contains tens of methods the programmers never like to override all of them directly in their classes so they use adapter classes and its a very effective technique.
It reduces code and saves time.

Friday, July 27, 2012

Creating a SSL Certificate


>> First of all You need JDK installed on your system to proceed further.
>> Now using the keyTool utility available with JDK we can create SSL certificates like shown in the screenshot.
use the command "keytool -genkey -alias tomcat -keyalag RSA"
* here RSA is the algorithm used for encryption of data.

     
>> You will see all the steps as shown in the above screenshot if you are going right.
>> After creation of .keystore file(SSL certificate) it is stored in the user' home folder automatically.
>> Now you need to configure the .keystore file in the server.xml file which is located inside %TOMCAT_HOME%\conf

               add the following element to the server.xml file.
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" keystoreFile="C:/Users/hsd/.keystore" secure="true" keystorePass="hsdhaka" clientAuth="false" sslProtocol="TLS" />
>> Now start the tomcat server
>> Enter the URL https://localhost:8443/ in addressbar of any browser and you will see the following page


This page indicates that your certificate is not created by a trusted vendor and thus can't be trusted,but the SSL security is on for your applications by doing so.

If you will click on
you will see the requested page as you expect it to be
but you can easily notice address bar of your browser

this shows that the resource you have requested is not trust worthy.
If you don't want to see this kind of alerts before your website is displayed get,your certificate designed and signed by a trusted SSL vendor in the market like thawte.



Wednesday, July 4, 2012

how to deploy a servlet application in tomcat

Step to Deploy servlet application on tomcat web-server:

Step-1  Installing Tomcat :
If you have tomcat server already installed on your system go to step-2 directly.
Otherwise download the tomcat setup or zip file from http://tomcat.apache.org/ and extract the files wherever you prefer.Extracting is enough in case of zip file download,no special installation setup is required.

Step-2 Setting environment variables
 >> Set JAVA_HOME variable to your JDK installation directory i.e C:\Program Files\Java\jdk1.6.0 in my
      System.It may be different on your system so check for it.
>> Set classpath for servlet-api.jar file which contains all the servlet libraries which is essential for compiling
      any servlet application.This servlet-api.jar file is provided with your server product in a location similar to
      "D:\apache-tomcat-6.0.29\lib\servlet-api.jar" ,this path may vary according to the installation location of 
       tomcat server.
       you need to execute this command from command prompt to set classpath:
       set classpath=D:\apache-tomcat-6.0.29\lib\servlet-api.jar;
       and your classpath is set proceed to next step.

Step-3 Designing Basic components like a servlet,html page.

>> Create a simple html file which will be used to invoke the servlet class.

//index.html

<html>
<center>
<form action="./myServlet" method="get">
<input type="submit"/>
</form>
</center>
</form>


>> Now its time to create a servlet class.

//Myservlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Myservlet extends HttpServlet
{
     public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
     {
          PrintWriter pw=resp.getWriter();
          pw.println("<html><center>this is servlet response</center></html>");
      }

}

Step-4 Compile the servlet class.

Open the command prompt
Change current directory to the one which contains your Myservlet.java file
Now execute command:   "javac Myservlet.java" 
It will generate the class file for your servlet if there is no error.

Step-5 Create a deployment descriptor file i.e web.xml
deployment descriptor contains the servlet information like servlet class,servlet mapping and url pattern for which the container will invoke the servlet.

//web.xml

<web-app>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>


Step-6 Arranging all the above components in a standard directory structure

Create a root folder for your application i.e Sample here in my example
Inside root folder create a new folder WEB-INF.
Inside WEB-INF create sub-folder classes and arreange the all the files as shown in the directory structure.
Your final directory structure should look like the below one.

Step-7 Deploy the Application 

Deployment is nothing but placing root folder of your application inside the
"D:\apache-tomcat-6.0.29\webapps "    folder  that is inside the server installation directory.

Step-8 Make a request to your application:
>> start the tomcat server by clicking on startup.batch file located inside the bin folder of your tomcat installation directory.
>>open any browser and type the following url  "http://localhost:8080/Sample/index.html "
     it will show your html page with a submit button which will call  Myservlet on clicking.

You are done,Good luck




Saturday, June 30, 2012

Session Tracking using Cookies

Cookies are piece of information sent by any web application to a web browser. and this information is further used to track the client state(data).
In my last post i wrote about session tracking with the help of hidden form fields but i also mentioned there that the hidden form fields are not effective in most of the situations.
So cookies are our next hope and cookies are nice indeed as they sound, I am going to discuss how.

Whenever a client or end user sends a request to a web application by supplying some information in the form of request body or through URL.
The web appliction does :
  • Grab all the information from the request body or URL(Depends on the request method either get or post).
  • Create cookies for each of these information elements.(!! creating cookies is far easy you will see very soon)
  • Now that the information is encapsulated in the cookies the web application sends these cookies back to the requesting browser as a response.  
 Now the browser plays its role :
  • The duty of browser is to store the cookies received from the web-application in some private location with Domain name and path of web-application from where the cookies arrived.
  • Now when the cookies are stored,whenever next request is made from the same browser to the same domain the browser automatically embeds all the cookies matching that particular domain to the request body.
  Note: Every Browser keep its cookies separately. ex. Internet Explorer don't share its cookies with Mozilla or any other,and same is the case with any other browser.

pictorial representation of cookie transfer mechanism

As you can observe above the mechanism of cookies is very simple.This was the general concept of how the cookies work.This concept remain same, doesn't matter on whether you use JAVA, PHP or .net.

But i am totally java oriented person so Lets relate the concept of cookies with the java technology.

Cookie : is a class in java come with javax.servlet.http package with one and only two argument constructor.
Cookie(String ,"value"); 
second argument to the constructor can be of any type i.e String,int,double,float,boolean etc.
>> Creating a cookie:
You can't create a cookie object without providing these two arguments i.e name and value.
Syntax for creating a Cookie object is :

Cookie cuki=new Cookie("uasername","wilson");

in the above line of java code "cuki" is a complete cookie with name "username" and value "wilson".

Every cookie in the world is created in the same way as shown above.

>> Now the second minor challenge is to pass the cookie to the browser back.

we do it like this:

response.addCookie("reference to cookie object");

After adding the cookie to the response the role of Server side application is almost over.
>> Now the browser will store the cookie in a predefined fashion
that is:
whenever the browser receives a cookie it first checks whether there is prior cookie from the same domain with same name.

case1: if a cookie is already present there with same name and domain
          browser just replace it with the new one.
case2: if the cookie is new to the browser then it stores the cookie normally.

>> After storing the cookie,the prime duty of browser is to attach all the associated cookies for a domain to any of request made for that domain.

>> And the web application utilizes these cookies to identify client states.


This was all theoretical view of working of cookies.
now its time for a real and working example which will show you the complete picture:

//index.html the starting page.

<html>
<head>
<%@page language="java"%>
<title>cookies tutorial</title>
</head>
<body bgcolor="gray">
<form name="login" action="Storecookies">
UserName:<input type="text" name="uname"/><br/>
Password: <input type="password" name="pass"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>


// this is the source of Storecookies servlet.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Storecookies extends HttpServlet
{
    public Storecookies(){
    }
  
    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
    {
        Enumeration paras=req.getParameterNames();
        PrintWriter pw=resp.getWriter();
        String rem=req.getParameter("remember")
      while(paras.hasMoreElements())                                                                             
            {                                                                                                                     
                String pname=(String) paras.nextElement();                                                  
                String pvalue=req.getParameter(pname);                                                      
                Cookie c=new Cookie(pname,pvalue);                                                           
                c.setPath("/*");                                                                                            
                resp.addCookie(c);                                                                                       
            }                                                                                                                     
            pw.write("<b>cookies are stored successfully</b>");                                            
            pw.write("<a href='Showcookies'>show me the cookies</a>");                               
    }                                                                                                                             
}                                                                                                                                 


// Source of Showcookies Servlet.


import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Showcookies extends HttpServlet
{
   
    public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
    {
       
        Cookie c[]=req.getCookies();
       
        PrintWriter pw=resp.getWriter();
        pw.write("<html><body bgcolor='gray'>");
        for(int i=0;i<c.length;i++)
        {
            String name=c[i].getName();
            String value=c[i].getValue();
       
            pw.println(name+" -> "+value+"<br/>");
        }
            pw.write("</body></html>");

    }
    public void doPost(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
    {
        doGet(req,resp);
    }

}

// web.xml file with Servlet mappings

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <servlet>
  <description>just testing servlets</description>
  <servlet-name>Storecookies</servlet-name>
  <servlet-class>Storecookies</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Storecookies</servlet-name>
  <url-pattern>/Storecookies</url-pattern>
 </servlet-mapping>
 <servlet>
  <servlet-name>Showcookies</servlet-name>
  <servlet-class>Showcookies</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Showcookies</servlet-name>
  <url-pattern>/Showcookies</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>


This was a Simple application imlementing cookies to store client data.You can easily Deploy this simple and ready made application and checkout the outcome.

Now i want to add some methods which are provided by Cookie class for providing advance control over cookies.

>>What is Age for a cookie?

Its the time period for which the browsers keep a cookie and after expiring of that time period they delete the cookie.
We can set Maximum age for any cookie using the below method

setMaxAge(time in seconds);

Default MaxAge for any cookie is -1 which instructs browser to keep the cookie till the browser is running,once the browser is closed cookie is lost.

>> We can set Domain name for a cookie explicitly if we like to do so.otherwise its automatically set by the web containers. 

setDomain("Domain name");

>> We can decide the paths for which the browser should send the cookie within a applicatin,like if you want a cookie to be sent only for the login page in your web applicatin.you can do it like this

setPath("/login.jsp");

>> Cookies are of two types secured and insecure
Secured cookies use https(hypertext secure socket layer) protocol.But cookies are insecure by default.

setSecure("boolean"); //provide true as argument to make a cookie secure.

>> To get value of a cookie object we use the below method on the cookie object:

getValue();

>> To get name of a cookie :
getName();

>> If you want to know MaxAge of a cookie use 
getMaxAge();



 --------------------------------------------------------------------------------------


 support by providing your valuable feedback !!

Thursday, June 28, 2012

Session Tracking

What is Session ?

Session is nothing But the time for which a client is recognizable to the web application.
When a client first time makes a request for some web resource by providing some information about itself the Session starts, and when the serving web application loses information about the client the session ends.
For example : when you click on login button after providing a valid email id and password in the Gmail login screen your session is started, because from that time onward google can recognize you untill you logout. 

Here in this Post you will learn about the requirement of session tracking and various mechanisms to achieve session tracking.

What is Session Tracking ? 

Session tracking is mechanism of tracking the client provided data and making it available to the next request from the same client.and this process is continued until the user choose to LogOut or terminate the session.

Why we need Session Tracking ?

Hypertext Transfer Protocol(HTTP) we all are familiar with this protocol because it is totally unavoidable.
The must know characteristic of HTTP is its stateless nature.
Stateless means it can't sustain a relationship with the clients.HTTP protocol sends a response back to a client and then it just forget about this activity, and go for serving next request. 

StateLess nature of Http protocol
If our requirement is limited to static content only then HTTP is very effective because it is faster than any other protocol,but what to do if you want to be recognized by the application you are using on the web.
like if you want to reserve air tickets and you are on website of Kingfisher Airlines,how would you feel if they ask you for your account information and then shows you a welcome note, obviously you will feel good to be welcomed
but what happens if they just forget about you on the next request and again ask you to provide account information,everybody is supposed to lose patience at that time this is also obvious.
So the Conclusion is,we need to maintain client data to design effective dynamic applications.




Session tracking mechanisms :

1. Hidden Form Fields.
2. Cookies.
3. URL rewriting.
4. HttpSession interface.

Hidden Form Fields Mechanism: as we are aware about html forms,they are used to accept input from client or end user.
Form fields are of three types regular,password and hidden.
we can define them like this:
<input type="text" name="<any anme>" value="<default value>"/>
<input type="password" name="<any name>" value="<default value>"/>
<input type="hidden" name="<any name>" value="<value of field>"/>
 The last one with type="hidden" is not displayed by the browser while rendering the response.So these hidden form fields become effective tools to embed information about the client inside the html forms without displaying it to the end user.
The wonderful quality of hidden fields is,they are automatically sent with the request object along other fields when user clicks on the submit button.

Example:
here is an example of a simple servlet based application using hidden form fields to maintain client data.


Bank account refilling application

In the above sample application flow diagram,first of all user sees a login form:
<form action="Authorization" method="post">
<input type="text" name="userid"/>
<input type="password" name="upasswd"/>
<input type="submit" value="login"/>
</form>

User name:
Password:


when the user click on login the control goes to Authorization servlet which accesses database to match the input data and if the data provided by the user is valid it produces a dynamic html form like this:
<form action="refill" method="post">
<input type="hidden" value=request.getParameter("userid")/>
<input type="text" name="bank"/>
<input type="text" name="amount"/> 
<input type="submit"/>
</form>

Bank name:
Amount to be Filled:

when the user clicks on the refill button the control automatically goes to refill servlet which then communicate with database to refill the account of client with userID embedded in the hidden form field.

So now i think its clear to you that how the information is shared between multiple requests using hidden form fields. 

now its time to discuss some drawbacks of this mechanism of hidden form fields

Drawbacks:
1.It is not supported by hyperlinks :means if the control transfer is through the means of form submission then its k but if a user clicks on an anchor tag then all the information in hidden fields is just lost.
2.We cant track sensitive data like passwords in the hidden form fields because,even a average technical person can view the HTML source of the pages retrieved from server and take out passwords very easily.
3.Useful only if the forms are generated by server side scripts,these hidden fields are of no use in session tracking if the forms are static. 


The alternative to the mechanism of hidden form fields are :

Cookies 

URL rewriting  


HttpSession interface.

Wednesday, June 27, 2012

Environment variables

Environment variables:

These are variables which controls the behavior of applications and various processes dynamically.
for example %TEMP% environment variable can be used by a processes to store temporary data used by it at the path provided by %TEMP% variable.
Environmental variables enhances the flexibility of applications in two ways: 
1. user can edit the environment variables an application uses to change its behavior,any time.
2. As the environmental variables are external to the applications they are loaded at run-time.So its possible to change the behavior of application without recompiling them.

Note: Environment variables can be provided only specific names which can be detected by the processes which use them.So it is not in our hands to decide the Environment Variable Name but We can change the paths to which Environment variables points.
For Example:     
%HOME% Environment Variable is used by various processes to locate the root user's home directory which is by default "C:\users\<user account>" in every windows operating system.
but we can change this path to any other say:  "d:\home"
but if we attempt to change variable name from %HOME% to any other say %MYHOME% then this Environment Variable is of no use to any process which are coded to use %HOME% Environment variable.

There are many standard Environment variables:

  • HOME (points to the user home directory) 
  • TEMP  or TMP (point to the path used for storing temporary data)
  • NUMBER_OF_PROCESSORS (no of processors deployed in your system)
  • OS (represents Operating System)
  • PROCESSOR_ARCHITECTURE
  • CLASSPATH:
       classpath variable is used to locate class files used inside java 
       applications.  
       whenever a class is need to be loaded in a java application the JVM    
       searches for appropriate class file in all locations starting from first path 
       in the CLASSPATH variable.If the class file is present in the current 
       working directory and you dont want JVM to search through all path   
       locations in the CLASSPATH variable just add ".;" to the beginning of 
       your CLASSPATH variable. in ".;" the dot "." represents current working 
       directory and ";" is the separator.
  • path:
          path environment variable is used to provide paths to the executable  
          files and commands of the operating syatem or some other application 
       like Compilers and MySQL. We use path variables for individual 
       commands so that we are not required to provide full directory path 
       every time we execute the commands. 
       Example: we provide path "c:\program files\java\jdk1.6.0\bin" in the   
       path variable because we need to use javac and java commands to 
       compile and execute java applications from command prompt and these 
       executable commands are located inside the bin directory of our java 
       installation directory.after setting path variable we can directly use javac
       and java commands in command prompt like any other DOS command. 
  • USERNAME  (stores the username for admin account)     etc.

Most of the above Environment variables must have are already declared on your system if you will check for them,because these above Environment variables are Operating System oriented.

How to check Environment Variables:
there are two ways
1. Open command prompt
    give command:   set
    It will display all the variables on the console.  
    note:If you want to look at some specific variables for ex. if you want to
    display variables with names starting with character L 
    give command: set L
 
2. Open control panel
    select System > advance system settings > Environment variables

How to set Environment Variable:
there are two ways
1. Open command prompt
    give command: set <variable name>=<path>
2. Open control panel > system > advance system settings >Environment    
    variables > new
    then provide variable name and value in the fields provided.

How to delete  Environment variable
again there are two ways
1. Open command prompt
    give command: set <variable name to be deleted>=
    this way the value for the variable will be set to null value in other words   
    it will be removed.
2. Open  control panel > system > advance system settings >Environment
    variables  select variable and click on delete.

note: You may have seen environment variable names enclosed in %---%
this syntax is used with those Environment variables which are used in other paths like path=%JAVA_HOME%/bin;
this way %JAVA_HOME% will be automatically replaced with value of JAVA_HOME Environment variable.

   

Thursday, June 21, 2012

Using Type-4 DB2 driver for Communication between java application and DB2 server

This is my second Post on JDBC the first was based on Type-1 architecture based JDBC Drivers and this one is for Type-4
 
I suppose that you have Installed the DB2 database server and JDK/JRE on your system if you have not installed yet Do it now,before starting this tutorial.

Now to create an application which can communicate with DB2 server you need
1. JDBC driver.
2. CLASSPATH environment variable of our system set to JDBC driver provided by DB2.
3. Little knowledge of basic JAVA and  following interfaces
    a.) Driver interface.
    b.) Statement and PreparedStatement Interfaces.
    c.) ResultSet Interface.
   
>> JDBC driver requirement is not a reason to worry,because type-4 drivers are shipped with database products by default by the database vendors.
For your DB2 version you can find it in the installation directory of your DB2
for windows OS it is mostly ->  c:\program files\IBM
then you can find drivers in the SQLLIB\java directory in the IBM folder
the driver names are   db2jcc.jar and  db2jcc_license_cu.jar

>> Now that you have located your drivers you need to add complete path for these driver to the CLASSPATH environment variable of your system.
To do this proceed with following steps:
  1. open control panel.
  2. select system option.
  3. select advanced system settings.
  4. a new small window will pop up select environment variables from here 
  5. now see if there is already a CLASSPATH variable in system or user variables or not
case 1: If it is already there select it to edit and add full path for both the drivers mentioned above separated by a semicolon(;) and save the settings by clicking on ok button.
case 2: If the CLASSPATH variable is not there already create a new one provide the name CLASSPATH to it and add path for both  drivers.

>>Half of your JOB is done already. Its time for coding the application

Keep in mind:
  • Default port no for DB2 is : 50000
  • Host name : localhost ( if the server is on your own machine).
  • Driver URL:
       For type-4 Drivers:
                      "jdbc:db2://localhost:50000/test","username","password"
       and for type-2 Drivers it is: 
                      "jdbc:db2:database","username","password"
  • Never forget to close the connection after using it,its not a matter of consideration here in our sample application.but if you are designing some enterprise level application for your employer,and you forget to close the connections then only god can save you from getting fired .. mind it.
import java.util.*;
import java.sql.*;
class test
{
    public static void main(String args[])
    {
  
        try
        {
          /* load the driver class and registers the driver with driver pool automatically*/
         Class.forName("com.ibm.db2.jcc.DB2Driver");
          /* create a connection object using DriverManager class of java.sql package*/ 
         Connection conn=DriverManager.getConnection("jdbc:db2://localhost:5000/test","hsd","hsdhaka91");
         /*create statement class object and use it to send query to the connected database*/
         ResultSet rs=conn.createStatement().executeQuery("select * from test.employee");
         while(rs.next())
         {
            // access the data records/rows here.          
           // if there is no record in the tablename table this block will not be executed.
         }
         conn.close();
        }
      
        catch(Exception ex)
        {
         System.out.println(ex);
        }

    }  
}

Same application but without using the DriverManager

import java.util.*;
import java.sql.*;
class test
{
    public static void main(String args[])
    {
   
        try
        {
         /* load the driver class,registers the driver with driver pool and creates an object to Driver class*/
        com.ibm.db2.jcc.DB2Driver obj=new com.ibm.db2.jcc.DB2Driver();
        /* Properties  is an inbuilt class in the java.util package used to store properties */
        Properties p=new Properties();
        p.setProperty("user","username");  //provide username as second argument.
        p.setProperty("password","userpassword");   // provide password for the database user
        Connection conn=obj.connect("jdbc:db2://localhost:50000/dbname",p);

        ResultSet rs=conn.createStatement().executeQuery("select * from tablename");
        while(rs.next())
        {
            // access the data records/rows here.
            // if there is no record in the tablename table this block will not be executed.
        }
        conn.close();
        }
       
        catch(Exception ex)
        {
        System.out.println(ex);
        }

    }   
}
              
In the second application we are not taking support of DriverManager class to create connection object
but we are directly calling connect("URL",property object); method  to create the connection.
This connect method is a member of Driver class object.

>> You can also use PreparedStatement Interface to increase the user interactivity of your application.

I think This tutorial will be helpful for my readers.
Please provide your valuable Feedback for this post.