Thursday, June 9, 2011

Create Web Service in Java Using Apache Axis2 and Eclipse

Web services are application components which communicate using open protocols. Using Web Services we can publish our application's functions to everyone. This tutorial provides step by step instructions to develop Web Services using Axis2 Web Services / SOAP / WSDL engine and Eclipse IDE. Let's start.

1. Setup the Development Environment


1.1. First you need to set up the development environment. Following things are needed if you want to create Web Services using Axis2 and Eclipse IDE.

Some Eclipse versions have compatibility issues with Axis2. This tutorial is tested with Apache Axis2 1.5.2, Eclipse Helios and Apache Tomcat 6.

1) Apache Axis2 Binary Distribution - Download
2) Apache Axis2 WAR Distribution - Download
3) Apache Tomcat - Download
4) Eclipse IDE – Download
5) Java installed in your Computer – Download

1.2. Then you have to set the environment variables for Java and Tomcat. There following variables should be added.
JAVA_HOME :- Set the value to jdk directory (e.g. C:\Program Files\Java\jdk1.6.0_21)
TOMCAT_HOME :- Set the value to top level directory of your Tomcat install (e.g. D:\programs\apache-tomcat-6.0.29)
PATH :- Set the value to bin directory of your jdk (e.g. C:\Program Files\Java\jdk1.6.0_21\bin)
1.3. Now you have to add runtime environment to eclipse. There go to Windows –-> Preferences and Select the Server --> Runtime Environments.


There select Apache Tomcat v6.0 and in the next window browse your Apache installation directory and click finish.


1.4. Then click on the Web Service –-> Axis2 Preferences and browse the top level directory of Apache Axis2 Binary Distribution.


2. Creating the Web Service Using Bottom-Up Approach


2.1 First create a new Dynamic Web Project (File --> New –-> Other…) and choose Web --> Dynamic Web Project.


2.2 Set Apache Tomcat as the Target Runtime and click Modify to install Axis2 Web Services project facet.


2.3 Select Axis2 Web Services


2.4 Click OK and then Next. There you can choose folders and click Finish when you are done.

3. Create Web Service Class


Now you can create a Java class that you would want to expose as a Web Service. I’m going to create new class called FirstWebService and create public method called addTwoNumbers which takes two integers as input and return the addition of them.

3.1 Right Click on MyFirstWebService in Project Explorer and select New –-> Class and give suitable package name and class name. I have given com.sencide as package name and FirstWebService as class name.

package com.sencide;
public class FirstWebService { 
 public int addTwoNumbers(int firstNumber, int secondNumber){
  return firstNumber + secondNumber;
 }
}
3.2 Then, select File --> New –-> Other and choose Web Service.


3.3 Select the FirstWebService class as service implementation and to make sure that the Configuration is setup correctly click on Server runtime.


3.4 There set the Web Service runtime as Axis2 (Default one is Axis) and click Ok.


3.5 Click Next and make sure Generate a default service.xml file is selected.


3.6 Click Next and Start the Server and after server is started you can Finish if you do not want to publish the Web service to a test UDDI repository.


You can go to http://localhost:8888/MyFirstWebService/services/listServices to see your running service which is deployed by Axis2. You can see the WSDL by clicking the link FirstWebService.


We have to use Eclipse every time when we want to run the service if we do not create .aar (Axis Archive) file and deploy it to the server. So let’s see how we can create it.

4. Create .aar (Axis Archive) file and Deploying Service


4.1 In your eclipse workspace and go to MyFirstWebService folder and there you can find our web service inside services folder. Go to that directory using command prompt and give following command. It will create the FirstWebService.aar file there.
jar cvf FirstWebService.aar com META-INF



4.2 Then copy the axis2.war file you can find inside the Apache Axis2 WAR Distribution (You downloaded this at the first step) to the webapps directory of Apache Tomcat. Now stop the Apache Tomcat server which is running on Eclipse IDE.


4.3 Using command prompt start the Apache Tomcat (Go to bin directory and run the file startup.bat). Now there will be new directory called axis2 inside the webapps directory. Now if you go to the http://localhost:8080/axis2/ you can see the home page of Axis2 Web Application.


4.4 Then click the link Administration and login using username : admin and password : axis2. There you can see upload service link on top left and there you can upload the created FirstWebService.aar file. This is equal to manually copping the FirstWebService.aar to webapps\axis2\WEB-INF\services directory.


4.5 Now when you list the services by going to http://localhost:8080/axis2/services/listServices you should be able to see our newly added service.


5. Creating a Web service client


5.1 Select File --> New --> Other… and choose Web Service Client


5.2 Set he newly created Axis2 Web service (http://localhost:8080/axis2/services/FirstWebService?wsdl) as the Service definition. Then configure the Server runtime as previously and click finish.


5.3 This will generate two new classes called FirstWebServiceStub.java and FirstWebServiceCallbackHandler.java. Now we can create test class for client and use our web service. Create new class called TestClient.java and paste following code.
package com.sencide;

import java.rmi.RemoteException;
import com.sencide.FirstWebServiceStub.AddTwoNumbers;
import com.sencide.FirstWebServiceStub.AddTwoNumbersResponse;

public class TestClient {

 public static void main(String[] args) throws RemoteException {
  
  FirstWebServiceStub stub = new FirstWebServiceStub();
  AddTwoNumbers atn = new AddTwoNumbers();
  atn.setFirstNumber(5);
  atn.setSecondNumber(7);
  AddTwoNumbersResponse res = stub.addTwoNumbers(atn);
  System.out.println(res.get_return());
  
 }
}
Now you can run the above code as java application and you will get the output as 12 since we are adding 7 and 5.
Download the Eclipse project of the above example (Password:sara)
Your comments are welcome !

Sunday, March 20, 2011

Hibernate Tutorial for Beginners

Hibernate is an Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases.

Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.

By following this tutorial you will get the knowledge of;

1. Setup the Development Environment for Hibernate
2. Create POJO Classes
3. Create Mapping Files
4. Hibernate Configuration
5. Create Startup Helper Class
6. Create Test Class to Load and Store Objects


Let's start.

1. Setup the Development Environment for Hibernate

First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.

1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download

1.1 Setup the Database

I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.


1.2 Create New Project

In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.

First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".


You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.


Now copy following files into that folder.
1. hibernate3.jar (Can be found in distribution bundle)
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )

Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).


Now you will be able to see the referenced libraries as follow (Figure 5).


2. Create POJO Classes

Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.

To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…


User Class
package com.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}
Task Class
package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;
 
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
The id property holds a unique identifier value for a particular user and task. All persistent entity classes will need such an identifier property if you want to use the full feature set of Hibernate.

3. Create Mapping Files

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Right click on the "src" folder and select New --> File and paste following code there. Save it as user.hbm.xml.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>
Tasks.java should also have a mapping file, so create another file and paste following code. Save it as task.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property>  
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>
In the above mapping file you can see the mapping of the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column by giving class="native". If it is not AUTO_INCREMENT one we should use class="assign".

The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.

4. Hibernate Configuration

Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.

Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>
  
  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>
  
  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  
  <!-- Drop and re-create the database schema on startup -->
  <property name="hbm2ddl.auto">update</property>
  
  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>
  
 </session-factory>
</hibernate-configuration>
5. Create Startup Helper Class

You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.

To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
package com.hib;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
6. Create Test Class to Load and Store Objects

Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.

To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
package com.hib;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  Test tst = new Test();
  
  /**
   * adding records 
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");
  
  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity"); 
  tst.addTask(2, "Email", "Send birthday wish to Pubudu"); 
  tst.addTask(2, "SMS", "Send message to Dad"); 
  tst.addTask(2, "Office", "Give a call to Boss");
  
  /**
   *  retrieving data 
   */
  tst.getFullName("Saranga");
  
  /** 
   * full updating records 
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);
  
  /**
   * partial updating records 
   */
  tst.updateLastName(3, "Jayamaha");

  /** 
   * deleting records 
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {
  
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   User user = new User();
   
   user.setFirstName(firstName);
   user.setLastName(lastName);
   
   session.save(user);
   
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 }

 private void addTask(int userID, String title, String description) {
  
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   Task task = new Task();
   
   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);
   
   session.save(task);
   
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 }
 
 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
  
 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 } 

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  } 
 } 
 
 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   
   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 } 
}
If you have setup the database and followed the above steps correctly you should get following output.
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: select user0_.id as id0_, user0_.first_name as first2_0_, user0_.last_name as last3_0_ from users user0_ where user0_.first_name=?
Saranga Rath
Saranga Jaya
Hibernate: update users set first_name=?, last_name=? where id=?
Hibernate: update users set last_name=? where id=?
Hibernate: delete from users where id=?
Hibernate use Hibernate Query Language (HQL) which is powerful than SQL and fully object-oriented. You can get good knowledge about HQL by following HQL Documentation.

I have included the source files of this tutorial with the database. You can download it from here (Password : sara).
Related Posts Plugin for WordPress, Blogger...