developing database driven web service using hibernate and implementing restful web service in cloud...

45
Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client Skill Level: Intermediate Partha Goswami ([email protected]) Jr. Developer Protech Infosystems Pvt. Ltd Kuntal Ganguly ([email protected]) Jr. Consultant Protech Infosystems Pvt. Ltd 31 Aug 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. Section 1. 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 Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client Trademarks © Copyright IBM Corporation 2011. All rights reserved. Page 1 of 45

Upload: loky-zeto

Post on 22-Jun-2015

103 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Developing database driven web service usinghibernate and implementing Restful web service incloud to be invoked by Android and J2ME ClientSkill Level Intermediate

Partha Goswami (parthaextgmailcom)Jr DeveloperProtech Infosystems Pvt Ltd

Kuntal Ganguly (kuntalganguly86gmailcom)Jr ConsultantProtech Infosystems Pvt Ltd

31 Aug 2011

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

Section 1 Before you start

This tutorial is for developers who build applications that use database driven webservices with persistence framework like Hibernate By using web services yourapplication can publish its function or message to the rest of the world Web servicesuse XML to code and to decode data and SOAP to transport it (using openprotocols) Representational State Transfer (REST) has gained widespreadacceptance 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 servicesare viewed as resources and can be identified by their URLs

About this tutorial

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 1 of 45

This Tutorial will describes the way of developing web service (JAX-WS and REST)Web services can be implemented using different application protocols like SOAPXML JSON Restful HTTP and support various transport protocols like HTTP orJMS (Java Message Service) This tutorial will help you in developing a DatabaseDriven Information Retrieval Web service with Hibernate followed by Hello UserRestful web service which is deployed in the Google Cloud (GAE) Finallyconsuming the developed web services with mobile clients (J2ME and Android)

Objectives

In this tutorial learn how to

bull Develop and deploy a JAX-WS Web Service which operates on DB2database using Hibernate as an ORM framework

bull Develop a simple Restful webservice and deploy it in Cloud (GAE)

bull Invoke both the above Web Services using an Android Client and a J2MEclient

Prerequisites

This tutorial assumes familiarity with some basic concepts of the Eclipse IDE andbasic understanding of Web Service architecture see Resources for additionalinformation

Section 2 Introduction

What is web service

A web service is a network accessible interface to application functionality builtusing standard Internet technologies It is software application that can be accessedremotely using different XML-based languages Normally a web service is identifiedby a URLjust like any other Web site What makes web services different fromordinary Web sites is the type of interaction that they can provide

Benefits of web service

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 2 of 45

A web service is a very well known open technology standard provides a number ofbenefits including

bull Increase competition among vendors resulting in lower product costs

bull Ease transition from one product to another resulting in lower trainingcosts

bull Increase the ability for parties to interoperate resulting in lowermaintenance costs

bull Ensure a greater degree of adoption and longevity for a standard A largedegree of usage from the vendors and the users leads to a higher degreeof acceptance

How are web services used

There are three main ways in which an organization can move deploy web servicesThese are as follows

1 Creating a new web service from scratch (Contract First) The developercreates the functionalities of the services as well as preparing a documentto describe those services

2 Exposing an existing functionality through a web service (Code First)Here the functionalities of the service already exist Only the servicedescription needs to be implemented

3 Integrating web services from other vendors or business partners (Meet inthe Middle) There are instances where using a service implemented byanother is more feasible than building from scratch On these occasionsthe organization will be required to integrate others or even businesspartners Web Services

The real utility of the web service concept is present in the second and the thirdmethods which leads to other web services and applications that can be used inexisting applications

Web service and SOA

SOA and web services are two different things but web services are the preferredstandards-based way to realize SOA Service-oriented architecture (SOA) is anarchitectural style for building software applications that use services available in anetwork such as the web It promotes loose coupling between software components

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 3 of 45

so that they can be reused Applications in SOA are built based on services Aservice is an implementation of well-defined business functionality and suchservices can then be consumed by clients in different applications or businessprocesses

As SOA promotes loose coupling it obviously allows reuse of existing assets wherenew services can be created from an existing IT infrastructure of systems In otherwords it enables businesses to leverage existing investments by allowing them toreuse existing applications and promises interoperability between heterogeneousapplications and technologies SOA provides a level of flexibility that wasnt possiblebefore in the sense that

bull Services are software components with well-defined interfaces that areimplementation-independent An important aspect of SOA is theseparation of the service interface (the what) from its implementation (thehow) Such services are consumed by clients that are not concerned withhow these services will execute their requests

bull Services are self-contained (perform predetermined tasks) and looselycoupled (for independence)

bull Services can be dynamically discovered

bull Composite services can be built from aggregates of other services

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

SOA-based applications are distributed multi-tier applications that have presentationbusiness logic and persistence layers Services are the building blocks of SOAapplications While any functionality can be made into a service the challenge is todefine a service interface that is at the right level of abstraction Services shouldprovide coarse-grained functionality

Realizing SOA with web services

Web services are software systems designed to support interoperablemachine-to-machine interaction over a network This interoperability is gainedthrough 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 throughthe use of web services as one of the key benefits of web services isinteroperability which allows different distributed web services to run on a variety of

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 4 of 45

software platforms and hardware architectures The advent of web services andSOA offers potential for lower integration costs and greater flexibility An importantaspect of SOA is the separation of the service interface (the what) from itsimplementation (the how) Such services are consumed by clients that are notconcerned with how these services will execute their requests Web services are thenext step in the Webs evolution since they promise the infrastructure and tools forautomation 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 servicescould ever be trendy (lets face it you use soap to wash and you rest when you aretired) The main advantages of REST web services are

bull Lightweight - not a lot of extra xml markup

bull Human Readable Results

bull Easy to build - no toolkits required

SOAP also has some advantages

bull Easy to consume - sometimes

bull Rigid - type checking adheres to a contract

bull Development tools

For consuming web services it is sometimes a tossup between which is easier Forinstance Googles Ad Words web service is really hard to consume as it uses SOAPheaders and a number of other things that make it kind of difficult On the converseAmazons REST web service can sometimes be tricky to parse because it can behighly nested and the result schema can vary quite a bit based on what you searchfor

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA and you canleverage SOA without leveraging cloud computing the real value of cloud computingis the ability to use services data and processes that can exist outside of thefirewall in somebody elses datacenter Indeed one can consider cloud computingthe extension of SOA out to cloud-delivered resources such asstorage-as-a-service data-as-a-service platform-as-a-service The trick is todetermine which services information and processes are good candidates to residein the clouds as well as which cloud services should be abstracted within the existing

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 5 of 45

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 2: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

This Tutorial will describes the way of developing web service (JAX-WS and REST)Web services can be implemented using different application protocols like SOAPXML JSON Restful HTTP and support various transport protocols like HTTP orJMS (Java Message Service) This tutorial will help you in developing a DatabaseDriven Information Retrieval Web service with Hibernate followed by Hello UserRestful web service which is deployed in the Google Cloud (GAE) Finallyconsuming the developed web services with mobile clients (J2ME and Android)

Objectives

In this tutorial learn how to

bull Develop and deploy a JAX-WS Web Service which operates on DB2database using Hibernate as an ORM framework

bull Develop a simple Restful webservice and deploy it in Cloud (GAE)

bull Invoke both the above Web Services using an Android Client and a J2MEclient

Prerequisites

This tutorial assumes familiarity with some basic concepts of the Eclipse IDE andbasic understanding of Web Service architecture see Resources for additionalinformation

Section 2 Introduction

What is web service

A web service is a network accessible interface to application functionality builtusing standard Internet technologies It is software application that can be accessedremotely using different XML-based languages Normally a web service is identifiedby a URLjust like any other Web site What makes web services different fromordinary Web sites is the type of interaction that they can provide

Benefits of web service

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 2 of 45

A web service is a very well known open technology standard provides a number ofbenefits including

bull Increase competition among vendors resulting in lower product costs

bull Ease transition from one product to another resulting in lower trainingcosts

bull Increase the ability for parties to interoperate resulting in lowermaintenance costs

bull Ensure a greater degree of adoption and longevity for a standard A largedegree of usage from the vendors and the users leads to a higher degreeof acceptance

How are web services used

There are three main ways in which an organization can move deploy web servicesThese are as follows

1 Creating a new web service from scratch (Contract First) The developercreates the functionalities of the services as well as preparing a documentto describe those services

2 Exposing an existing functionality through a web service (Code First)Here the functionalities of the service already exist Only the servicedescription needs to be implemented

3 Integrating web services from other vendors or business partners (Meet inthe Middle) There are instances where using a service implemented byanother is more feasible than building from scratch On these occasionsthe organization will be required to integrate others or even businesspartners Web Services

The real utility of the web service concept is present in the second and the thirdmethods which leads to other web services and applications that can be used inexisting applications

Web service and SOA

SOA and web services are two different things but web services are the preferredstandards-based way to realize SOA Service-oriented architecture (SOA) is anarchitectural style for building software applications that use services available in anetwork such as the web It promotes loose coupling between software components

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 3 of 45

so that they can be reused Applications in SOA are built based on services Aservice is an implementation of well-defined business functionality and suchservices can then be consumed by clients in different applications or businessprocesses

As SOA promotes loose coupling it obviously allows reuse of existing assets wherenew services can be created from an existing IT infrastructure of systems In otherwords it enables businesses to leverage existing investments by allowing them toreuse existing applications and promises interoperability between heterogeneousapplications and technologies SOA provides a level of flexibility that wasnt possiblebefore in the sense that

bull Services are software components with well-defined interfaces that areimplementation-independent An important aspect of SOA is theseparation of the service interface (the what) from its implementation (thehow) Such services are consumed by clients that are not concerned withhow these services will execute their requests

bull Services are self-contained (perform predetermined tasks) and looselycoupled (for independence)

bull Services can be dynamically discovered

bull Composite services can be built from aggregates of other services

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

SOA-based applications are distributed multi-tier applications that have presentationbusiness logic and persistence layers Services are the building blocks of SOAapplications While any functionality can be made into a service the challenge is todefine a service interface that is at the right level of abstraction Services shouldprovide coarse-grained functionality

Realizing SOA with web services

Web services are software systems designed to support interoperablemachine-to-machine interaction over a network This interoperability is gainedthrough 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 throughthe use of web services as one of the key benefits of web services isinteroperability which allows different distributed web services to run on a variety of

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 4 of 45

software platforms and hardware architectures The advent of web services andSOA offers potential for lower integration costs and greater flexibility An importantaspect of SOA is the separation of the service interface (the what) from itsimplementation (the how) Such services are consumed by clients that are notconcerned with how these services will execute their requests Web services are thenext step in the Webs evolution since they promise the infrastructure and tools forautomation 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 servicescould ever be trendy (lets face it you use soap to wash and you rest when you aretired) The main advantages of REST web services are

bull Lightweight - not a lot of extra xml markup

bull Human Readable Results

bull Easy to build - no toolkits required

SOAP also has some advantages

bull Easy to consume - sometimes

bull Rigid - type checking adheres to a contract

bull Development tools

For consuming web services it is sometimes a tossup between which is easier Forinstance Googles Ad Words web service is really hard to consume as it uses SOAPheaders and a number of other things that make it kind of difficult On the converseAmazons REST web service can sometimes be tricky to parse because it can behighly nested and the result schema can vary quite a bit based on what you searchfor

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA and you canleverage SOA without leveraging cloud computing the real value of cloud computingis the ability to use services data and processes that can exist outside of thefirewall in somebody elses datacenter Indeed one can consider cloud computingthe extension of SOA out to cloud-delivered resources such asstorage-as-a-service data-as-a-service platform-as-a-service The trick is todetermine which services information and processes are good candidates to residein the clouds as well as which cloud services should be abstracted within the existing

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 5 of 45

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 3: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

A web service is a very well known open technology standard provides a number ofbenefits including

bull Increase competition among vendors resulting in lower product costs

bull Ease transition from one product to another resulting in lower trainingcosts

bull Increase the ability for parties to interoperate resulting in lowermaintenance costs

bull Ensure a greater degree of adoption and longevity for a standard A largedegree of usage from the vendors and the users leads to a higher degreeof acceptance

How are web services used

There are three main ways in which an organization can move deploy web servicesThese are as follows

1 Creating a new web service from scratch (Contract First) The developercreates the functionalities of the services as well as preparing a documentto describe those services

2 Exposing an existing functionality through a web service (Code First)Here the functionalities of the service already exist Only the servicedescription needs to be implemented

3 Integrating web services from other vendors or business partners (Meet inthe Middle) There are instances where using a service implemented byanother is more feasible than building from scratch On these occasionsthe organization will be required to integrate others or even businesspartners Web Services

The real utility of the web service concept is present in the second and the thirdmethods which leads to other web services and applications that can be used inexisting applications

Web service and SOA

SOA and web services are two different things but web services are the preferredstandards-based way to realize SOA Service-oriented architecture (SOA) is anarchitectural style for building software applications that use services available in anetwork such as the web It promotes loose coupling between software components

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 3 of 45

so that they can be reused Applications in SOA are built based on services Aservice is an implementation of well-defined business functionality and suchservices can then be consumed by clients in different applications or businessprocesses

As SOA promotes loose coupling it obviously allows reuse of existing assets wherenew services can be created from an existing IT infrastructure of systems In otherwords it enables businesses to leverage existing investments by allowing them toreuse existing applications and promises interoperability between heterogeneousapplications and technologies SOA provides a level of flexibility that wasnt possiblebefore in the sense that

bull Services are software components with well-defined interfaces that areimplementation-independent An important aspect of SOA is theseparation of the service interface (the what) from its implementation (thehow) Such services are consumed by clients that are not concerned withhow these services will execute their requests

bull Services are self-contained (perform predetermined tasks) and looselycoupled (for independence)

bull Services can be dynamically discovered

bull Composite services can be built from aggregates of other services

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

SOA-based applications are distributed multi-tier applications that have presentationbusiness logic and persistence layers Services are the building blocks of SOAapplications While any functionality can be made into a service the challenge is todefine a service interface that is at the right level of abstraction Services shouldprovide coarse-grained functionality

Realizing SOA with web services

Web services are software systems designed to support interoperablemachine-to-machine interaction over a network This interoperability is gainedthrough 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 throughthe use of web services as one of the key benefits of web services isinteroperability which allows different distributed web services to run on a variety of

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 4 of 45

software platforms and hardware architectures The advent of web services andSOA offers potential for lower integration costs and greater flexibility An importantaspect of SOA is the separation of the service interface (the what) from itsimplementation (the how) Such services are consumed by clients that are notconcerned with how these services will execute their requests Web services are thenext step in the Webs evolution since they promise the infrastructure and tools forautomation 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 servicescould ever be trendy (lets face it you use soap to wash and you rest when you aretired) The main advantages of REST web services are

bull Lightweight - not a lot of extra xml markup

bull Human Readable Results

bull Easy to build - no toolkits required

SOAP also has some advantages

bull Easy to consume - sometimes

bull Rigid - type checking adheres to a contract

bull Development tools

For consuming web services it is sometimes a tossup between which is easier Forinstance Googles Ad Words web service is really hard to consume as it uses SOAPheaders and a number of other things that make it kind of difficult On the converseAmazons REST web service can sometimes be tricky to parse because it can behighly nested and the result schema can vary quite a bit based on what you searchfor

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA and you canleverage SOA without leveraging cloud computing the real value of cloud computingis the ability to use services data and processes that can exist outside of thefirewall in somebody elses datacenter Indeed one can consider cloud computingthe extension of SOA out to cloud-delivered resources such asstorage-as-a-service data-as-a-service platform-as-a-service The trick is todetermine which services information and processes are good candidates to residein the clouds as well as which cloud services should be abstracted within the existing

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 5 of 45

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 4: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

so that they can be reused Applications in SOA are built based on services Aservice is an implementation of well-defined business functionality and suchservices can then be consumed by clients in different applications or businessprocesses

As SOA promotes loose coupling it obviously allows reuse of existing assets wherenew services can be created from an existing IT infrastructure of systems In otherwords it enables businesses to leverage existing investments by allowing them toreuse existing applications and promises interoperability between heterogeneousapplications and technologies SOA provides a level of flexibility that wasnt possiblebefore in the sense that

bull Services are software components with well-defined interfaces that areimplementation-independent An important aspect of SOA is theseparation of the service interface (the what) from its implementation (thehow) Such services are consumed by clients that are not concerned withhow these services will execute their requests

bull Services are self-contained (perform predetermined tasks) and looselycoupled (for independence)

bull Services can be dynamically discovered

bull Composite services can be built from aggregates of other services

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

SOA-based applications are distributed multi-tier applications that have presentationbusiness logic and persistence layers Services are the building blocks of SOAapplications While any functionality can be made into a service the challenge is todefine a service interface that is at the right level of abstraction Services shouldprovide coarse-grained functionality

Realizing SOA with web services

Web services are software systems designed to support interoperablemachine-to-machine interaction over a network This interoperability is gainedthrough 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 throughthe use of web services as one of the key benefits of web services isinteroperability which allows different distributed web services to run on a variety of

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 4 of 45

software platforms and hardware architectures The advent of web services andSOA offers potential for lower integration costs and greater flexibility An importantaspect of SOA is the separation of the service interface (the what) from itsimplementation (the how) Such services are consumed by clients that are notconcerned with how these services will execute their requests Web services are thenext step in the Webs evolution since they promise the infrastructure and tools forautomation 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 servicescould ever be trendy (lets face it you use soap to wash and you rest when you aretired) The main advantages of REST web services are

bull Lightweight - not a lot of extra xml markup

bull Human Readable Results

bull Easy to build - no toolkits required

SOAP also has some advantages

bull Easy to consume - sometimes

bull Rigid - type checking adheres to a contract

bull Development tools

For consuming web services it is sometimes a tossup between which is easier Forinstance Googles Ad Words web service is really hard to consume as it uses SOAPheaders and a number of other things that make it kind of difficult On the converseAmazons REST web service can sometimes be tricky to parse because it can behighly nested and the result schema can vary quite a bit based on what you searchfor

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA and you canleverage SOA without leveraging cloud computing the real value of cloud computingis the ability to use services data and processes that can exist outside of thefirewall in somebody elses datacenter Indeed one can consider cloud computingthe extension of SOA out to cloud-delivered resources such asstorage-as-a-service data-as-a-service platform-as-a-service The trick is todetermine which services information and processes are good candidates to residein the clouds as well as which cloud services should be abstracted within the existing

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 5 of 45

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 5: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

software platforms and hardware architectures The advent of web services andSOA offers potential for lower integration costs and greater flexibility An importantaspect of SOA is the separation of the service interface (the what) from itsimplementation (the how) Such services are consumed by clients that are notconcerned with how these services will execute their requests Web services are thenext step in the Webs evolution since they promise the infrastructure and tools forautomation 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 servicescould ever be trendy (lets face it you use soap to wash and you rest when you aretired) The main advantages of REST web services are

bull Lightweight - not a lot of extra xml markup

bull Human Readable Results

bull Easy to build - no toolkits required

SOAP also has some advantages

bull Easy to consume - sometimes

bull Rigid - type checking adheres to a contract

bull Development tools

For consuming web services it is sometimes a tossup between which is easier Forinstance Googles Ad Words web service is really hard to consume as it uses SOAPheaders and a number of other things that make it kind of difficult On the converseAmazons REST web service can sometimes be tricky to parse because it can behighly nested and the result schema can vary quite a bit based on what you searchfor

Cloud Computing and SOA Convergence

While you can certainly leverage a cloud without practicing SOA and you canleverage SOA without leveraging cloud computing the real value of cloud computingis the ability to use services data and processes that can exist outside of thefirewall in somebody elses datacenter Indeed one can consider cloud computingthe extension of SOA out to cloud-delivered resources such asstorage-as-a-service data-as-a-service platform-as-a-service The trick is todetermine which services information and processes are good candidates to residein the clouds as well as which cloud services should be abstracted within the existing

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 5 of 45

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 6: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

or emerging SOA SOA not only is a mechanism to drive more reuse and agility butalso offers the ability to figure out what should stay local and what should find aplace in the clouds Good SOA leads to a good cloud computing strategy whichleads to reduced costs enhanced agility and more excitement around enterprisecomputing 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 aretoo course-grained too fine-grained or just not at all well designed In reality unlessservices are not well defined and well designed they will not sell well when deliveredon demand The major cloud computing providers who provide services through thecloud spends a lot of time on the design of the services including usability anddurability

Service Expandability - Cloud computing services are designed to expand asneeded and those who leverage cloud services do so because they can get theservices on demand when they need them

What Is Google App Engine

Google App Engine lets you run your web applications on Googles infrastructure Itprovide both development community and the enterprise-computing space AppEngine applications are easy to build easy to maintain

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

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

App Engine costs nothing to get started All applications can use up to 500 MB ofstorage and enough CPU and bandwidth to support an efficient app serving around5 million page views a month absolutely free When you enable billing for yourapplication your free limits are raised and you only pay for resources you useabove the free levels

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 6 of 45

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 7: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Section 3 Configuration and development

Example I ndash Information retrieval web service using Hibernate

Web services is a technology that allows applications to communicate with eachother in a platform- and programming language-independent manner It is a softwareinterface that describes a collection of operations that can be accessed over thenetwork through standardized XML messaging It uses protocols based on the XMLlanguage to describe an operation to execute or data to exchange with another webservice

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

This is a simple Information Retrieval Database driven web service using Hibernatewith Code First Approach where user will input the Employee ID to retrieve theInformation (ie Name Address Date of Birth and Contact Number) about theEmployee 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 forwriting editing compiling and running computer programs And Eclipse provides anexcellent integrated development environment You can find the latest release ofeclipse in wwweclipseorg

Eclipse Web Tools Platform (WTP) The Eclipse Web Tools Platform (WTP)consists of software produced by the Eclipse Project combined with third partysoftware from other open source projects These plug-in sets up the environment foreasy J2EE based application development You can download a zipped version ofthe plug-in from httpwwweclipseorgwebtools and then extract the plug-in in theeclipse directory (where you have downloaded and extracted the Eclipse IDE) andrestart the IDE

Websphere Application Server Community Edition 211 (WASCE) IBMregWebSpherereg Application Server Community Edition (Community Edition) is amember of the IBM WebSphere Application Server family Community Edition is alightweight Java Platform Enterprise Edition (Java EE) application server built onApache Geronimo the open source application server project of the ApacheSoftware Foundation The community using Community Edition consists of all sortsof people and companies who design develop deploy or utilize Java EE solutionsWe can get the latest version of Community Edition by going to

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 7 of 45

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 8: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

httpwwwibmcomdeveloperworksdownloadswswasce

WASCE and eclipse plug-in (WEP) In order to work with Community Edition withinEclipse the WebSphere Application Server Community Edition Eclipse Plug-in(WEP) must be installed WEP is the adapter that facilitates Web applicationdevelopment in Eclipse with Community Edition You can download a zipped versionof the plug-in fromhttpdownloadboulderibmcomibmdlpubsoftwarewebspherewasceupdatesandthen extract the plug-in in the eclipse directory (where you have downloaded andextracted the Eclipse IDE) and restart the IDE

Hibernate Hibernate is an open source object (relational) mapping library for theJava language that provides persistent classes and logic without caring how tohandle the data Hibernate solves Object-Relational impedance mismatch problemsby replacing direct persistence-related database accesses with high-level objecthandling functions You can download it from httpwwwhibernateorgdownloads

DB2 Express C DB2 Express-C data server software (DB2 Express-C) is amember of the IBM DB2 family of powerful data server software for managing bothrelational and XML data DB2 Express-C is a free no-limits and easy to use editionof DB2 The C in DB2 Express-C stands for the Community You can download itfrom wwwibmcomdb2expressdownloadhtml

Set up the environment

1 Install JDK 15 or above in your system

2 Start Eclipse after deploying the necessary WTP and WEP plugins

3 Install WASCE 211

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 listingCREATE TABLE ADMINISTRATORUSER_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

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 8 of 45

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 9: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Developing information retrieval web service and deploying in WASCE

1 Create a new Dynamic Web Project named UserInfo (select WASCE211 as target runtime environment)

2 Add the following jars in the WEB-INF |lib directoryantlr-274jarcglib-full-202jarcommons-collections-211jardom4j-152jarehcache-11jarhibernate3jarjtajarlog4j-129jar

For connecting to DB2 database server add the following jars located atIBMSQLLIBjava directorydb2javazipdb2jcc4jarsqlj4zip

Also add commons-logging-104jar to WebContent|WEB-INF directory and addit the project build path

Note Figure 2 shows the project structure

UserInfo Project Directory structure

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 9 of 45

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 10: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

3 Create a java bean class UserBeanjava under package comibmmodelwhich will be our persistent class See the Listing 1

Listing 1 UserBeanjava

package comibmmodelimport javautilDate

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 10 of 45

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 11: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

public class UserBean

String IDString AddressDate DOBString ContactNo

public String getID() return ID

public void setID(String iD)

ID = iD

public String getAddress() return Address

public void setAddress(String address)

Address = addresspublic Date getDOB()

return DOBpublic void setDOB(Date dOB)

DOB = dOBpublic String getContactNo()

return ContactNopublic void setContactNo(String contactNo)

ContactNo = contactNo

4 Create a interface named UserSEIjava under package comibmservicewhich will act as a service endpoint interface See the Listing 2

Listing 2 UserSEIjava

package comibmservice

import javaxjwsWebService

WebService (name=UserSEItargetNamespace=httpserviceibmcom)

public interface UserSEI

public String getInfo(String user_Id)

5 Create the service implementation class UserServiceImpljava which willcontain the main logic Annotate the class with WebService to specifythe following parameters

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 11 of 45

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 12: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

serviceName Name of the service(a class with this name will be created duringstub generation for the client)

portName the end port (a get portName method will be created in the stubclasses)

endpointInterface the interface class which serves as a endpoint to the service (inthis case the UserSEIjava class)

targetNamespace the name space for the web service after deployment

6 Inside UserServiceImpljava class create a method called getInfo whichreturns a string containing employee information and takes String input(employee ID) as its parameter See the Listing 3

Listing 3 UserServiceImpljava

package comibmservice

import javautilIteratorimport javautilListimport javaxjwsWebService

import orghibernateQueryimport orghibernateSessionimport orghibernateSessionFactoryimport orghibernatecfgConfiguration

import comibmmodel

WebService(serviceName = HiberServiceportName = HiberPortendpointInterface = comibmserviceUserSEItargetNamespace = httpserviceibmcom)

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 =sessionFactoryopenSession()

Build the prepared query

Query query = sessioncreateQuery(from UserBean use where useID =ID )setString(IDuser_Id)

List result = querylist()Iterator it = resultiterator()while(ithasNext())

UserBean user = (UserBean)itnext()

s=USER ID +usergetID()+ ADDRESS +usergetAddress()+ DATE OF BIRTH

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 12 of 45

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 13: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

+usergetDOB()+ CONTACT NO +usergetContactNo()

sessionclose()

if(sequals())return s

else

return No Data Found

7 Right click the src folder select New gt File and create a file namedhibernatecfgxml which contains the database configuration See Listing4

Listing 4 hibernatecfgxml

ltxml version=10 encoding=UTF-8gtltDOCTYPE hibernate-configuration PUBLIC-HibernateHibernate Configuration DTDENhttphibernatesourceforgenethibernate-configuration-30dtdgt

lthibernate-configurationgtltsession-factorygt

ltproperty name=hibernateconnectiondriver_classgtcomibmdb2jccDB2Driverltpropertygtltproperty name=hibernateconnectionurlgtjdbcdb2localhost50000USERltpropertygt

ltproperty name=hibernateconnectionusernamegtADMINISTRATORltpropertygtltproperty name=hibernateconnectionpasswordgtserverltpropertygtltproperty name=hibernateconnectionpool_sizegt10ltpropertygtltproperty name=hibernatedefault_schemagtADMINISTRATORltpropertygtltproperty name=show_sqlgttrueltpropertygtltproperty name=dialectgtorghibernatedialectDB2Dialectltpropertygtltproperty name=hibernatehbm2ddlautogtreadltpropertygtlt-- Mapping files --gtltmapping resource=UserBeanhbmxmlgt

ltsession-factorygtlthibernate-configurationgt

8 Again right click src folder select New gt File and create another filenamed UserBeanhbmxml which provides mapping information whichmaps the UserBeanjava class to the UserInfo table in DB2databaseSee Listing 5

Listing 5 hibernatecfgxml

ltxml version=10 encoding=UTF-8gt

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 13 of 45

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 14: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

ltDOCTYPE hibernate-mapping PUBLIC-HibernateHibernate Mapping DTD 30ENhttphibernatesourceforgenethibernate-mapping-30dtdgt

lthibernate-mappinggt

ltclass name=comibmmodelUserBean table=USER_INFOgt

ltid name=ID column=USER_ID gtltgenerator class=assignedgtltidgt

ltproperty name=Address type=stringgtltcolumn name=ADDRESSgt

ltpropertygt

ltproperty name=DOB type=dategtltcolumn name=DATE_OF_BIRTHgt

ltpropertygt

ltproperty name=ContactNo type=stringgtltcolumn name=CONTACT_NOgt

ltpropertygt

ltclassgtlthibernate-mappinggt

9 Edit the webxml file as shown in Listing 6

Listing 6 webxml

ltxml version=10 encoding=UTF-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instance

xmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd id=WebApp_ID version=25gt

ltdisplay-namegtUserInfoltdisplay-namegtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-filegtindexjspltwelcome-filegt

ltwelcome-file-listgtltservletgt

ltservlet-namegtuserltservlet-namegtltservlet-classgtcomibmserviceUserImplltservlet-classgt

ltservletgtltservlet-mappinggt

ltservlet-namegtuserltservlet-namegtlturl-patterngtuserlturl-patterngt

ltservlet-mappinggtltweb-appgt

10 Create a deployment plan for WASCE by editing the geronimo-webxmlfile as shown in Listing 7

Listing 7 geronimo-webxml

ltxml version=10 encoding=UTF-8 standalone=nogt

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 14 of 45

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 15: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

ltwebweb-app xmlnsapp=httpgeronimoapacheorgxmlnsj2eeapplication-20xmlnsclient=httpgeronimoapacheorgxmlnsj2eeapplication-client-20xmlnsconn=httpgeronimoapacheorgxmlnsj2eeconnector-12xmlnsdep=httpgeronimoapacheorgxmlnsdeployment-12xmlnsejb=httpopenejbapacheorgxmlnsopenejb-jar-22xmlnslog=httpgeronimoapacheorgxmlnsloginconfig-20xmlnsname=httpgeronimoapacheorgxmlnsnaming-12xmlnspers=httpjavasuncomxmlnspersistencexmlnspkgen=httpopenejbapacheorgxmlnspkgen-21xmlnssec=httpgeronimoapacheorgxmlnssecurity-20xmlnsweb=httpgeronimoapacheorgxmlnsj2eeweb-201gt

ltdepenvironmentgtltdepmoduleIdgt

ltdepgroupIdgtdefaultltdepgroupIdgtltdepartifactIdgtUserInfoltdepartifactIdgtltdepversiongt10ltdepversiongtltdeptypegtcarltdeptypegt

ltdepmoduleIdgtltdepenvironmentgtltwebcontext-rootgtUserInfoltwebcontext-rootgt

ltwebweb-appgt

Select project right click Run As gt Run on Server (WASCE) Type the following URL(httplocalhost8080UserInfouser) to check your service being deployed in serversuccessfully See Figure 3

Service Deployed in the Server

Check the webservice WSDL location at httplocalhost8080UserInfouserWSDLas shown in Figure 4

WSDL Location

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 15 of 45

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 16: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Developing J2ME Client for the Information Retrieval service

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

bull Sun Java Wireless Toolkit30 - Download J2ME Emulator

bull KSoap2-j2me library - Download ksoap2-j2me-core-212-jar

1 Create a J2ME Project named User in the Emulator

2 Add the ksoap2-j2me-core-212 jar to the resource folder in the project

J2ME Project Structure

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 16 of 45

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 17: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

3 Create a Midlet name J2meNonJSR172Clientjava under the packagecomibmj2meclient See Listing 8

Listing 8 J2meNonJSR172Clientjava

package comibmj2meclient

import javaxmicroeditionmidletimport javaxmicroeditionmidletimport javaxmicroeditionlcduiimport javaioimport javaxmicroeditionioimport orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportimport orgksoap2serializationPropertyInfo

public class J2meKsoapClient extends MIDlet implements CommandListener private Form firstScreen

private Display display

private TextField id = new TextField(Enter User ID 1002 30 TextFieldANY)

StringItem resultItem=new StringItem()

Navigation commands

private static final Command EXIT_COMMAND =new Command(Exit CommandEXIT 1)private static final Command SEND =new Command(SEND CommandOK 1)

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 17 of 45

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 18: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

public J2meKsoapClient()

initFirstScreen()

private void initFirstScreen()

firstScreen = new Form(Information Retrieval )StringItem item = new StringItem( )firstScreenappend(item)firstScreenappend(id)

firstScreenaddCommand(SEND)firstScreensetCommandListener(this)

public void startApp() The initial display is the first formdisplay=DisplaygetDisplay(this)displaysetCurrent(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 MIDletnotifyDestroyed()

else if(command == SEND) soapCall()

public void soapCall()

trySoapObject rpc = new SoapObject(httpserviceibmcomgetInfo)

PropertyInfo propInfo1=new PropertyInfo()propInfo1name=arg0propInfo1type=PropertyInfoSTRING_CLASSrpcaddProperty(propInfo1idgetString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)envelopesetOutputSoapObject(rpc)

HttpTransport ht = new HttpTransport(http192168158080UserInfouser)htcall(httpserviceibmcomgetInfoenvelope)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 18 of 45

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

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

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

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

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

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

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

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

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

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

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

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

GAE output console

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

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

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 19: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

resultItemsetText(resultsRequestSOAPtoString())firstScreenappend(resultItem)

catch (Exception e)

Systemoutprintln(Exception + egetMessage())eprintStackTrace()

4 Now Build the Project and Run

5 Now enter the Employee ID and click Send button to get the desiredinformation You will see the output as shown in Figure 6

J2ME Emulator Output Screen

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 19 of 45

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

1 Create an Android Project named Android Client as shown in Figure 7

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 20: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

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 followingsoftware components

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 20 of 45

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

1 Create an Android Project named Android Client as shown in Figure 7

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 21: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

bull Eclipse IDE

bull Android SDK

bull ADT Plug-in for Eclipse

bull KSoap2-android library ndash Download ksoap2-android-assembly-24-jar

1 Create an Android Project named Android Client as shown in Figure 7

Create New Android Project in Eclipse

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 21 of 45

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 22: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

2 Add the ksoap2-android-assembly-24-jar to the build path of theproject as shown in Figure 8

ksoap2-android-assembly-24-jar directory

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 22 of 45

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 23: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

3 Now create a class name AndroidWSClient under the packagecomibmandroidclient See Listing 9

Listing 9 AndroidWSClientjava

package comibmandroidclient

ksoap-android library imports

import orgksoap2SoapEnvelopeimport orgksoap2serializationSoapObjectimport orgksoap2serializationSoapPrimitiveimport orgksoap2serializationSoapSerializationEnvelopeimport orgksoap2transportHttpTransportSEimport orgksoap2serializationPropertyInfo

Android imports

import androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 23 of 45

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 24: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

public class AndroidWSClient extends Activity

Declaring web service WSDLNamespaceMethod

private static final String NAMESPACE = httpserviceibmcomprivate static String URL = http192168158080UserInfouserprivate static final String METHOD_NAME = getInfoprivate static final String SOAP_ACTION = httpserviceibmcomgetInfo

private TextView lblResultprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)lblResult = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

SoapObject request = new SoapObject(NAMESPACE METHOD_NAME)

PropertyInfo propInfo=new PropertyInfo()propInfoname=arg0propInfotype=PropertyInfoSTRING_CLASSrequestaddProperty(propInfo textgetText()toString())

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelopeVER11)

envelopesetOutputSoapObject(request)HttpTransportSE androidHttpTransport = new HttpTransportSE(URL)

try androidHttpTransportcall(SOAP_ACTION envelope)

SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelopegetResponse()

lblResultsetText(resultsRequestSOAPtoString())

catch (Exception e) Systemoutprintln()

)

4 Now edit mainxml file under res|layout folder as shown in Listing 10

Listing 10 mainxml

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 24 of 45

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 25: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parentandroidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Enter Employee IDandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgt

ltButton androidtext=SEND androidid=+idbuttons androidlayout_width=wrap_contentandroidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

5 Add the following uses permission in the AndroidManifestxml file SeeListing 11

Listing 11 AndroidManifestxml

ltxml version=10 encoding=utf-8gtltmanifest xmlnsandroid=httpschemasandroidcomapkresandroid

package=comibmandroidclientandroidversionCode=1androidversionName=10gt

ltapplication androidicon=drawableicon androidlabel=stringapp_namegtltactivity androidname=AndroidWSClient

androidlabel=stringapp_namegtltintent-filtergt

ltaction androidname=androidintentactionMAIN gtltcategory androidname=androidintentcategoryLAUNCHER gt

ltintent-filtergtltactivitygt

ltapplicationgtltuses-permission androidname=androidpermissionINTERNETgtltuses-permissiongt

ltuses-sdk androidminSdkVersion=8 gt

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongtltmanifestgt

6 Now Run as Android Application See Figure 9

Run Android Project

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 25 of 45

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 26: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Once the Android emulator and Activity starts you will see the following in theconsole See Figure 10

Android Console Output

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 26 of 45

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 27: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

7 Now Enter the Employee ID of the Employee whose information andDetail you want to retrieve as shown in Figure 11

Android Invoke Preview

For example 1002 used in this tutorial or the Employee ID that you have in yourDatabase and click the send button to retrieve the information as response from theweb service developed before See Figure 12

Android Service Response Preview

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 27 of 45

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 28: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Example II - Developing Hello User Restful Web Service andDeploying in Google App Engine

Quick prototyping and publishing is very useful in developing Restful services Itsessential that consumers can access and experiment with a service while its beingdeveloped The Google App Engine (GAE) platform is free at the entry level andprovides sufficient capabilities to deploy Restful applications with a public URI

This is a very simple parameterized Hello User restful web services developed usingJersey and then deploying it in the Google Cloud where user will input hisher nameto receive welcome greetings To setup and run this example one need to know fewthings given below

Environment Setup

bull Obtain a free GAE account by visiting httpsappenginegooglecom SeeFigure 13

Google APP Engine Preview

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 28 of 45

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 29: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

bull From the My Applications view on the App-engine page create a newApplication ID See Figure Figure 14

Google APP Engine My Applications Preview

bull Install the Eclipse plug-in for Google APP

bull Download JAXB 21 (note that JAXB 22 is not supported by GAEcurrently) unpack the file or if your systems is unix-based runjava -jar JAXB2_20081030jar

bull 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

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 29 of 45

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 30: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

RestCloudComputing (File | New |Web Application Project) as shownbelow (uncheck the Google Web Toolkit) See Figure 15

Google APP Engine New Project

2 Place the JAXB and JAX-RS jars in the Eclipse project under|war|WEB-INF|lib See Figure 16

GAE Project jars

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 30 of 45

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 31: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

3 Also add the jars to the Java Build Path of the project See Figure 17

Add to Build Path

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 31 of 45

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 32: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

4 Now create a Restful Class named TestRestServicejava under packagecomibmrest as shown below in Listing 12

Listing 12 TestRestServicejava

package comibmrest

import javaxwsrsGETimport javaxwsrsPathimport javaxwsrsPathParamimport javaxwsrsProduces

Path(testuserUsername)public class TestRestService

GETProduces(textplain)public String getWelcome(PathParam(Username)String user)

return Welcome + user + to DeveloperWorks

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 32 of 45

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 33: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

5 Update webxml in the following way shown in the Listing 13

Listing 13 webxml

ltxml version=10 encoding=utf-8gtltweb-app xmlnsxsi=httpwwww3org2001XMLSchema-instancexmlns=httpjavasuncomxmlnsjavaeexmlnsweb=httpjavasuncomxmlnsjavaeeweb-app_2_5xsdxsischemaLocation=httpjavasuncomxmlnsjavaeehttpjavasuncomxmlnsjavaeeweb-app_2_5xsd version=25gtltservletgtltservlet-namegtjerseyltservlet-namegtltservlet-classgtcomsunjerseyspicontainerservletServletContainerltservlet-classgt

ltinit-paramgtltparam-namegtcomsunjerseyconfigpropertypackagesltparam-namegtltparam-valuegtcomibmltparam-valuegt

ltinit-paramgtltload-on-startupgt1ltload-on-startupgt

ltservletgt

ltservlet-mappinggtltservlet-namegtjerseyltservlet-namegt

lturl-patterngtrestlturl-patterngtltservlet-mappinggtltwelcome-file-listgt

ltwelcome-filegtindexhtmlltwelcome-filegtltwelcome-file-listgtltweb-appgt

6 Deploy app engine from Eclipse by clicking on the Deploy to AppEngine Project icon in the toolbar (installed by the GAE plug-in) SeeFigure 18

Deploy Application to Cloud

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 33 of 45

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 34: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

7 Deploy to Google Cloud (GAE) by signing with the email and passwordthat you created during GAE sign-up See Figure 19

Login to GAE

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 34 of 45

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 35: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

8 Click on the App Engine Project settings link to give your Application IDthat you have created before See Figure 20

Set the Application ID and Version number

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 35 of 45

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 36: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

9 After success full Deployment you will see in the console as shown inFigure 21

GAE output console

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 36 of 45

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 37: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

After this you can check your application by going to the following URL httprestingaeappspotcom

You can test or invoke the restful web service through web client ie browser justgo to the following link with your name (like here I am using Kuntal)httprestingaeappspotcomresttestuserKuntal See Figure 22

Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 37 of 45

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 38: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

1 Create an Android Project named AndroidRSClient

2 Now create a class name AndroidRestClient under the packagecomibmandroidrestclient See Listing 14

Listing 14 AndroidRestClientjava

package comibmandroidrestclient java net importimport javaioBufferedReaderimport javaioIOExceptionimport javaioInputStreamimport javaioInputStreamReaderimport javanetHttpURLConnectionimport javanetMalformedURLExceptionimport javanetURLimport javanetURLConnectionimport javanetURLEncoder

import androidappActivityimport androidosBundleimport androidwidgetTextView Android importsimport androidviewViewimport androidwidgetButtonimport androidwidgetTextViewimport androidappActivityimport androidosBundleimport androidwidgetArrayAdapterimport androidwidgetAutoCompleteTextViewimport androidwidgetEditText

public class AndroidRestClient extends Activity

Declaring web service WSDLNamespaceMethod

private TextView textViewprivate EditText text

Overridepublic void onCreate(Bundle savedInstanceState) superonCreate(savedInstanceState)setContentView(Rlayoutmain)

text = (EditText) findViewById(RideditText)textView = (TextView) findViewById(Ridresult)

final Button button = (Button) findViewById(Ridbuttons)buttonsetOnClickListener(new ViewOnClickListener()

public void onClick(View v)

try

String s=textgetText()toString()URL url = new URL(httprestingaeappspotcomresttestuser+s )URLConnection urlConnection = urlopenConnection()HttpURLConnection httpConnection = (HttpURLConnection) urlConnection

Get the HTTP response codeif(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_OK)

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 38 of 45

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 39: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

InputStream inputStream = httpConnectiongetInputStream()

if(inputStream = null)

StringBuilder stringBuilder = new StringBuilder()String line

try

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream UTF-8))

while ((line = readerreadLine()) = null)

stringBuilderappend(line)append(n)

finally

inputStreamclose()textViewsetText(stringBuildertoString())

if(httpConnectiongetResponseCode() == HttpURLConnectionHTTP_NOT_FOUND)

textViewsetText(404 (not found))

catch (MalformedURLException urlEx)

textViewsetText(urlExgetMessage())catch (IOException ioEx)

textViewsetText(ioExgetMessage())catch (Exception ex)

textViewsetText(exgetMessage())

)

3 Now edit mainxml file under res|layout folder See Listing 15

Listing 15 AndroidRestClientjava

ltxml version=10 encoding=utf-8gtltLinearLayout xmlnsandroid=httpschemasandroidcomapkresandroid

androidorientation=verticalandroidlayout_width=fill_parentandroidlayout_height=fill_parentgt

ltTextViewandroidid=+idresultandroidlayout_width=fill_parent

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 39 of 45

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 40: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

androidlayout_height=wrap_contentandroidtext=gt

ltEditText androidlayout_height=wrap_content androidtext=Parthaandroidid=+ideditText androidlayout_width=wrap_contentgtltEditTextgtltButton androidtext=SEND androidid=+idbuttonsandroidlayout_width=wrap_content androidlayout_height=wrap_contentgtltButtongt

ltLinearLayoutgt

4 Add the following uses permission in the AndroidManifestxml file toaccess the internet

ltuses-permission androidname=androidpermissionWRITE_SETTINGSgtltuses-permissiongt

5 Now Run As Android Application and Enter your Name (like herePartha)and Click send to receive a welcome greetings from the restful asshown below in Figure 23

Invoke Service through Android

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 40 of 45

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 41: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Section 4 Conclusion

Conclusion

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 41 of 45

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 42: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

In this tutorial you just learn to develope JAX-WS and JAX-RS web service in veryshort interval of time Also you get a overview of SOA and Cloud Computing whichgoes hand in hand SOA and Cloud Computing together provides a much scalableplatform for large Enterprise applications reducing cost and increasing ROI

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 42 of 45

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 43: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Downloads

Description Name Size Downloadmethod

Sample code for this tutorial codezip 175KB HTTP

Information about download methods

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 43 of 45

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 44: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

Resources

bull Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2

bull Developing a web service and consuming it with J2ME Client(developerWorks Mar 2011) to develop web service with Java 2 Platform anddeploying it in WebSphere Application Server Community Edition (WASCE) andTomcat server using two simple examples (Hello World and Logging) andinvoking them through a J2ME client

bull SOA development with Axis2 (developerWorks Aug 2006) - The nextgeneration SOAP processing framework

bull Service-Oriented Architecture and Web Services Concepts Technologies andTools at the Sun Developer Network describes some tools and technologiesfor web services and SOA

bull Take the tutorial Deliver Web services to mobile apps (developerWorks Jan2003) to learn how to access Web services using Java 2 Platform Micro Edition(J2ME)-enabled mobile devices

bull Developing web services (developerWorks June 2011) - developing the codeand contract first approach web service with Axis2

About the authors

Partha GoswamiBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy BIRT and DB2 express C) Apart from his passion for Latest Technology he has numerous otherinterests including Cricket and Tabla

Kuntal GangulyBTech with more than 13 months experience in developing J2EE WebService (JAX-WS) J2ME and Android applicationCurrently associatedwith Protech Infosystems Kolkata as Junior ConsultantHas expertisein using a wide range of open source and commercial tools (WASCEEclipse Oracle SOA Suite11g EZlegacy Active MQ BIRTand DB2express C) and technologies(GWT and Android) Apart from his

developerWorksreg ibmcomdeveloperWorks

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 44 of 45

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors
Page 45: Developing Database Driven Web Service Using Hibernate and Implementing Restful Web Service in Cloud to Be Invoked by Android and J2ME Client

passion for Latest Technology he has numerous other interestsincluding Cricket Yoga and Body Building

ibmcomdeveloperWorks developerWorksreg

Developing database driven web service using hibernate and implementing Restful web service in cloud tobe invoked by Android and J2ME Client

Trademarks

copy Copyright IBM Corporation 2011 All rights reserved Page 45 of 45

  • Table of Contents
  • Before you start
    • About this tutorial
    • Objectives
    • Prerequisites
      • Introduction
        • What is web service
        • Benefits of web service
        • How are web services used
        • Web service and SOA
        • Realizing SOA with web services
        • REST vs SOAP
        • Cloud Computing and SOA Convergence
        • SOA Can Gain the following from Cloud Computing
        • What Is Google App Engine
          • Configuration and development
            • Example I ndash Information retrieval web service using Hibernate
            • Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
              • Conclusion
                • Conclusion
                  • Downloads
                  • Resources
                  • About the authors