Skip to main content

If you don't have an IBM ID and password, register here.

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

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

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.

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

All information submitted is secure.

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

Partha Goswami (partha.ext@gmail.com), Jr. Developer, Protech Infosystems Pvt. Ltd
Partha Goswami
B.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 (kuntalganguly86@gmail.com), Jr. Consultant, Protech Infosystems Pvt. Ltd
Kuntal Ganguly
B.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.

Summary:  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.

Date:  31 Aug 2011
Level:  Intermediate PDF:  A4 and Letter (752 KB | 45 pages)Get Adobe® Reader®

Comments:  

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://download.boulder.ibm.com/ibmdl/pub/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

3 of 7 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=754359
TutorialTitle=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
author1-email=partha.ext@gmail.com
author1-email-cc=
author2-email=kuntalganguly86@gmail.com
author2-email-cc=

Table of contents

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).