cloud to be invoked by android and j2me client hibernate ... · followed by hello user restful web...

32
© Copyright IBM Corporation 2011 Trademarks Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client Page 1 of 32 Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client Partha Goswami Kuntal Ganguly August 31, 2011 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. 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.

Upload: others

Post on 05-Oct-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

© Copyright IBM Corporation 2011 TrademarksDeveloping database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 1 of 32

Developing database driven web service usinghibernate and implementing Restful web service incloud to be invoked by Android and J2ME ClientPartha GoswamiKuntal Ganguly

August 31, 2011

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

Before you startThis tutorial is for developers who build applications that use database driven web services withpersistence framework like Hibernate. By using web services, your application can publish itsfunction 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) hasgained widespread acceptance across the Web as a simpler alternative to SOAP. It s a key designidiom that embraces a stateless client-server architecture in which the web services are viewed asresources and can be identified by their URLs.

About this tutorialThis Tutorial will describes the way of developing web service (JAX-WS and REST). Web servicescan 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 tutorialwill 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). Finallyconsuming the developed web services with mobile clients (J2ME and Android).

ObjectivesIn this tutorial, learn how to:

• Develop and deploy a JAX-WS Web Service, which operates on DB2 database usingHibernate 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.

Page 2: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 2 of 32

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

IntroductionWhat is web service?A web service is a network accessible interface to application functionality, built using standardInternet 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 canprovide.

Benefits of web serviceA web service is a very well known open technology standard provides a number of benefitsincluding:

• 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 asfollows:

1. Creating a new web service from scratch (Contract First): The developer creates thefunctionalities 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 functionalitiesof 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): Thereare instances where using a service implemented by another is more feasible than buildingfrom scratch. On these occasions, the organization will be required to integrate others' oreven business partners' Web Services.

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

Web service and SOASOA 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 buildingsoftware applications that use services available in a network such as the web. It promotes loosecoupling between software components so that they can be reused. Applications in SOA are builtbased on services. A service is an implementation of well-defined business functionality, and suchservices can then be consumed by clients in different applications or business processes.

Page 3: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 3 of 32

As SOA promotes loose coupling it obviously allows reuse of existing assets where new servicescan be created from an existing IT infrastructure of systems. In other words, it enables businessesto leverage existing investments by allowing them to reuse existing applications, and promisesinteroperability between heterogeneous applications and technologies. SOA provides a level offlexibility 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 (thewhat) from its implementation (the how). Such services are consumed by clients that are notconcerned with how these services will execute their requests.

• Services are self-contained (perform predetermined tasks) and loosely coupled (forindependence).

• 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, serviceproviders register their service in a public registry. This registry is used by consumers to findservices that match certain criteria. If the registry has such a service, it provides the consumer witha contract and an endpoint address for that service.

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

Realizing SOA with web servicesWeb services are software systems designed to support interoperable machine-to-machineinteraction over a network. This interoperability is gained through a set of XML-based openstandards, such as WSDL, SOAP, and UDDI.

Interoperability is the most important principle of SOA. This can be realized through the use ofweb services, as one of the key benefits of web services is interoperability, which allows differentdistributed 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 greaterflexibility. An important aspect of SOA is the separation of the service interface (the what) fromits implementation (the how). Such services are consumed by clients that are not concernedwith how these services will execute their requests. Web services are the next step in the Web'sevolution, since they promise the infrastructure and tools for automation of business-to-businessrelationships over the Internet.

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

• Lightweight - not a lot of extra xml markup

Page 4: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 4 of 32

• 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 instanceGoogle's Ad Words web service is really hard to consume, as it uses SOAP headers, and anumber of other things that make it kind of difficult. On the converse, Amazon's REST web servicecan sometimes be tricky to parse because it can be highly nested, and the result schema can varyquite a bit based on what you search for.

Cloud Computing and SOA ConvergenceWhile you can certainly leverage a cloud without practicing SOA, and you can leverage SOAwithout 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, suchas storage-as-a-service, data-as-a-service, platform-as-a-service. The trick is to determine whichservices, information, and processes are good candidates to reside in the clouds as well aswhich cloud services should be abstracted within the existing or emerging SOA. SOA not only isa mechanism to drive more reuse and agility but also offers the ability to figure out what shouldstay local and what should find a place in the clouds. Good SOA leads to a good cloud computingstrategy, which leads to reduced costs, enhanced agility, and more excitement around enterprisecomputing than we have seen in a while.

SOA Can Gain the following from Cloud ComputingService 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 welldefined and well designed, they will not sell well when delivered on demand. The major cloudcomputing providers, who provide services through the cloud, spends a lot of time on the design ofthe services, including usability and durability.

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

What Is Google App Engine?Google App Engine lets you run your web applications on Google's infrastructure. It provide bothdevelopment community and the enterprise-computing space. App Engine applications are easy tobuild, easy to maintain.

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

Page 5: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 5 of 32

App Engine is structured differently from the typical web application server. At its core, App Enginerestricts your application from any access to the physical infrastructure, preventing you fromopening sockets, running background processes (although you can use cron), and using othercommon 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 andenough CPU and bandwidth to support an efficient app serving around 5 million page views amonth, 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 developmentExample I – Information retrieval web service using HibernateWeb services is a technology that allows applications to communicate with each other in aplatform- and programming language-independent manner. It is a software interface that describesa collection of operations that can be accessed over the network through standardized XMLmessaging. It uses protocols based on the XML language to describe an operation to execute ordata to exchange with another web service.

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

This is a simple Information Retrieval Database driven web service using Hibernate with CodeFirst 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 exampleone 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 integrateddevelopment environment. You can find the latest release of eclipse in Eclipse.org.

Eclipse Web Tools Platform (WTP): The Eclipse Web Tools Platform (WTP) consists of softwareproduced by the Eclipse Project combined with third party software from other open sourceprojects. 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 thenextract the plug-in in the eclipse directory (where you have downloaded and extracted the EclipseIDE) 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 WebSphereApplication Server family. Community Edition is a lightweight Java Platform Enterprise Edition(Java EE) application server built on Apache Geronimo, the open source application server projectof the Apache Software Foundation. The community using Community Edition consists of allsorts of people and companies, who design, develop, deploy, or utilize Java EE solutions. We

Page 6: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 6 of 32

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, theWebSphere Application Server Community Edition Eclipse Plug-in (WEP) must be installed. WEPis the adapter that facilitates Web application development in Eclipse with Community Edition. Youcan 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 downloadedand extracted the Eclipse IDE) and restart the IDE.

Hibernate: Hibernate is an open source object (relational) mapping library for the Java languagethat provides persistent classes and logic without caring how to handle the data. Hibernatesolves Object-Relational impedance mismatch problems by replacing direct persistence-relateddatabase 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 theIBM DB2 family of powerful data server software for managing both relational and XML data. DB2Express-C is a free, no-limits, and easy to use edition of DB2. The 'C' in DB2 Express-C stands forthe Community.

Set up the environment1. 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

Developing information retrieval web service and deploying in WASCE1. 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

Page 7: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 7 of 32

cglib-full-2.0.2.jarcommons-collections-2.1.1.jardom4j-1.5.2.jarehcache-1.1.jarhibernate3.jarjta.jarlog4j-1.2.9.jar

For connecting to DB2 database server add the following jars located at "..\IBM\SQLLIB\java\"directorydb2java.zipdb2jcc4.jarsqlj4.zip

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

Note Figure 2, shows the project structure.

UserInfo Project Directory structure

3. Create a java bean class UserBean.java under package com.ibm.model which will be ourpersistent class. See the Listing 1:

Listing 1. UserBean.javapackage com.ibm.model;

Page 8: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 8 of 32

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

}

4. Create a interface named UserSEI.java under package com.ibm.service which will act as aservice endpoint interface. See the Listing 2.

Listing 2. UserSEI.javapackage com.ibm.service;

import javax.jws.WebService;

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

public interface UserSEI {

public String getInfo(String user_Id);

}

5. Create the service implementation class UserServiceImpl.java which will contain the mainlogic. 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 generationfor the client).

Page 9: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 9 of 32

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 theUserSEI.java class).

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

6. Inside UserServiceImpl.java class create a method called getInfo which returns a stringcontaining employee information and takes String input (employee ID) as its parameter. Seethe Listing 3.

Listing 3. UserServiceImpl.javapackage 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("")){

Page 10: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 10 of 32

return s; } else{ return "No Data Found"; }

}}

7. Right click the src folder, select New > File and create a file named hibernate.cfg.xml whichcontains 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>

8. Again right click src folder, select New > File and create another file namedUserBean.hbm.xml which provides mapping information which maps the UserBean.javaclass 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>

Page 11: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 11 of 32

<property name="ContactNo" type="string"> <column name="CONTACT_NO"/> </property>

</class></hibernate-mapping>

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

10. Create a deployment plan for WASCE by editing the geronimo-web.xml file as shown inListing 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. SeeFigure 3.

Page 12: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 12 of 32

Service Deployed in the Server

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

WSDL Location

Developing J2ME Client for the Information Retrieval serviceTo develop a J2ME client (not supporting JSR-172 standard) for consuming the web service wewould require the following software components.

• Sun Java Wireless Toolkit3.0 - Download J2ME Emulator• KSoap2-j2me library - Download ksoap2-j2me-core-2.1.2-jar

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

Page 13: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 13 of 32

3. Create a Midlet name J2meNonJSR172Client.java under the packagecom.ibm.j2me.client. See Listing 8.

Listing 8. J2meNonJSR172Client.javapackage 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 }

Page 14: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 14 of 32

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

}}

4. Now Build the Project and Run.5. Now enter the Employee ID and click Send button to get the desired information. You will see

the output as shown in Figure 6.

Page 15: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 15 of 32

J2ME Emulator Output Screen

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

Developing Android Client for the Information Retrieval service

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

• Eclipse IDE• Android SDK• ADT Plug-in for Eclipse• KSoap2-android library – Download ksoap2-android-assembly-2.4-jar.

1. Create an Android Project named Android Client as shown in Figure 7.

Page 16: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 16 of 32

Create New Android Project in Eclipse

2. Add the ksoap2-android-assembly-2.4-jar to the build path of the project as shown in Figure8.

ksoap2-android-assembly-2.4-jar directory

3. Now create a class name AndroidWSClient under the package com.ibm.android.client.See Listing 9.

Page 17: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 17 of 32

Listing 9. AndroidWSClient.javapackage 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);

Page 18: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 18 of 32

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

lblResult.setText(resultsRequestSOAP.toString());

} catch (Exception e) { System.out.println();

} } });

}}

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

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

Page 19: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 19 of 32

6. Now Run as Android Application. See Figure 9.

Run Android Project

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

Android Console Output

7. Now Enter the Employee ID of the Employee whose information and Detail you want toretrieve as shown in Figure 11.

Android Invoke Preview

Page 20: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 20 of 32

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

Android Service Response Preview

Example II - Developing Hello User Restful Web Service and Deploying inGoogle App EngineQuick prototyping and publishing is very useful in developing Restful services. It's essential thatconsumers can access and experiment with a service while it's being developed. The GoogleApp Engine (GAE) platform is free at the entry level, and provides sufficient capabilities to deployRestful applications with a public URI.

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

Environment Setup

• Obtain a free GAE account by visiting: https://appengine.google.com. See Figure 13.

Google APP Engine Preview

Page 21: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 21 of 32

• From the "My Applications" view on the App-engine page, create a new Application ID. SeeFigure Figure 14.

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.

Page 22: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 22 of 32

Google APP Engine New Project

2. Place the JAXB and JAX-RS jars in the Eclipse project under |war|WEB-INF|lib. See Figure16.

Page 23: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 23 of 32

GAE Project jars

3. Also, add the jars to the Java Build Path of the project. See Figure 17.

Add to Build Path

Page 24: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 24 of 32

4. Now create a Restful Class named TestRestService.java under package com.ibm.rest asshown 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!"; }

}

5. 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/javaeehttp://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>

6. Deploy app engine from Eclipse, by clicking on the "Deploy to App Engine Project" icon inthe toolbar (installed by the GAE plug-in). See Figure 18.

Page 25: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 25 of 32

Deploy Application to Cloud

7. Deploy to Google Cloud (GAE) by signing with the email and password that you createdduring GAE sign-up. See Figure 19.

Login to GAE

8. Click on the App Engine Project settings link to give your Application ID that you havecreated before. See Figure 20.

Page 26: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 26 of 32

Set the Application ID and Version number

9. After success full Deployment you will see in the console as shown in Figure 21.

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 thefollowing link with your name (like here I am using Kuntal). See Figure 22.

Page 27: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 27 of 32

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service1. Create an Android Project named AndroidRSClient2. Now create a class name AndroidRestClient under the package

com.ibm.android.rest.client. See Listing 14.

Listing 14. AndroidRestClient.javapackage com.ibm.android.rest.client;// java net importimport 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 importsimport 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() {

Page 28: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 28 of 32

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

}}

3. Now edit main.xml file under res|layout folder. See Listing 15.

Page 29: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 29 of 32

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>

4. Add the following uses permission in the AndroidManifest.xml file to access the internet.

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

5. Now Run As Android Application and Enter your Name (like here 'Partha')and Click send toreceive a welcome greetings from the restful as shown below in Figure 23.

Invoke Service through Android

Page 30: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 30 of 32

Conclusion

Conclusion

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

Page 31: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

ibm.com/developerWorks/ developerWorks®

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 31 of 32

Downloadable resources

Description Name SizeSample code for this tutorial code.zip 175KB

Page 32: cloud to be invoked by Android and J2ME Client hibernate ... · followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed

developerWorks® ibm.com/developerWorks/

Developing database driven web service using hibernate andimplementing Restful web service in cloud to be invoked byAndroid and J2ME Client

Page 32 of 32

Related topics

• "Developing a web service and consuming it with J2ME Client", (developerWorks, Mar 2011)to develop web service with Java 2 Platform and deploying it in WebSphere Application ServerCommunity Edition (WASCE) and Tomcat server using two simple examples (Hello World andLogging) and invoking them through a J2ME client.

• "Service-Oriented Architecture and Web Services: Concepts, Technologies, and Tools", at theSun Developer Network describes some tools and technologies for web services and SOA.

• "Developing web services", (developerWorks, June 2011) - developing the code and contractfirst approach web service with Axis2.

© Copyright IBM Corporation 2011(www.ibm.com/legal/copytrade.shtml)Trademarks(www.ibm.com/developerworks/ibm/trademarks/)