Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client

This tutorial demonstrates how to develop database driven web service using Hibernate and invoking it with J2ME and Android Client. Finally it shows how to develop a restful web service and deploy it in the Google cloud and then consuming the web service with an Android client.

Partha Goswami, Jr. Developer, Protech Infosystems Pvt. Ltd

Partha GoswamiB.Tech with more than 13 months experience in developing J2EE, Web Service (JAX-WS), J2ME and Android application.Currently associated with Protech Infosystems, Kolkata as Junior Consultant.Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Oracle SOA Suite11g, EZlegacy , BIRT and DB2 express C) . Apart from his passion for Latest Technology, he has numerous other interests including Cricket and Tabla.



Kuntal Ganguly, Jr. Consultant, Protech Infosystems Pvt. Ltd

Kuntal GangulyB.Tech with more than 13 months experience in developing J2EE, Web Service (JAX-WS), J2ME and Android application.Currently associated with Protech Infosystems, Kolkata as Junior Consultant.Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Oracle SOA Suite11g, EZlegacy , Active MQ , BIRTand DB2 express C) and technologies(GWT and Android). Apart from his passion for Latest Technology, he has numerous other interests including Cricket, Yoga and Body Building.



31 August 2011

Also available in Japanese

Before you start

This tutorial is for developers who build applications that use database driven web services with persistence framework like Hibernate. By using web services, your application can publish its function or message to the rest of the world. Web services use XML to code and to decode data, and SOAP to transport it (using open protocols). Representational State Transfer (REST) has gained widespread acceptance across the Web as a simpler alternative to SOAP. It s a key design idiom that embraces a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URLs.

About this tutorial

This Tutorial will describes the way of developing web service (JAX-WS and REST). Web services can be implemented using different application protocols like SOAP, XML, JSON, Restful HTTP, and support various transport protocols like HTTP or JMS (Java Message Service). This tutorial will help you in developing a Database Driven Information Retrieval Web service with Hibernate, followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed web services with mobile clients (J2ME and Android).

Objectives

In this tutorial, learn how to:

  • Develop and deploy a JAX-WS Web Service, which operates on DB2 database using Hibernate as an ORM framework.
  • Develop a simple Restful webservice and deploy it in Cloud (GAE).
  • Invoke both the above Web Services using an Android Client and a J2ME client.

Prerequisites

This tutorial assumes familiarity with some basic concepts of the Eclipse IDE, and basic understanding of Web Service architecture, see Resources for additional information.


Introduction

What is web service?

A web service is a network accessible interface to application functionality, built using standard Internet technologies. It is software application that can be accessed remotely using different XML-based languages. Normally, a web service is identified by a URL,just like any other Web site. What makes web services different from ordinary Web sites is the type of interaction that they can provide.

Benefits of web service

A web service is a very well known open technology standard provides a number of benefits including:

  • Increase competition among vendors, resulting in lower product costs.
  • Ease transition from one product to another, resulting in lower training costs.
  • Increase the ability for parties to interoperate, resulting in lower maintenance costs.
  • Ensure a greater degree of adoption and longevity for a standard. A large degree of usage from the vendors and the users leads to a higher degree of acceptance.

How are web services used?

There are three main ways in which an organization can move deploy web services. These are as follows:

  1. Creating a new web service from scratch (Contract First): The developer creates the functionalities of the services as well as preparing a document to describe those services.
  2. Exposing an existing functionality through a web service (Code First): Here, the functionalities of the service already exist. Only the service description needs to be implemented.
  3. Integrating web services from other vendors or business partners (Meet in the Middle): There are instances where using a service implemented by another is more feasible than building from scratch. On these occasions, the organization will be required to integrate others' or even business partners' Web Services.

The real utility of the web service concept is present in the second and the third methods, which leads to other web services and applications that can be used in existing applications.

Web service and SOA

SOA and web services are two different things, but web services are the preferred standards-based way to realize SOA. Service-oriented architecture (SOA) is an architectural style for building software applications that use services available in a network such as the web. It promotes loose coupling between software components so that they can be reused. Applications in SOA are built based on services. A service is an implementation of well-defined business functionality, and such services can then be consumed by clients in different applications or business processes.

As SOA promotes loose coupling it obviously allows reuse of existing assets where new services can be created from an existing IT infrastructure of systems. In other words, it enables businesses to leverage existing investments by allowing them to reuse existing applications, and promises interoperability between heterogeneous applications and technologies. SOA provides a level of flexibility that wasn't possible before in the sense that:

  • Services are software components with well-defined interfaces that are implementation-independent. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests.
  • Services are self-contained (perform predetermined tasks) and loosely coupled (for independence).
  • Services can be dynamically discovered.
  • Composite services can be built from aggregates of other services.

SOA uses the find-bind-execute paradigm as shown in Figure 1. In this paradigm, service providers register their service in a public registry. This registry is used by consumers to find services that match certain criteria. If the registry has such a service, it provides the consumer with a contract and an endpoint address for that service.

SOA-based applications are distributed multi-tier applications that have presentation, business logic, and persistence layers. Services are the building blocks of SOA applications. While any functionality can be made into a service, the challenge is to define a service interface that is at the right level of abstraction. Services should provide coarse-grained functionality.

Realizing SOA with web services

Web services are software systems designed to support interoperable machine-to-machine interaction over a network. This interoperability is gained through a set of XML-based open standards, such as WSDL, SOAP, and UDDI.

Interoperability is the most important principle of SOA. This can be realized through the use of web services, as one of the key benefits of web services is interoperability, which allows different distributed web services to run on a variety of software platforms and hardware architectures. The advent of web services and SOA offers potential for lower integration costs and greater flexibility. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests. Web services are the next step in the Web's evolution, since they promise the infrastructure and tools for automation of business-to-business relationships over the Internet.

REST vs. SOAP

REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (let's face it you use soap to wash, and you rest when you are tired). The main advantages of REST web services are:

  • Lightweight - not a lot of extra xml markup
  • Human Readable Results
  • Easy to build - no toolkits required

SOAP also has some advantages:

  • Easy to consume - sometimes
  • Rigid - type checking, adheres to a contract
  • Development tools

For consuming web services, it is sometimes a tossup between which is easier. For instance Google's Ad Words web service is really hard to consume, as it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon's REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA, and you can leverage SOA without leveraging cloud computing, the real value of cloud computing is the ability to use services, data, and processes that can exist outside of the firewall in somebody else's datacenter. Indeed, one can consider cloud computing the extension of SOA out to cloud-delivered resources, such as storage-as-a-service, data-as-a-service, platform-as-a-service. The trick is to determine which services, information, and processes are good candidates to reside in the clouds as well as which cloud services should be abstracted within the existing or emerging SOA. SOA not only is a mechanism to drive more reuse and agility but also offers the ability to figure out what should stay local and what should find a place in the clouds. Good SOA leads to a good cloud computing strategy, which leads to reduced costs, enhanced agility, and more excitement around enterprise computing than we have seen in a while.

SOA Can Gain the following from Cloud Computing

Service Design - Many SOA projects have a tendency to build in services that are too course-grained, too fine-grained, or just not at all well designed. In reality, unless services are not well defined and well designed, they will not sell well when delivered on demand. The major cloud computing providers, who provide services through the cloud, spends a lot of time on the design of the services, including usability and durability.

Service Expandability - Cloud computing services are designed to expand as needed, and those who leverage cloud services do so because they can get the services on demand, when they need them.

What Is Google App Engine?

Google App Engine lets you run your web applications on Google's infrastructure. It provide both development community and the enterprise-computing space. App Engine applications are easy to build, easy to maintain.

The App Engine enables you to build enterprise-scalable applications on the same infrastructure that Google uses.

App Engine is structured differently from the typical web application server. At its core, App Engine restricts your application from any access to the physical infrastructure, preventing you from opening sockets, running background processes (although you can use cron), and using other common back-end routines that application developers take for granted in other environments.

App Engine costs nothing to get started. All applications can use up to 500 MB of storage and enough CPU and bandwidth to support an efficient app serving around 5 million page views a month, absolutely free. When you enable billing for your application, your free limits are raised, and you only pay for resources you use above the free levels.


Configuration and development

Example I – Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with each other in a platform- and programming language-independent manner. It is a software interface that describes a collection of operations that can be accessed over the network through standardized XML messaging. It uses protocols based on the XML language to describe an operation to execute or data to exchange with another web service.

Here we will create a web service that basically interacts with the a database (in this case DB2) using Hibernate as a ORM framework .As discussed earlier that web services are loosely coupled in nature, so we will invoke this web service using a Android client and a J2ME client (not supporting JSR-172 ).

This is a simple Information Retrieval Database driven web service using Hibernate with Code First Approach, where user will input the Employee ID to retrieve the Information (i.e. Name, Address, Date of Birth and Contact Number) about the Employee. To setup and run this example one need to know few things given below:

Eclipse IDE: An integrated development environment (IDE) is an all-in-one tool for writing, editing, compiling, and running computer programs. And Eclipse provides an excellent integrated development environment. You can find the latest release of eclipse in www.eclipse.org.

Eclipse Web Tools Platform (WTP): The Eclipse Web Tools Platform (WTP) consists of software produced by the Eclipse Project combined with third party software from other open source projects. These plug-in sets up the environment for easy J2EE based application development. You can download a zipped version of the plug-in from: http://www.eclipse.org/webtools/ and then extract the plug-in in the eclipse directory (where you have downloaded and extracted the Eclipse IDE) and restart the IDE.

Websphere Application Server Community Edition 2.1.1 (WASCE): IBM® WebSphere® Application Server Community Edition (Community Edition) is a member of the IBM WebSphere Application Server family. Community Edition is a lightweight Java Platform Enterprise Edition (Java EE) application server built on Apache Geronimo, the open source application server project of the Apache Software Foundation. The community using Community Edition consists of all sorts of people and companies, who design, develop, deploy, or utilize Java EE solutions. We can get the latest version of Community Edition by going to http://www.ibm.com/developerworks/downloads/ws/wasce/.

WASCE and eclipse plug-in (WEP): In order to work with Community Edition within Eclipse, the WebSphere Application Server Community Edition Eclipse Plug-in (WEP) must be installed. WEP is the adapter that facilitates Web application development in Eclipse with Community Edition. You can download a zipped version of the plug-in from: http://public.dhe.ibm.com/software/websphere/wasce/updates/and then extract the plug-in in the eclipse directory (where you have downloaded and extracted the Eclipse IDE) and restart the IDE.

Hibernate: Hibernate is an open source object (relational) mapping library for the Java language that provides persistent classes and logic without caring how to handle the data. Hibernate solves Object-Relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. You can download it from http://www.hibernate.org/downloads.

DB2 Express C: DB2 Express-C data server software ("DB2 Express-C") is a member of the IBM DB2 family of powerful data server software for managing both relational and XML data. DB2 Express-C is a free, no-limits, and easy to use edition of DB2. The 'C' in DB2 Express-C stands for the Community. You can download it from www.ibm.com/db2/express/download.html.

Set up the environment

  1. Install JDK 1.5 or above in your system.
  2. Start Eclipse after deploying the necessary WTP and WEP plugins.
  3. Install WASCE 2.1.1.
  4. Link the server in eclipse using WEP and start WASCE.
  5. Install DB2 Express-C.
  6. Create the following table as shown in the listing.

    CREATE TABLE "ADMINISTRATOR"."USER_INFO" (
    "USER_ID" VARCHAR(10) NOT NULL ,
    "ADDRESS" VARCHAR(50) NOT NULL ,
    "DATE_OF_BIRTH" DATE NOT NULL ,
    "CONTACT_NO" VARCHAR(12) NOT NULL ) ;
Administrator table
Administrator table

Developing information retrieval web service and deploying in WASCE

  1. Create a new Dynamic Web Project named UserInfo (select WASCE 2.1.1 as target runtime environment).
  2. Add the following jars in the WEB-INF |lib directory
    antlr-2.7.4.jar
    cglib-full-2.0.2.jar
    commons-collections-2.1.1.jar
    dom4j-1.5.2.jar
    ehcache-1.1.jar
    hibernate3.jar
    jta.jar
    log4j-1.2.9.jar

For connecting to DB2 database server add the following jars located at "..\IBM\SQLLIB\java\" directory
db2java.zip
db2jcc4.jar
sqlj4.zip

Also add commons-logging-1.0.4.jar to WebContent|WEB-INF directory and add it the project build path.

Note Figure 2, shows the project structure.

UserInfo Project Directory structure
UserInfo Project Directory structure
  1. Create a java bean class UserBean.java under package com.ibm.model which will be our persistent class. See the Listing 1:
Listing 1. UserBean.java
package com.ibm.model;
import java.util.Date;

public class UserBean {
	
	String ID;
	String Address;
	Date DOB;
	String ContactNo;
	
	
	public String getID() {
		return ID;
	}
	public void setID(String iD) {
		ID = iD;
	}
	
	public String getAddress() {
		return Address;
	}
	public void setAddress(String address) {
		Address = address;
	}
	public Date getDOB() {
		return DOB;
	}
	public void setDOB(Date dOB) {
		DOB = dOB;
	}
	public String getContactNo() {
		return ContactNo;
	}
	public void setContactNo(String contactNo) {
		ContactNo = contactNo;
	}
	
	
}
  1. Create a interface named UserSEI.java under package com.ibm.service which will act as a service endpoint interface. See the Listing 2.
Listing 2. UserSEI.java
package com.ibm.service;

import javax.jws.WebService;

@WebService (name="UserSEI",
		targetNamespace="http://service.ibm.com")

public interface UserSEI {
	
	public String getInfo(String user_Id);

}
  1. Create the service implementation class UserServiceImpl.java which will contain the main logic. Annotate the class with @WebService to specify the following parameters.

serviceName: Name of the service(a class with this name will be created during stub generation for the client).

portName: the end port (a get "portName" method will be created in the stub classes.)

endpointInterface: the interface class which serves as a endpoint to the service (in this case the UserSEI.java class).

targetNamespace: the name space for the web service after deployment.

  1. Inside UserServiceImpl.java class create a method called getInfo which returns a string containing employee information and takes String input (employee ID) as its parameter. See the Listing 3.
Listing 3. UserServiceImpl.java
package com.ibm.service;

import java.util.Iterator;
import java.util.List;
import javax.jws.WebService;

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

import com.ibm.model.*;

@WebService(serviceName = "HiberService",
		portName = "HiberPort",
		endpointInterface = "com.ibm.service.UserSEI",
		targetNamespace = "http://service.ibm.com")
		
public class UserImpl implements UserSEI{
	
	public String getInfo(String user_Id){
	
	String s="";
	Session session = null;

// Create a new sessionFactory object 
		
	SessionFactory sessionFactory = new Configuration().
                        configure().buildSessionFactory();		
	session =sessionFactory.openSession();

//Build the prepared query	

	Query query = session.createQuery("from UserBean use where use.ID =:ID" ).
                        setString("ID",user_Id);

	List result = query.list();
	Iterator it = result.iterator();
	while(it.hasNext()){
		UserBean user = (UserBean)it.next();
		
s="USER ID :"+user.getID()+ " , ADDRESS  :" +user.getAddress()+ "  , DATE OF BIRTH  
                        :"+user.getDOB()+ "  , CONTACT NO :  " +user.getContactNo()  ;
		
		
	}
	

	session.close();
	
	if(!s.equals("")){
		return s;	
	}
	else{
		return "No Data Found";
	}
	
	}
}
  1. Right click the src folder, select New > File and create a file named hibernate.cfg.xml which contains the database configuration. See Listing 4:
Listing 4. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory> 

<property name="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
 <property name="hibernate.connection.url">jdbc:db2://localhost:50000/USER</property>
      <property name="hibernate.connection.username">ADMINISTRATOR</property>
      <property name="hibernate.connection.password">server</property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="hibernate.default_schema">ADMINISTRATOR</property>
      <property name="show_sql">true</property>
      <property name="dialect">org.hibernate.dialect.DB2Dialect</property>
      <property name="hibernate.hbm2ddl.auto">read</property>
      <!-- Mapping files -->
      <mapping resource="UserBean.hbm.xml"/>

</session-factory>
</hibernate-configuration>
  1. Again right click src folder, select New > File and create another file named UserBean.hbm.xml which provides mapping information which maps the UserBean.java class to the UserInfo table in DB2 database.See Listing 5:
Listing 5. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.ibm.model.UserBean" table="USER_INFO">
   
   <id name="ID"  column="USER_ID" >
   <generator class="assigned"/>
   </id>    
       
 <property name="Address" type="string">
    <column name="ADDRESS"/>
  </property>
  
  <property name="DOB" type="date">
    <column name="DATE_OF_BIRTH"/>
  </property>
  
  <property name="ContactNo" type="string">
    <column name="CONTACT_NO"/>
  </property>
  
 </class>
</hibernate-mapping>
  1. Edit the web.xml file as shown in Listing 6.
Listing 6. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>UserInfo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>user</servlet-name>
    <servlet-class>com.ibm.service.UserImpl</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>user</servlet-name>
    <url-pattern>/user</url-pattern>
  </servlet-mapping>
</web-app>
  1. Create a deployment plan for WASCE by editing the geronimo-web.xml file as shown in Listing 7.
Listing 7. geronimo-web.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" 
xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" 
xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" 
xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" 
xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" 
xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" 
xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" 
xmlns:pers="http://java.sun.com/xml/ns/persistence" 
xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" 
xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" 
xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
    <dep:environment>
        <dep:moduleId>
            <dep:groupId>default</dep:groupId>
            <dep:artifactId>UserInfo</dep:artifactId>
            <dep:version>1.0</dep:version>
            <dep:type>car</dep:type>
        </dep:moduleId>
    </dep:environment>
    <web:context-root>/UserInfo</web:context-root>
</web:web-app>

Select project right click Run As > Run on Server (WASCE). Type the following URL (http://localhost:8080/UserInfo/user) to check your service being deployed in server successfully. See Figure 3.

Service Deployed in the Server
Service Deployed in the Server

Check the webservice WSDL location at http://localhost:8080/UserInfo/user?WSDL as shown in Figure 4.

WSDL Location
WSDL Location

Developing J2ME Client for the Information Retrieval service

To develop a J2ME client (not supporting JSR-172 standard) for consuming the web service we would require the following software components.

  1. Create a J2ME Project named User in the Emulator.
  2. Add the ksoap2-j2me-core-2.1.2 jar to the resource folder in the project.
J2ME Project Structure
J2ME Project Structure
  1. Create a Midlet name J2meNonJSR172Client.java under the package com.ibm.j2me.client. See Listing 8.
Listing 8. J2meNonJSR172Client.java
package com.ibm.j2me.client;

import javax.microedition.midlet.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.*;
import org.ksoap2.serialization.PropertyInfo;


public class J2meKsoapClient extends MIDlet implements CommandListener {
    private Form firstScreen;

    private Display display;

private TextField id = new TextField("Enter User ID :", "1002", 30, TextField.ANY);


StringItem resultItem=new StringItem("","");

    // Navigation commands

    private static final Command EXIT_COMMAND =new Command("Exit", Command.EXIT, 1);
    private static final Command SEND =new Command("SEND", Command.OK, 1);

    public J2meKsoapClient() {

        initFirstScreen();


    }

    private void initFirstScreen() {

        firstScreen = new Form("Information Retrieval ");
        StringItem item = new StringItem(""," ");
        firstScreen.append(item);
        firstScreen.append(id);
               firstScreen.addCommand(SEND);
        firstScreen.setCommandListener(this);
    }


    public void startApp() {
        // The initial display is the first form
        display=Display.getDisplay(this);
        display.setCurrent(firstScreen);

    }

    

    public void pauseApp() {
        // No implementation required
    }

    
    public void destroyApp(boolean unconditional) {
        // No implementation required
    }

    
    public void commandAction(Command command, Displayable displayable) {
        if (command == EXIT_COMMAND) {
            // Exit the MIDlet
            notifyDestroyed();
        }


    else if(command == SEND) {
        soapCall() ;
    }


    }

    public void soapCall() {

try{
SoapObject rpc = new SoapObject("http://service.ibm.com","getInfo");

  PropertyInfo propInfo1=new PropertyInfo();
  propInfo1.name="arg0";
  propInfo1.type=PropertyInfo.STRING_CLASS;
  rpc.addProperty(propInfo1,id.getString());


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(rpc);


HttpTransport ht = new HttpTransport("http://192.168.1.5:8080/UserInfo/user");
ht.call("http://service.ibm.com/getInfo",envelope);

 SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();

resultItem.setText(resultsRequestSOAP.toString());
 firstScreen.append(resultItem);

}
catch (Exception e){
    		System.out.println("Exception : "+ e.getMessage());
                 e.printStackTrace();
    	}

    }
}
  1. Now Build the Project and Run.
  2. Now enter the Employee ID and click Send button to get the desired information. You will see the output as shown in Figure 6.
J2ME Emulator Output Screen
J2ME Emulator Output Screen

Note: For Invoking web service through JSR-172 compliant Handset (using Stub) please refer to the following Tutorial.

Developing Android Client for the Information Retrieval service

To develop an Android client for the web service we would require the following software components.

  1. Create an Android Project named Android Client as shown in Figure 7.
Create New Android Project in Eclipse
Create New Android Project in Eclipse
  1. Add the ksoap2-android-assembly-2.4-jar to the build path of the project as shown in Figure 8.
ksoap2-android-assembly-2.4-jar directory
ksoap2-android-assembly-2.4-jar directory
  1. Now create a class name AndroidWSClient under the package com.ibm.android.client. See Listing 9.
Listing 9. AndroidWSClient.java
package com.ibm.android.client;

// ksoap-android library imports

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.serialization.PropertyInfo;

// Android imports

import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;


public class AndroidWSClient extends Activity {

 // Declaring web service WSDL,Namespace,Method

 private static final String NAMESPACE = "http://service.ibm.com";
 private static String URL = "http://192.168.1.5:8080/UserInfo/user"; 
 private static final String METHOD_NAME = "getInfo";
 private static final String SOAP_ACTION =  "http://service.ibm.com/getInfo";
 
 private TextView lblResult;
 private EditText text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  text = (EditText) findViewById(R.id.editText);
  lblResult = (TextView) findViewById(R.id.result);
  
  
  final Button button = (Button) findViewById(R.id.buttons);
  button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {

 
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 

  
  PropertyInfo propInfo=new PropertyInfo();
  propInfo.name="arg0";
  propInfo.type=PropertyInfo.STRING_CLASS;
  request.addProperty(propInfo, text.getText().toString());  

  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 

  envelope.setOutputSoapObject(request);
 HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

  try {
   androidHttpTransport.call(SOAP_ACTION, envelope);
  
    SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
  

   lblResult.setText(resultsRequestSOAP.toString());
   
 
  } catch (Exception e) {
	  System.out.println();
	  
   
  }
      }
  });

 }
}
  1. Now edit main.xml file under res|layout folder as shown in Listing 10.
Listing 10. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <TextView 
    android:id="@+id/result" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
    
<EditText android:layout_height="wrap_content" android:text="Enter Employee ID" 
        android:id="@+id/editText" android:layout_width="wrap_content"></EditText>
<Button android:text="SEND" android:id="@+id/buttons" android:layout_width="wrap_content" 
        android:layout_height="wrap_content"></Button>

</LinearLayout>
  1. Add the following uses permission in the AndroidManifest.xml file. See Listing 11.
Listing 11. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ibm.android.client"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidWSClient"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    
    <uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
</manifest>
  1. Now Run as Android Application. See Figure 9.
Run Android Project
Run Android Project

Once the Android emulator and Activity starts, you will see the following in the console See Figure 10.

Android Console Output
Android Console Output
  1. Now Enter the Employee ID of the Employee whose information and Detail you want to retrieve as shown in Figure 11.
Android Invoke Preview
Android Invoke Preview

For example '1002' used in this tutorial or the Employee ID that you have in your Database and click the send button to retrieve the information as response from the web service developed before. See Figure 12.

Android Service Response Preview
Android Service Response Preview

Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services. It's essential that consumers can access and experiment with a service while it's being developed. The Google App Engine (GAE) platform is free at the entry level, and provides sufficient capabilities to deploy Restful applications with a public URI.

This is a very simple parameterized Hello User restful web services developed using Jersey and then deploying it in the Google Cloud, where user will input his/her name to receive welcome greetings. To setup and run this example one need to know few things given below:

Environment Setup

Google APP Engine Preview
Google APP Engine Preview
  • From the "My Applications" view on the App-engine page, create a new Application ID. See Figure Figure 14.
Google APP Engine My Applications Preview
Google APP Engine My Applications Preview
  • Install the Eclipse plug-in for Google APP
  • Download JAXB 2.1; (note that JAXB 2.2 is not supported by GAE currently) unpack the file or, if your systems is unix-based, run:
    java -jar JAXB2_20081030.jar
  • Download the JAX-RS reference implementation (jersey), and unpack

Developing and Deploying a Restful App on Google Cloud (GAE)

  1. In Eclipse, create a new Web Application Project named RestCloudComputing (File | New |Web Application Project) as shown below (uncheck the Google Web Toolkit). See Figure 15.
Google APP Engine New Project
Google APP Engine New Project
  1. Place the JAXB and JAX-RS jars in the Eclipse project under |war|WEB-INF|lib. See Figure 16.
GAE Project jars
GAE Project jars
  1. Also, add the jars to the Java Build Path of the project. See Figure 17.
Add to Build Path
Add to Build Path
  1. Now create a Restful Class named TestRestService.java under package com.ibm.rest as shown below in Listing 12.
Listing 12. TestRestService.java
package com.ibm.rest;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;


@Path("/testuser/{Username}")
public class TestRestService {
	 @GET
	    @Produces("text/plain")
	    public String getWelcome(@PathParam("Username")String user) {
	        return "Welcome  "+ user +"  to DeveloperWorks!";
	    }

}
  1. Update web.xml in the following way shown in the Listing 13.
Listing 13. web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet><servlet-name>jersey</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
   <init-param>
       <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.ibm</param-value>
    </init-param>
       <load-on-startup>1</load-on-startup>
    </servlet>

 <servlet-mapping>
    <servlet-name>jersey</servlet-name>
       <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
<welcome-file-list>
	<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
  1. Deploy app engine from Eclipse, by clicking on the "Deploy to App Engine Project" icon in the toolbar (installed by the GAE plug-in). See Figure 18.
Deploy Application to Cloud
Deploy Application to Cloud
  1. Deploy to Google Cloud (GAE) by signing with the email and password that you created during GAE sign-up. See Figure 19.
Login to GAE
Login to GAE
  1. Click on the App Engine Project settings link to give your Application ID that you have created before. See Figure 20.
Set the Application ID and Version number
Set the Application ID and Version number
  1. After success full Deployment you will see in the console as shown in Figure 21.
GAE output console
GAE output console

After this you can check your application by going to the following URL : http://restingae.appspot.com

You can test or invoke the restful web service through web client, i.e. browser, just go to the following link with your name (like here I am using Kuntal). http://restingae.appspot.com/rest/testuser/Kuntal. See Figure 22.

Test Rest Service through browser URL
Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

  1. Create an Android Project named AndroidRSClient
  2. Now create a class name AndroidRestClient under the package com.ibm.android.rest.client. See Listing 14.
Listing 14. AndroidRestClient.java
package com.ibm.android.rest.client;
// java net import
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
// Android imports
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;


public class AndroidRestClient extends Activity {

 // Declaring web service WSDL,Namespace,Method
 
 
 private TextView textView;
 private EditText text;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  text = (EditText) findViewById(R.id.editText);
  textView = (TextView) findViewById(R.id.result);
  
  
  final Button button = (Button) findViewById(R.id.buttons);
  button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {

 
    	  try
          {
    		  String s=text.getText().toString();
              URL url = new URL("http://restingae.appspot.com/rest/testuser/"+s );
              URLConnection urlConnection = url.openConnection();
              HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
   
              // Get the HTTP response code
              if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
              {
                  InputStream inputStream = httpConnection.getInputStream();
   
                  if(inputStream != null)
                  {
                      StringBuilder stringBuilder = new StringBuilder();
                      String line;
   
                      try
                      {
                          BufferedReader reader = new BufferedReader(
                                  new InputStreamReader(inputStream, "UTF-8"));
   
                          while ((line = reader.readLine()) != null)
                          {
                              stringBuilder.append(line).append("\n");
                          }
                      }
                      finally
                      {
                          inputStream.close();
                      }
                      textView.setText(stringBuilder.toString());
                  }
   
              }
   
              if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
              {
                  textView.setText("404 (not found)");
              }
          }
          catch (MalformedURLException urlEx)
          {
              textView.setText(urlEx.getMessage());
          }
          catch (IOException ioEx)
          {
              textView.setText(ioEx.getMessage());
          }
          catch (Exception ex)
          {
              textView.setText(ex.getMessage());
          }
      }
  });
 
}  
}
  1. Now edit main.xml file under res|layout folder. See Listing 15.
Listing 15. AndroidRestClient.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
 <TextView 
    android:id="@+id/result" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
    
<EditText android:layout_height="wrap_content" android:text="Partha"
android:id="@+id/editText" android:layout_width="wrap_content"></EditText>
<Button android:text="SEND" android:id="@+id/buttons"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

</LinearLayout>
  1. Add the following uses permission in the AndroidManifest.xml file to access the internet.
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
  1. Now Run As Android Application and Enter your Name (like here 'Partha')and Click send to receive a welcome greetings from the restful as shown below in Figure 23.
Invoke Service through Android
Invoke Service through Android

Conclusion

Conclusion

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in very short interval of time. Also you get a overview of SOA and Cloud Computing which goes hand in hand. SOA and Cloud Computing together provides a much scalable platform for large Enterprise applications reducing cost and increasing ROI.


Download

DescriptionNameSize
Sample code for this tutorialcode.zip175KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=754359
ArticleTitle=Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client
publish-date=08312011