Android Webserver

Published on June 2016 | Categories: Documents | Downloads: 39 | Comments: 0 | Views: 304
of 45
Download PDF   Embed   Report

Comments

Content

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 © Copyright IBM Corporation 2011. All rights reserved. Trademarks Page 1 of 45

developerWorks®

ibm.com/developerWorks

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

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

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

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

Benefits of web service

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 2 of 45

ibm.com/developerWorks

developerWorks®

A web service is a very well known open technology standard provides a number of benefits including: • Increase competition among vendors, resulting in lower product costs. • Ease transition from one product to another, resulting in lower training costs. • Increase the ability for parties to interoperate, resulting in lower maintenance costs. • Ensure a greater degree of adoption and longevity for a standard. A large degree of usage from the vendors and the users leads to a higher degree of acceptance.

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

2.

3.

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

Web service and SOA
SOA and web services are two different things, but web services are the preferred standards-based way to realize SOA. Service-oriented architecture (SOA) is an architectural style for building software applications that use services available in a network such as the web. It promotes loose coupling between software components

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 3 of 45

developerWorks®

ibm.com/developerWorks

so that they can be reused. Applications in SOA are built based on services. A service is an implementation of well-defined business functionality, and such services can then be consumed by clients in different applications or business processes. As SOA promotes loose coupling it obviously allows reuse of existing assets where new services can be created from an existing IT infrastructure of systems. In other words, it enables businesses to leverage existing investments by allowing them to reuse existing applications, and promises interoperability between heterogeneous applications and technologies. SOA provides a level of flexibility that wasn't possible before in the sense that: • Services are software components with well-defined interfaces that are implementation-independent. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests. • Services are self-contained (perform predetermined tasks) and loosely coupled (for independence). • Services can be dynamically discovered. • Composite services can be built from aggregates of other services. SOA uses the find-bind-execute paradigm as shown in Figure 1. In this paradigm, service providers register their service in a public registry. This registry is used by consumers to find services that match certain criteria. If the registry has such a service, it provides the consumer with a contract and an endpoint address for that service. SOA-based applications are distributed multi-tier applications that have presentation, business logic, and persistence layers. Services are the building blocks of SOA applications. While any functionality can be made into a service, the challenge is to define a service interface that is at the right level of abstraction. Services should provide coarse-grained functionality.

Realizing SOA with web services
Web services are software systems designed to support interoperable machine-to-machine interaction over a network. This interoperability is gained through a set of XML-based open standards, such as WSDL, SOAP, and UDDI. Interoperability is the most important principle of SOA. This can be realized through the use of web services, as one of the key benefits of web services is interoperability, which allows different distributed web services to run on a variety of

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 4 of 45

ibm.com/developerWorks

developerWorks®

software platforms and hardware architectures. The advent of web services and SOA offers potential for lower integration costs and greater flexibility. An important aspect of SOA is the separation of the service interface (the what) from its implementation (the how). Such services are consumed by clients that are not concerned with how these services will execute their requests. Web services are the next step in the Web's evolution, since they promise the infrastructure and tools for automation of business-to-business relationships over the Internet.

REST vs. SOAP
REST is definitely the trendy way to create a web service, if creating web services could ever be trendy (let's face it you use soap to wash, and you rest when you are tired). The main advantages of REST web services are: • Lightweight - not a lot of extra xml markup • Human Readable Results • Easy to build - no toolkits required SOAP also has some advantages: • Easy to consume - sometimes • Rigid - type checking, adheres to a contract • Development tools For consuming web services, it is sometimes a tossup between which is easier. For instance Google's Ad Words web service is really hard to consume, as it uses SOAP headers, and a number of other things that make it kind of difficult. On the converse, Amazon's REST web service can sometimes be tricky to parse because it can be highly nested, and the result schema can vary quite a bit based on what you search for.

Cloud Computing and SOA Convergence
While you can certainly leverage a cloud without practicing SOA, and you can leverage SOA without leveraging cloud computing, the real value of cloud computing is the ability to use services, data, and processes that can exist outside of the firewall in somebody else's datacenter. Indeed, one can consider cloud computing the extension of SOA out to cloud-delivered resources, such as storage-as-a-service, data-as-a-service, platform-as-a-service. The trick is to determine which services, information, and processes are good candidates to reside in the clouds as well as which cloud services should be abstracted within the existing

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 5 of 45

developerWorks®

ibm.com/developerWorks

or emerging SOA. SOA not only is a mechanism to drive more reuse and agility but also offers the ability to figure out what should stay local and what should find a place in the clouds. Good SOA leads to a good cloud computing strategy, which leads to reduced costs, enhanced agility, and more excitement around enterprise computing than we have seen in a while.

SOA Can Gain the following from Cloud Computing
Service Design - Many SOA projects have a tendency to build in services that are too course-grained, too fine-grained, or just not at all well designed. In reality, unless services are not well defined and well designed, they will not sell well when delivered on demand. The major cloud computing providers, who provide services through the cloud, spends a lot of time on the design of the services, including usability and durability. Service Expandability - Cloud computing services are designed to expand as needed, and those who leverage cloud services do so because they can get the services on demand, when they need them.

What Is Google App Engine?
Google App Engine lets you run your web applications on Google's infrastructure. It provide both development community and the enterprise-computing space. App Engine applications are easy to build, easy to maintain. The App Engine enables you to build enterprise-scalable applications on the same infrastructure that Google uses. App Engine is structured differently from the typical web application server. At its core, App Engine restricts your application from any access to the physical infrastructure, preventing you from opening sockets, running background processes (although you can use cron), and using other common back-end routines that application developers take for granted in other environments. App Engine costs nothing to get started. All applications can use up to 500 MB of storage and enough CPU and bandwidth to support an efficient app serving around 5 million page views a month, absolutely free. When you enable billing for your application, your free limits are raised, and you only pay for resources you use above the free levels.

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 6 of 45

ibm.com/developerWorks

developerWorks®

Section 3. Configuration and development
Example I – Information retrieval web service using Hibernate
Web services is a technology that allows applications to communicate with each other in a platform- and programming language-independent manner. It is a software interface that describes a collection of operations that can be accessed over the network through standardized XML messaging. It uses protocols based on the XML language to describe an operation to execute or data to exchange with another web service. Here we will create a web service that basically interacts with the a database (in this case DB2) using Hibernate as a ORM framework .As discussed earlier that web services are loosely coupled in nature, so we will invoke this web service using a Android client and a J2ME client (not supporting JSR-172 ). This is a simple Information Retrieval Database driven web service using Hibernate with Code First Approach, where user will input the Employee ID to retrieve the Information (i.e. Name, Address, Date of Birth and Contact Number) about the Employee. To setup and run this example one need to know few things given below: Eclipse IDE: An integrated development environment (IDE) is an all-in-one tool for writing, editing, compiling, and running computer programs. And Eclipse provides an excellent integrated development environment. You can find the latest release of eclipse in www.eclipse.org. Eclipse Web Tools Platform (WTP): The Eclipse Web Tools Platform (WTP) consists of software produced by the Eclipse Project combined with third party software from other open source projects. These plug-in sets up the environment for easy J2EE based application development. You can download a zipped version of the plug-in from: http://www.eclipse.org/webtools/ and then extract the plug-in in the eclipse directory (where you have downloaded and extracted the Eclipse IDE) and restart the IDE. Websphere Application Server Community Edition 2.1.1 (WASCE): IBM® WebSphere® Application Server Community Edition (Community Edition) is a member of the IBM WebSphere Application Server family. Community Edition is a lightweight Java Platform Enterprise Edition (Java EE) application server built on Apache Geronimo, the open source application server project of the Apache Software Foundation. The community using Community Edition consists of all sorts of people and companies, who design, develop, deploy, or utilize Java EE solutions. We can get the latest version of Community Edition by going to

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 7 of 45

developerWorks®

ibm.com/developerWorks

http://www.ibm.com/developerworks/downloads/ws/wasce/. WASCE and eclipse plug-in (WEP): In order to work with Community Edition within Eclipse, the WebSphere Application Server Community Edition Eclipse Plug-in (WEP) must be installed. WEP is the adapter that facilitates Web application development in Eclipse with Community Edition. You can download a zipped version of the plug-in from: http://download.boulder.ibm.com/ibmdl/pub/software/websphere/wasce/updates/and then extract the plug-in in the eclipse directory (where you have downloaded and extracted the Eclipse IDE) and restart the IDE. Hibernate: Hibernate is an open source object (relational) mapping library for the Java language that provides persistent classes and logic without caring how to handle the data. Hibernate solves Object-Relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions. You can download it from http://www.hibernate.org/downloads. DB2 Express C: DB2 Express-C data server software ("DB2 Express-C") is a member of the IBM DB2 family of powerful data server software for managing both relational and XML data. DB2 Express-C is a free, no-limits, and easy to use edition of DB2. The 'C' in DB2 Express-C stands for the Community. You can download it from www.ibm.com/db2/express/download.html. Set up the environment 1. 2. 3. 4. 5. 6. Install JDK 1.5 or above in your system. Start Eclipse after deploying the necessary WTP and WEP plugins. Install WASCE 2.1.1. Link the server in eclipse using WEP and start WASCE. Install DB2 Express-C. Create the following table as shown in the listing. CREATE TABLE "ADMINISTRATOR"."USER_INFO" ( "USER_ID" VARCHAR(10) NOT NULL , "ADDRESS" VARCHAR(50) NOT NULL , "DATE_OF_BIRTH" DATE NOT NULL , "CONTACT_NO" VARCHAR(12) NOT NULL ) ;

Administrator table

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 8 of 45

ibm.com/developerWorks

developerWorks®

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

For connecting to DB2 database server add the following jars located at "..\IBM\SQLLIB\java\" directory db2java.zip db2jcc4.jar sqlj4.zip Also add commons-logging-1.0.4.jar to WebContent|WEB-INF directory and add it the project build path. Note Figure 2, shows the project structure. UserInfo Project Directory structure

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 9 of 45

developerWorks®

ibm.com/developerWorks

3.

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

Listing 1. UserBean.java
package com.ibm.model; import java.util.Date;

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 10 of 45

ibm.com/developerWorks

developerWorks®

public class UserBean { String ID; String Address; Date DOB; String ContactNo; public String getID() { return ID; } public void setID(String iD) { ID = iD; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } public Date getDOB() { return DOB; } public void setDOB(Date dOB) { DOB = dOB; } public String getContactNo() { return ContactNo; } public void setContactNo(String contactNo) { ContactNo = contactNo; } }

4.

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

Listing 2. UserSEI.java
package com.ibm.service; import javax.jws.WebService; @WebService (name="UserSEI", targetNamespace="http://service.ibm.com") public interface UserSEI { public String getInfo(String user_Id); }

5.

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 11 of 45

developerWorks®

ibm.com/developerWorks

serviceName: Name of the service(a class with this name will be created during stub generation for the client). portName: the end port (a get "portName" method will be created in the stub classes.) endpointInterface: the interface class which serves as a endpoint to the service (in this case the UserSEI.java class). targetNamespace: the name space for the web service after deployment. 6. Inside UserServiceImpl.java class create a method called getInfo which returns a string containing employee information and takes String input (employee ID) as its parameter. See the Listing 3.

Listing 3. UserServiceImpl.java
package com.ibm.service; import java.util.Iterator; import java.util.List; import javax.jws.WebService; import import import import org.hibernate.Query; org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.cfg.Configuration;

import com.ibm.model.*; @WebService(serviceName = "HiberService", portName = "HiberPort", endpointInterface = "com.ibm.service.UserSEI", targetNamespace = "http://service.ibm.com") public class UserImpl implements UserSEI{ public String getInfo(String user_Id){ String s=""; Session session = null; // Create a new sessionFactory object SessionFactory sessionFactory = new Configuration(). configure().buildSessionFactory(); session =sessionFactory.openSession(); //Build the prepared query Query query = session.createQuery("from UserBean use where use.ID =:ID" ). setString("ID",user_Id); List result = query.list(); Iterator it = result.iterator(); while(it.hasNext()){ UserBean user = (UserBean)it.next(); s="USER ID :"+user.getID()+ " , ADDRESS :" +user.getAddress()+ " , DATE OF BIRTH

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 12 of 45

ibm.com/developerWorks

developerWorks®

:"+user.getDOB()+ " } session.close(); if(!s.equals("")){ return s; } else{ return "No Data Found"; } } }

, CONTACT NO :

" +user.getContactNo()

;

7.

Right click the src folder, select New > File and create a file named hibernate.cfg.xml which contains the database configuration. See Listing 4:

Listing 4. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</property> <property name="hibernate.connection.url">jdbc:db2://localhost:50000/USER</property> <property name="hibernate.connection.username">ADMINISTRATOR</property> <property name="hibernate.connection.password">server</property> <property name="hibernate.connection.pool_size">10</property> <property name="hibernate.default_schema">ADMINISTRATOR</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.DB2Dialect</property> <property name="hibernate.hbm2ddl.auto">read</property> <!-- Mapping files --> <mapping resource="UserBean.hbm.xml"/> </session-factory> </hibernate-configuration>

8.

Again right click src folder, select New > File and create another file named UserBean.hbm.xml which provides mapping information which maps the UserBean.java class to the UserInfo table in DB2 database.See Listing 5:

Listing 5. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 13 of 45

developerWorks®

ibm.com/developerWorks

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.ibm.model.UserBean" table="USER_INFO"> <id name="ID" column="USER_ID" > <generator class="assigned"/> </id> <property name="Address" type="string"> <column name="ADDRESS"/> </property> <property name="DOB" type="date"> <column name="DATE_OF_BIRTH"/> </property> <property name="ContactNo" type="string"> <column name="CONTACT_NO"/> </property> </class> </hibernate-mapping>

9.

Edit the web.xml file as shown in Listing 6.

Listing 6. web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UserInfo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>user</servlet-name> <servlet-class>com.ibm.service.UserImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>user</servlet-name> <url-pattern>/user</url-pattern> </servlet-mapping> </web-app>

10. Create a deployment plan for WASCE by editing the geronimo-web.xml file as shown in Listing 7. Listing 7. geronimo-web.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 14 of 45

ibm.com/developerWorks

developerWorks®

<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1"> <dep:environment> <dep:moduleId> <dep:groupId>default</dep:groupId> <dep:artifactId>UserInfo</dep:artifactId> <dep:version>1.0</dep:version> <dep:type>car</dep:type> </dep:moduleId> </dep:environment> <web:context-root>/UserInfo</web:context-root> </web:web-app>

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

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 15 of 45

developerWorks®

ibm.com/developerWorks

Developing J2ME Client for the Information Retrieval service To develop a J2ME client (not supporting JSR-172 standard) for consuming the web service we would require the following software components. • Sun Java Wireless Toolkit3.0 - Download J2ME Emulator • KSoap2-j2me library - Download ksoap2-j2me-core-2.1.2-jar 1. 2. Create a J2ME Project named User in the Emulator. Add the ksoap2-j2me-core-2.1.2 jar to the resource folder in the project.

J2ME Project Structure

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 16 of 45

ibm.com/developerWorks

developerWorks®

3.

Create a Midlet name J2meNonJSR172Client.java under the package com.ibm.j2me.client. See Listing 8.

Listing 8. J2meNonJSR172Client.java
package com.ibm.j2me.client; import import import import import import import import import import import javax.microedition.midlet.*; javax.microedition.midlet.*; javax.microedition.lcdui.*; java.io.*; javax.microedition.io.*; org.ksoap2.SoapEnvelope; org.ksoap2.serialization.SoapObject; org.ksoap2.serialization.SoapPrimitive; org.ksoap2.serialization.SoapSerializationEnvelope; org.ksoap2.transport.*; org.ksoap2.serialization.PropertyInfo;

public class J2meKsoapClient extends MIDlet implements CommandListener { private Form firstScreen; private Display display; private TextField id = new TextField("Enter User ID :", "1002", 30, TextField.ANY); StringItem resultItem=new StringItem("",""); // Navigation commands private static final Command EXIT_COMMAND =new Command("Exit", Command.EXIT, 1); private static final Command SEND =new Command("SEND", Command.OK, 1);

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 17 of 45

developerWorks®

ibm.com/developerWorks

public J2meKsoapClient() { initFirstScreen(); } private void initFirstScreen() { firstScreen = new Form("Information Retrieval "); StringItem item = new StringItem(""," "); firstScreen.append(item); firstScreen.append(id); firstScreen.addCommand(SEND); firstScreen.setCommandListener(this); } public void startApp() { // The initial display is the first form display=Display.getDisplay(this); display.setCurrent(firstScreen); }

public void pauseApp() { // No implementation required } public void destroyApp(boolean unconditional) { // No implementation required } public void commandAction(Command command, Displayable displayable) { if (command == EXIT_COMMAND) { // Exit the MIDlet notifyDestroyed(); } else if(command == SEND) { soapCall() ; } } public void soapCall() { try{ SoapObject rpc = new SoapObject("http://service.ibm.com","getInfo"); PropertyInfo propInfo1=new PropertyInfo(); propInfo1.name="arg0"; propInfo1.type=PropertyInfo.STRING_CLASS; rpc.addProperty(propInfo1,id.getString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(rpc); HttpTransport ht = new HttpTransport("http://192.168.1.5:8080/UserInfo/user"); ht.call("http://service.ibm.com/getInfo",envelope);

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 18 of 45

ibm.com/developerWorks

developerWorks®

SoapPrimitive

resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();

resultItem.setText(resultsRequestSOAP.toString()); firstScreen.append(resultItem); } catch (Exception e){ System.out.println("Exception : "+ e.getMessage()); e.printStackTrace(); } } }

4. 5.

Now Build the Project and Run. Now enter the Employee ID and click Send button to get the desired information. You will see the output as shown in Figure 6.

J2ME Emulator Output Screen

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 19 of 45

developerWorks®

ibm.com/developerWorks

Note: For Invoking web service through JSR-172 compliant Handset (using Stub) please refer to the following Tutorial. Developing Android Client for the Information Retrieval service To develop an Android client for the web service we would require the following software components.

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 20 of 45

ibm.com/developerWorks

developerWorks®

• Eclipse IDE • Android SDK • ADT Plug-in for Eclipse • KSoap2-android library – Download ksoap2-android-assembly-2.4-jar 1. Create an Android Project named Android Client as shown in Figure 7.

Create New Android Project in Eclipse

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 21 of 45

developerWorks®

ibm.com/developerWorks

2.

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

ksoap2-android-assembly-2.4-jar directory

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 22 of 45

ibm.com/developerWorks

developerWorks®

3.

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

Listing 9. AndroidWSClient.java
package com.ibm.android.client; // ksoap-android library imports import import import import import import org.ksoap2.SoapEnvelope; org.ksoap2.serialization.SoapObject; org.ksoap2.serialization.SoapPrimitive; org.ksoap2.serialization.SoapSerializationEnvelope; org.ksoap2.transport.HttpTransportSE; org.ksoap2.serialization.PropertyInfo;

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 23 of 45

developerWorks®

ibm.com/developerWorks

public class AndroidWSClient extends Activity { // Declaring web service WSDL,Namespace,Method private private private private static static static static final String String URL = final String final String NAMESPACE = "http://service.ibm.com"; "http://192.168.1.5:8080/UserInfo/user"; METHOD_NAME = "getInfo"; SOAP_ACTION = "http://service.ibm.com/getInfo";

private TextView lblResult; private EditText text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (EditText) findViewById(R.id.editText); lblResult = (TextView) findViewById(R.id.result); final Button button = (Button) findViewById(R.id.buttons); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo propInfo=new PropertyInfo(); propInfo.name="arg0"; propInfo.type=PropertyInfo.STRING_CLASS; request.addProperty(propInfo, text.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();

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

4.

Now edit main.xml file under res|layout folder as shown in Listing 10.

Listing 10. main.xml

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 24 of 45

ibm.com/developerWorks

developerWorks®

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <EditText android:layout_height="wrap_content" android:text="Enter Employee ID" android:id="@+id/editText" android:layout_width="wrap_content"></EditText> <Button android:text="SEND" android:id="@+id/buttons" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>

5.

Add the following uses permission in the AndroidManifest.xml file. See Listing 11.

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

6.

Now Run as Android Application. See Figure 9.

Run Android Project

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 25 of 45

developerWorks®

ibm.com/developerWorks

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 26 of 45

ibm.com/developerWorks

developerWorks®

7.

Now Enter the Employee ID of the Employee whose information and Detail 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 your Database and click the send button to retrieve the information as response from the web service developed before. See Figure 12. Android Service Response Preview

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 27 of 45

developerWorks®

ibm.com/developerWorks

Example II - Developing Hello User Restful Web Service and Deploying in Google App Engine
Quick prototyping and publishing is very useful in developing Restful services. It's essential that consumers can access and experiment with a service while it's being developed. The Google App Engine (GAE) platform is free at the entry level, and provides sufficient capabilities to deploy Restful applications with a public URI. This is a very simple parameterized Hello User restful web services developed using Jersey and then deploying it in the Google Cloud, where user will input his/her name to receive welcome greetings. To setup and run this example one need to know few things given below: Environment Setup • Obtain a free GAE account by visiting: https://appengine.google.com. See Figure 13. Google APP Engine Preview

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 28 of 45

ibm.com/developerWorks

developerWorks®

• From the "My Applications" view on the App-engine page, create a new Application ID. See Figure Figure 14. Google APP Engine My Applications Preview

• Install the Eclipse plug-in for Google APP • Download JAXB 2.1; (note that JAXB 2.2 is not supported by GAE currently) unpack the file or, if your systems is unix-based, run: java -jar JAXB2_20081030.jar • Download the JAX-RS reference implementation (jersey), and unpack Developing and Deploying a Restful App on Google Cloud (GAE) 1. In Eclipse, create a new Web Application Project named
Trademarks Page 29 of 45

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

developerWorks®

ibm.com/developerWorks

RestCloudComputing (File | New |Web Application Project) as shown below (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
Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved. Trademarks Page 30 of 45

ibm.com/developerWorks

developerWorks®

3.

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

Add to Build Path

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 31 of 45

developerWorks®

ibm.com/developerWorks

4.

Now create a Restful Class named TestRestService.java under package com.ibm.rest as shown below in Listing 12.

Listing 12. TestRestService.java
package com.ibm.rest; import import import import javax.ws.rs.GET; javax.ws.rs.Path; javax.ws.rs.PathParam; javax.ws.rs.Produces;

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 32 of 45

ibm.com/developerWorks

developerWorks®

5.

Update web.xml in the following way shown in the Listing 13.

Listing 13. web.xml
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet><servlet-name>jersey</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.ibm</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>

6.

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

Deploy Application to Cloud

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 33 of 45

developerWorks®

ibm.com/developerWorks

7.

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

Login to GAE

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 34 of 45

ibm.com/developerWorks

developerWorks®

8.

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

Set the Application ID and Version number

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 35 of 45

developerWorks®

ibm.com/developerWorks

9.

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

GAE output console

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 36 of 45

ibm.com/developerWorks

developerWorks®

After this you can check your application by going to the following URL : http://restingae.appspot.com You can test or invoke the restful web service through web client, i.e. browser, just go to the following link with your name (like here I am using Kuntal). http://restingae.appspot.com/rest/testuser/Kuntal. See Figure 22. Test Rest Service through browser URL

Developing Android Client for the Hello User Restful web service

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 37 of 45

developerWorks®

ibm.com/developerWorks

1. 2.

Create an Android Project named AndroidRSClient Now create a class name AndroidRestClient under the package com.ibm.android.rest.client. See Listing 14.

Listing 14. AndroidRestClient.java
package com.ibm.android.rest.client; // java net import import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; // Android imports import android.view.View; import android.widget.Button; import android.widget.TextView; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.EditText; public class AndroidRestClient extends Activity { // Declaring web service WSDL,Namespace,Method private TextView textView; private EditText text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (EditText) findViewById(R.id.editText); textView = (TextView) findViewById(R.id.result); final Button button = (Button) findViewById(R.id.buttons); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { String s=text.getText().toString(); URL url = new URL("http://restingae.appspot.com/rest/testuser/"+s ); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; // Get the HTTP response code if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 38 of 45

ibm.com/developerWorks

developerWorks®

{ InputStream inputStream = httpConnection.getInputStream(); if(inputStream != null) { StringBuilder stringBuilder = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8")); while ((line = reader.readLine()) != null) { stringBuilder.append(line).append("\n"); } } finally { inputStream.close(); } textView.setText(stringBuilder.toString()); } } if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) { textView.setText("404 (not found)"); } } catch (MalformedURLException urlEx) { textView.setText(urlEx.getMessage()); } catch (IOException ioEx) { textView.setText(ioEx.getMessage()); } catch (Exception ex) { textView.setText(ex.getMessage()); } } }); } }

3.

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

Listing 15. AndroidRestClient.java
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/result" android:layout_width="fill_parent"

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 39 of 45

developerWorks®

ibm.com/developerWorks

android:layout_height="wrap_content" android:text="" /> <EditText android:layout_height="wrap_content" android:text="Partha" android:id="@+id/editText" android:layout_width="wrap_content"></EditText> <Button android:text="SEND" android:id="@+id/buttons" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button> </LinearLayout>

4.

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

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

5.

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

Invoke Service through Android

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 40 of 45

ibm.com/developerWorks

developerWorks®

Section 4. Conclusion
Conclusion
Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved. Trademarks Page 41 of 45

developerWorks®

ibm.com/developerWorks

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

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 42 of 45

ibm.com/developerWorks

developerWorks®

Downloads
Description
Sample code for this tutorial Information about download methods

Name
code.zip

Size
175KB

Download method
HTTP

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 43 of 45

developerWorks®

ibm.com/developerWorks

Resources
• Eclipse WTP Tutorials - Creating Bottom Up Web Service via Apache Axis2. • "Developing a web service and consuming it with J2ME Client", (developerWorks, Mar 2011) to develop web service with Java 2 Platform and deploying it in WebSphere Application Server Community Edition (WASCE) and Tomcat server using two simple examples (Hello World and Logging) and invoking them through a J2ME client. • "SOA development with Axis2", (developerWorks, Aug 2006) - The next generation SOAP processing framework. • "Service-Oriented Architecture and Web Services: Concepts, Technologies, and Tools", at the Sun Developer Network describes some tools and technologies for web services and SOA. • Take the tutorial "Deliver Web services to mobile apps", (developerWorks, Jan 2003) to learn how to access Web services using Java 2 Platform, Micro Edition (J2ME)-enabled mobile devices. • "Developing web services", (developerWorks, June 2011) - developing the code and contract first approach web service with Axis2.

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

Kuntal Ganguly B.Tech with more than 13 months experience in developing J2EE, Web Service (JAX-WS), J2ME and Android application.Currently associated with Protech Infosystems, Kolkata as Junior Consultant.Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Oracle SOA Suite11g, EZlegacy , Active MQ , BIRTand DB2 express C) and technologies(GWT and Android). Apart from his
Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved. Trademarks Page 44 of 45

ibm.com/developerWorks

developerWorks®

passion for Latest Technology, he has numerous other interests including Cricket, Yoga and Body Building.

Developing database driven web service using hibernate and implementing Restful web service in cloud to be invoked by Android and J2ME Client © Copyright IBM Corporation 2011. All rights reserved.

Trademarks Page 45 of 45

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close