Developing a web service and consuming it with J2ME Client

This tutorial demonstrates how 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 (HelloWorld and Logging), then invoking them through a J2ME client. Eclipse IDE is also used to develop a web service and deploy it in the WASCE. There is also a Stock-Quote service example in a remote location (not in local host) developed in .NET platform and this tutorial will show how to invoke it using a J2ME client.

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

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



09 March 2011

Also available in Japanese

Before you start

Learn what to expect from this tutorial, and how to get the most out of it.

About this tutorial

This tutorial demonstrates how 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. Eclipse IDE is also used to develop a web service and deploy it in the WASCE. There is also a Stock-Quote service example in a remote location (not in local host) developed in .NET platform and this tutorial will show how to invoke it using a J2ME client.

All these web service uses SOAP as a fundamental messaging framework for web services. SOAP builds up a loosely coupled infrastructure that provides significant resilience, scalability and flexibility in deployment using different implementation technologies and network transport. J2ME Web services specification (JSR 172) identifies two independent, optional packages that you can use to access remote SOAP- or XML-based Web services and parse XML data. The complete JSR 172 specification, which is available for download at the Java Community process.

Objectives

In this tutorial, learn how to:

  • Download and Install the web servers (Tomcat and WASCE), if it is not already installed, and make minor additions to it to successfully implement the given examples.
  • Download and install Sun J2ME Emulator (Java[TM] ME Platform SDK 3.0) for developing J2me Client to invoke the web services.
  • Download and install Axis2 runtime environment into Tomcat for developing and deploying Web service (Hello World).
  • Developing web service (Logging) using Eclipse IDE and deploying it in WebSphere Community edition (WASCE).
  • Accessing Remote web service (Stock Quote) developed in .Net platform and hosted in the Remote machine through J2me client.

Prerequisites

This tutorial assumes familiarity with some basic concepts of the Eclipse IDE, including views, editors, panels, and so on, along with basic programming concept in Java and J2me. For an introduction to Eclipse, Java and J2me, see Resources.


Introduction

What is a web service?

A web service is a network accessible interface to application functionality, built using standard Internet technologies.

The fundamental concept behind web services is the SOA (service-oriented architecture), where an application is no longer a large monolithic program, but is divided into smaller, loosely coupled programs, and provided services are loosely coupled together with standardized and well-defined interfaces. These loosely coupled programs make the architecture very extensible, as it acquires the ability to add or remove services with limited costs. Therefore, new services can be created by combining and reusing existing services.

Because of the abstraction provided by the standards-based interfaces, it does not matter whether the application services are written in Java and the browser written in C++, or the application services deployed on a UNIX box while the browser is deployed on Windows. Web services allow for cross-platform interoperability in a way that makes the platform irrelevant. Interoperability is one of the key benefits gained from implementing web services.

Figure 1. The web services invocation form j2me client
The web services invocation form j2me client

In the web services architecture, the service provider publishes a description of the service(s) it offers via the service registry. The service consumer searches the service registry to find a service that meets their needs. The service consumer could be a person or a program.In the web services architecture, the service provider publishes a description of the service(s) it offers via the service registry. The service consumer searches the service registry to find a service that meets their needs. The service consumer could be a person or a program.

The service provider offers business processes in the form of services. The services offered by the provider are called by the consumer to achieve certain sets of business goals. The process of services being provided and consumed is achieved by using directory services that lie between the provider and the consumer, in the form of broker. The service to be made available to the consumer is published to the directory services in the broker. The consumer wanting to achieve the set of business goal(s) will discover the service from the broker. If the service is found, it will bind to the service and execute the processing logic.

What is J2ME?

The Java 2 Micro Edition (J2ME) is a Java platform that is designed for small devices. It contains specially designed, lightweight virtual machines; a bare minimum of core-class libraries; and lightweight substitutes for standard Java libraries. J2ME is the ideal mobile client platform for wireless PDAs and enhanced mobile phones. It supports the standard Java programming language and contains a subset of APIs from the Java 2 Platform, Standard Edition (J2SE) with the addition of device-specific APIs. The Mobile Information Device Profile (MIDP) is a flavor of J2ME that runs on mobile phones.

All major mobile device vendors, including Nokia, Motorola, Siemens, Samsung, Fujitsu, Inventec, LG Electronics, Mitsubishi, NEC, Panasonic, Psion, RIM, Sharp, and Sony, have adopted Java as part of their core strategy for future smart devices. Major wireless carriers such as SprintPCS, and AT&T have committed to support Java devices and applications on their networks. In this tutorial, you focus on MIDP application development. For more information about J2ME and MIDP, see the J2ME 101 series of tutorials published by developerWorks (see Resources).

The Sun J2ME Wireless Toolkit

The J2ME Wireless Toolkit is a comprehensive set of tools for building MIDP applications. The toolkit can be used standalone, or incorporated into many popular integrated development environments (IDEs). Version 5 of Sun One Studio, Mobile Edition comes with the J2ME Wireless Toolkit 3.0 bundled in. It provides the byte code pre-verification tool, implementation of API class libraries, and a device emulator. The emulator does not correspond to any real physical device. Instead, it supports cutting-edge MIDP optional package APIs that are not yet implemented on physical devices.

Key Features of SUN J2ME Wireless Toolkit 3.0

  • Integration with 3rd party emulators and Windows Mobile devices.
  • On-device deployment and on-device debugging.
  • CLDC/MIDP, CDC/FP/PBP/AGUI and BD-J integrated into one SDK.
  • New CLDC Hot-Spot Virtual Machine.
  • Optimized MSA 1.1 Stack with Extensions.
  • Profiling support.
  • BD-J support (for Windows Only).
  • JavaFX Mobile Emulator.

Configuration and development

Example: Web service using AXIS2 and Tomcat

This is a very simple example “Hello World” web service, which will display the string passed as a parameter, invoked from a J2ME client. To setup and run this example one need to know few things given below.

Tomcat web server 5.5 or above: The Tomcat servlet engine is an open-source package developed as part of the Apache Software Foundation's Jakarta project. It is the official reference implementation for both the servlet and JSP specifications. Tomcat can act as a stand-alone Web server and also as a servlet/JSP engine. We can download the latest release of Tomcat.

Axis2.war (web service engine): Axis2 is built upon a modular architecture that consists of core modules and non-core modules. The core engine is said to be a pure SOAP processing engine (there is not any JAX-RPC concept burnt into the core). Every message coming into the system has to be transformed into a SOAP message before it is handed over to the core engine. An incoming message can either be a SOAP message or a non-SOAP message (REST JSON or JMX). But at the transport level, it will be converted into a SOAP message.

We can download the latest Axis2 release. Each Axis2 release consists of four main release artifacts or distributions:

  • Binary distribution
  • WAR distribution
  • Source distribution
  • JAR distribution

The Axis2 WAR distribution is useful for deploying Axis2 in application servers such as Tomcat, Jboss, Weblogic, and so on. We can deploy the Axis2 WAR file into an application server, and check whether it works by typing the server address in a browser. For an example, if you deploy the Axis2 WAR file in Apache Tomcat, by typing http://localhost:8080/axis2 ,we can figure out whether Axis2 is up and running.

Set up the Environment

  1. Install JDK 1.5 or above in your system.
  2. After downloading Axis2 file (war version) extract the zip file to any local directory. After extracting you will find axis2.war file. Copy the file and paste it to the <TOMCAT_HOME>webapp| directory, then start Tomcat. You will see following in the console:
Figure 2. Tomcat startup console
Tomcat startup console

After this go the <TOMCAT_HOME>webapps| directory, inside this you will find a new directory named axis2, which indicates that the axis2.war file is deployed successfully.

  1. Download and install Java Micro Edition SDK 3.0.

Set up the web service: Code-First Approach (Bottom up web service)

If you are new to the web services area, then the best thing is to start with the POJO approach, since that is just writing a set of lines of Java code. We can expose the Java class as a web service and consume it universally. So, let us discuss the code first, and see how we can write an Axis2-compatible web service using a Java class. In the code first approach, we start by writing the service implementation class or the class that provides the service. So, first, we will write a simple web service, which says hello, when the service is invoked.

Let us assume that our service class does not have any package name and will appear as follows:

Listing 1. HelloWorld.java
public class HelloWorld { 
public String sayHello(String name) { 
return "Hello " + name; 
}
}
  1. Create a HelloWorld.java file which will return a string as shown in the above and compile this code as shown below.
Figure 3. Compiling HelloWorld.java
Compiling HelloWorld.java
  1. Then find HelloWorld.class file and Go to <TOMCAT_HOME> | webapps | axis2 | WEB-INF.
  2. Create a directory called 'pojo' inside the WEB-INF directory.
  3. Next, copy the HelloWorld.class file into the pojo directory.
  4. If Tomcat is not running, then start it.
    Go to http://localhost:8080/axis2/services/listServices where you can find a service called HelloWorld as shown in the figure below.
Figure 4. AXIS2 web service list
AXIS2 web service list

You can access the HelloWorld web service in the AXIS2 engine through the localhost by typing its URL in the browser as shown below:

http://localhost:8080/axis2/services/Helloworld

If you navigate there, you'll see a description of the service, and the one method: sayHello(String name). We're going to invoke that method remotely from a Java ME Midlet.

To view the WSDL type http://localhost:8080/axis2/services/Helloworld?WSDL in the URL.

Set up the J2ME-Client

To invoke any web service a client is required. Whether it's a web-client or mobile client both requires to know the endpoint interface of the web service. This can be resolved by creating stubs and including them in the client application.

Generating the Stub Class

Next, we will need the Web Service Description Language (WSDL) description of the service to generate the "stub" Java classes.

The Java ME SDK contains a tool called "wscompile", that reads the WSDL data and generates a "stub" Java class. This class acts as a local proxy for the remote service. We call a method in the stub class, and it calls the remote method for us.

  1. You need to create the 'config.xml' file as shown below (for HelloWorld Web service):

    (The wsdl location must match the URL for the service (with "?WSDL" tacked on the end). The packageName is the package for the generated files.)
Listing 2. config.xml
<?xml version="1.0"?>
<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
<wsdl location=" http://localhost:8080/axis2/services/HelloWorld?wsdl" 
                                            packageName="rpcdemo" />
</configuration>
  1. Save this file in the <J2ME_SDK_HOME> | bin| directory.
  2. Next generate the stubs by executing the command as show below:

\Java_ME_platform_SDK_3.0\bin\wscompile.exe -gen -cldc1.1 config.xml

This will give a view as shown in the figure below. (You should specify -cldc1.1 if the web service might use floats or doubles as arguments or return value. And make sure that the server (Tomcat) is running while executing this command).

Figure 5. Stub generation
Stub generation
  1. After executing this, you should have a file (amongst others) for the class: 'HelloWorldPortType_Stub.java' in the 'rpcdemo' directory that was created automatically inside <J2ME_SDK_HOME> bin| directory.

Creating the Client Project

  1. Now start the Java(TM) ME SDK Platform and Create a Project(uncheck Hello Midlet) as shown in the figure below.
Figure 6. Creating new project in Sun Java(TM) ME SDK 3.0
Creating new project in Sun Java ME SDK 3.0
  1. Next create a Package name 'rpcdemo' inside the Project named 'Test' as shown in figure 7 and copy the stub java files from <J2ME_SDK_HOME> bin|rpcdemo| directory and paste it in the rpcdemo package as shown in Figure 8.
Figure 7. Creating a package in Sun Java(TM) ME SDK 3.0
Creating a package in Sun Java ME SDK 3.0
Figure 8. Adding the stubs
Adding the stubs
  1. Now create an new Midlet named 'HelloMid' (as shown in Figure 9) within rpcdemo package and write the code for it as shown sequentially:
    • Create a form.
    • Add a text field in the form.
    • Create an object of the stub.
    • Use the 'object._setProperty()' function to specify the Endpoint Interface.
    • Invoke the service method by 'object.method(parameters)'.
    • Process and display the returns.
Figure 9. Creating a MidLet in Sun Java(TM) ME SDK 3.0
Creating a MidLet in Sun Java(TM) ME SDK 3.0
Listing 3. HelloMid.java
package rpcdemo;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
import java.rmi.RemoteException;
public class HelloMid extends MIDlet implements Runnable, CommandListener {
Display display;
private Form f;
private TextField tf;
private Command sendCom = new Command("Send", Command.ITEM, 1);
private Command exitCom = new Command("Exit", Command.EXIT, 1);
String name = "";
public void startApp() {
display = Display.getDisplay(this);
f = new Form("Hello Client");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCom);
f.addCommand(exitCom);
f.setCommandListener(this);
display.setCurrent(f);
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == sendCom) {
name = tf.getString();
/* Start a new thread so that the remote invocation won't block the process */
new Thread(this).start();
}
if (c == exitCom) {
notifyDestroyed();
destroyApp(true);
}
}
public void run() {
try {
/* Create Stub and set URL for the service*/
HelloWorldPortType_Stub service = new HelloWorldPortType_Stub();
service._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, 
               "http://localhost:8080/axis2/services/HelloWorld");
	      
println("Connecting...");
String msg = service.sayHello(name);
println(msg);
} catch (Exception e) {
println(e.toString());
}
}
private void println(String s) {
f.append(s + "\n");
}
}
  1. Finally Build the Project (you will see build success full in the console) and then click the Run button to execute the J2ME Emulator as shown in Figure 10.
Figure 10. J2ME Emulator in Sun Java(TM) ME SDK 3.0
J2ME Emulator in Sun Java(TM) ME SDK 3.0
  1. Now Choose the Menu Button and SELECT < Querty. Then Choose Abc, to enter character from the Emulator itself or Virtual Mode (to enter character from keyboard). Finally type your name (like in this example: KUNTAL GANGULY). See Figure 11.
Figure 11. Enter a String in the J2ME Emulator
Enter a String in the J2ME Emulator
  1. Click the send button as shown in Figure 12.
Figure 12. Press the send button in the Emulator
Press the send button in the Emulator
  1. You receive a Display like shown in the figure below.
Figure 13. Output screen in the Emulator
Output screen in the Emulator

This concludes the Hello world example. In the next section, I will discuss how to access a web service deployed on WebSphere Application Server Community Edition from J2ME client.


Accessing web service deployed on WASCE from J2ME client

Introduction

This section describe how to access 'Login' web service developed using eclipse IDE and deployed in WebSphere Application Server Community Edition (WASCE). This example shows how the J2ME client access database (MySQL in this example) through the web service. (Note: J2ME cannot access database directly on its own). But first here is some brief overview about WASCE and Eclipse IDE.

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

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.

MySQL: The MySQL software delivers a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server. MySQL Server is intended for mission-critical, heavy-load production systems as well as for embedding into mass-deployed software. MySQL is a registered trademark of MySQL AB. The MySQL installation packages can be downloaded from http://dev.mysql.com/downloads/.

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

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

You can also install it from the internet directly by follow these steps:

  1. Start Eclipse
  2. Go to Help > Software Updates
  3. Select the Available Software tab and click on the Add Site button. Then enter this URL: http://public.dhe.ibm.com/software/websphere/wasce/updates/
  4. Restart Eclipse

Set up the environment

  1. Download the MySQL connector jar file (mysql-connector-java-3.0.17-ga-bin or mysql-connector-java-5.1.13) from: then copy and paste the jar file in <JAVA_HOME>jdk1.7|lib directory and set this in the CLASSPATH of environment variable as shown below:
Figure 14. Setting the CLASSPATH environment variable
Setting the CLASSPATH environment variable
  1. Create a table name logintab as shown below:
Listing 4. Create table DDL
CREATE TABLE 'logintab' (
  'username' varchar(30) default NULL,
  'password' varchar(20) default NULL,
  'profession' varchar(40) default NULL
);
Figure 15. Retrieving the mysql table
Retrieving the mysql table

Developing and Deploying Login web service using Eclipse and WAS CE

  1. Install Eclipse WTP plug-in.
  2. Install Eclipse WEP plug-in.
  3. Create a directory lib inside <JAVA_HOME> and copy-paste tool.jar file from <JAVA_HOME>jdk1.7|lib to <JAVA_HOME>lib.
  4. Configuring WAS CE with Eclipse: After the WEP is installed, restart Eclipse and go to Window > Open Perspective > Other, select Java EE as shown in the figure below and click OK.
Figure 16. Changing perspective in eclipse
Changing perspective in eclipse
  1. Now you can see the Servers tab at the bottom of the screen (see Figure 17). In this tab, right-click on a blank space and choose New > Server as show below. This will add a new server to the tab. If for any reason you do not see the Servers tab, go to Window > Show View, and then select the Servers view.
Figure 17. Instantiate new server
Instantiate new server
  1. Select IBM WASCE v2.1 Server as shown below and click Next as shown below.
Figure 18. Select WASCE v2.1 as server
Select WASCE v2.1 as server
  1. Click Browse and specify the JRE and the location where you have installed Community Edition as shown in Figure 19. Then click Next.
Figure 19. Set Server runtime environments
Set Server runtime environments
  1. Set the administrator's user ID (defaults to 'system') and password (defaults to 'manager') for your Community Edition server. This is shown in the figure below and click Next.
Figure 20. Set localhost and RMI
Set localhost and RMI

In the Add and Remove Projects window simply click Finish. Community Edition is now configured to work in Eclipse. You should be able to see your server in the Servers tab as shown below to start and stop your server, use the appropriate buttons as shown in the figure shown below. After you start the server, you should see the state column change to a value of Started.

Figure 21. Start the Wasce server
Start the Wasce server

Note: You may face a 'PermGen Space' error which occurs when the JVM runs out of space in the permanent generation heap while creating custom Deployment Environment profile. [(PermGen is the permanent generation of objects in the VM (Class names, internalized strings, objects that will never get garbage-collected)]. An easy, if somewhat memory-hungry fix is to enlarge the maximum space for these objects in the following way:

To resolve this first close the Eclipse and then go to the directory where eclipse is installed through command prompt and type this command:

General Syntax:

eclipse [normal arguments] -vmargs -XX:PermSize=64M -XX:MaxPermSize=128M 
[more VMargs]
eclipse.exe -vmargs -Duser.language=en -Xms128M -
        Xmx512M -XX:PermSize=64M -XX:MaxPermSize=128M

Set up the Web-Service

  1. Start Eclipse in JavaEE perspective and select File > New > Other > Dynamic web Project as shown in the following two figures.
Figure 22. Create new project in Eclipse
Create new project in Eclipse
Figure 23. Select Dynamic Web Project
Select Dynamic Web Project
  1. Create a Project name 'LoginService' and select IBM WASCE v2.1 as the target runtime environment having default configuration for the Project as shown in Figure 24.
Figure 24. Project name and runtime
Project name and runtime
  1. Expand the LoginService Project tab, select Java Resource: src and create a package 'com.ibm.wasce.login' as shown in Figure 25.
Figure 25. Create new package in Eclipse
Create new package in Eclipse
  1. Now create an interface (LoginSEI) inside 'com.ibm.wasce.login' package as shown in Figure 26. Add the web service annotation and a method which will return a string and will accept username and password as its parameters.
Figure 26. Create new interface in Eclipse
Create new interface in Eclipse
Listing 5. LoginSEI.java
package com.ibm.wasce.login;

import javax.jws.WebService;

@WebService (name="LoginSEI",targetNamespace="http://login.wasce.ibm.com")

public interface LoginSEI {

public String loginDB(String Username, String userpass);
}
  1. Now create a class named 'login' inside 'com.ibm.wasce.login' package as shown in Figure 27.
Figure 27. Create new class file in Eclipse
Create new class file in Eclipse
Listing 6. login.java
package com.ibm.wasce.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.jws.WebService;

import com.ibm.wasce.login.LoginSEI;
@WebService (serviceName = "LoginService",portName = "LogPort",
		endpointInterface = "com.ibm.wasce.login.LoginSEI",
		targetNamespace = "http://login.wasce.ibm.com")

public class login implements LoginSEI{

	
	
Connection conn = null;
Statement st=null;
ResultSet rs=null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "secret";
String s="";
String m="";
public String loginDB(String username,String userpass){
     
    
    

    
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);

String strQuery="select * from logintab where username='"+username+"' and  
                                                password='"+userpass+"'";
           
st = conn.createStatement();
rs = st.executeQuery(strQuery);
          
rs.next();
System.out.println("SUCCESS");
s=rs.getString(1);
m=rs.getString(3);
          
    } catch (SQLException e) {
return("User is NOT registered");
        
    }

    catch (Exception e)
    {
       
System.err.println ("CANNOT CONNECT TO DATABASE.....");
    }
return ("WELCOME   '  "+ s+"  '     Your Profession:    "+m);
	      
         
    }
	
}
  1. Edit the web.xml and add the following code inside <web-app> .. </web-app>.
Listing 7. Web.xml
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.ibm.wasce.login.login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/LOGIN</url-pattern>
</servlet-mapping>
  1. Now save the Project. Then Select Project (Right click) go to Run As > Run on Server as shown in the figure below.
Figure 28. Run on server
Run on server
  1. Select LoginService, Click Add and then Finish as shown in Figure 29.
Figure 29. Deploy project on server
Deploy project on server
  1. Now open your browser and enter the following: http://localhost:8080/LoginService/LOGIN to see LoginService as shown in Figure 30.
Figure 30. View of the deployed service
View of the deployed service
  1. To see the WSDL enter: http://localhost:8080/LoginService/LOGIN?WSDL

Set up the J2ME-Client

This section shows how to consume a 'LoginService' web service deployed in WASCE from your J2ME Client. For this example, we are going to access the LoginService web service: http://localhost:8080/LoginService/LOGIN

If you navigate there, you will see a description of the service, and its one method: loginDB(String username, String userpass). We're going to invoke that method remotely from a Java ME MidLet.

Generating the Stub Class

The client stub generation is similar to the previous example of 'Hello World' service, just one need to change the WSDL location in the config.xml file to http://localhost:8080/LoginService/LOGIN?WSDL and packageName to 'LoginStubs' (you can use any package you like).

Creating the Client Project

Creating the client project is similar to the previous "Hello World" example.

  • Now start the Java™ ME SDK Platform and Create a Project (uncheck Hello Midletsuite).
  • Next create a Package name 'LoginStubs' inside the Project named LogClient. Copy all the stub java file from <J2ME_SDK_HOME>bin|LoginStubs| directory and paste it in the LoginStubs package.
  • Now create an new Midlet (LogMid) within LoginStubs package and add the following things:
    • Create a form.
    • Add two text fields in the form for 'username' and 'password'.
    • Create a object of the stub.
    • Use the 'object._setProperty()' function to specify the Endpoint Interface.
    • Invoke the service method by 'object.method(parameter,parameter)'.
    • Process and display the returns.
Listing 8. LogMid.java
package LoginStubs;

   import javax.microedition.midlet.*;
   import javax.microedition.lcdui.*;
   import java.io.*;
   import java.util.*;
   import java.rmi.RemoteException;

public class LogMid extends MIDlet implements Runnable, CommandListener {

Display display;
private Form f;
private TextField tf,cf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
String name = "";
String pass = "";

public void startApp() {

display = Display.getDisplay(this);
f = new Form("Login Client");
tf = new TextField("Username:", "", 30, TextField.ANY);
cf = new TextField("Password:", "", 30, TextField.PASSWORD);
f.append(tf);
f.append(cf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);

	  }

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {

if (c == sendCommand) {
name = tf.getString();
pass = cf.getString();
  /* Start a new thread so that the remote invocation won't block the process.*/
new Thread(this).start();
	    }
if (c == exitCommand) {
notifyDestroyed();
destroyApp(true);
	    }
	  }

public void run() {
try {
/* Create Stub and set URL for the service*/
 LoginSEI_Stub service = new LoginSEI_Stub();
 service._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, 
                        "http://localhost:8080/LoginService/LOGIN");

println("Connecting...");
String msg = service.loginDB(name,pass);
println(msg);
	      	    } catch (Exception e) {
println(e.toString());
        }
    }

private void println(String s) {
f.append(s + "\n");
    }
        }
  • Finally Build the Project (you will see build successful in the console) and then click the Run button to execute the J2ME Emulator.
  • Now Choose Menu Button and SELECT > Querty. Then Choose Abc (To enter character from the Emulator itself) or Virtual Mode (to enter character from keyboard). Finally type User name and Password for which you want to access the Profession (in this example: Username: 'Partha' and Password: 'goswami')and click the SEND button from Menu as shown in Figure 31.
Figure 31. Runtime display in J2ME Emulator of Sun Java ME SDK 3.0
Runtime display in J2ME Emulator of Sun Java ME SDK 3.0

You will get display like this (see Figure 32):

Figure 32. Enter username and password to login
Enter username and password to login

This concludes the Login example.


Accessing . NET web service from J2ME Client

Introduction

This section shows how to consume a web service already hosted in the Internet (not in the Local host) from your J2ME Client.

For this example, we are going to access the Stock Quote web service build on .NET platform:

Click on to this http://www.webservicex.net/stockquote.asmx

If you navigate there, you will see a description of the service, and it's one method: getQuote(String name). We are going to invoke that method remotely from a Java ME Midlet.

Figure 33. StockQuote hosted web service
StockQuote hosted web service

If we click on to the Service Description link in the right corner of the web page, it will display the WSDL of the Stock-Quote service. As the service is already deployed and active we just need to create a client and invoke it through the stubs.

Generating the Stub Class

The client stub generation is similar to the previous example of 'Hello World' service, just one need to change the WSDL location in the config.xml file to http://www.webservicex.net/stockquote.asmx?wsdl and packageName to 'stockdemo' (you can use any package you like).

Creating the Client Project

  • Now start the Java™ ME SDK Platform and Create a Project (uncheck Hello Midletsuite).
  • Next create a Package name 'stockdemo' inside the Project named Quote. Copy all the stub file from <J2ME_SDK_HOME>bin|stockdemo| directory and paste it in the stockdemo package.
  • Now create an new Midlet (StockMid) within stockdemo package and add the following code:
Listing 9. StockMid.java
package stockdemo;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
import java.rmi.RemoteException;

public class StockMid extends MIDlet implements Runnable, CommandListener {
Display display;
private Form f;
private TextField tf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
String name = "";
public void startApp() {
display = Display.getDisplay(this);
f = new Form("Stock Client");
tf = new TextField("Stock Quote:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
	  }
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable d) {
if (c == sendCommand) {
name = tf.getString();
/* Start a new thread so that the remote invocation won't block the process.*/
new Thread(this).start();
	    }
if (c == exitCommand) {
notifyDestroyed();
destroyApp(true);
	    }
	  }
public void run() {
	    try {
/* Create Stub and set URL for the service*/
 StockQuoteSoap_Stub service = new StockQuoteSoap_Stub();
 service._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, 
                    "http://www.webservicex.net/stockquote.asmx");

println("Stock Quote for:"+tf.getString());
String msg = service.getQuote(name);
println(msg);
	      	    } catch (Exception e) {
println(e.toString());
        }
    }

private void println(String s) {
f.append(s + "\n");
    }
        }
  • Finally Build the Project (you will see build successful in the console) and then click the Run button to execute it in the J2ME Emulator.
  • In the emulator choose Menu Button and SELECT > Querty. Then choose Abc (To enter character from the Emulator itself) or Virtual Mode (to enter character from keyboard). Finally type name or symbol for which you want to access stock quote details (in this example: IBM) and click the SEND button from Menu (see Figure 34).
Figure 34. Enter the name of the stock in the emulator
Enter the name of the stock in the emulator
  • You Get the information about the stock in XML format as shown in Figure 35:
Figure 35. Displayed information in xml for the specific stock
Displayed information in xml for the specific stock

This concludes the Stock Quote example.


Conclusion and summary

Conclusion

The above three examples gives you an overview how J2ME can be used with today's modern technologies in a loosely coupled manner following the methodology of SOA.

Summary

In this tutorial, you have learned how to use Eclipse IDE and the Sun WTK. You have also learned how to develop a web service and deploy it in various servers and consume the web service through J2ME client developed in Sun WTK. These free tools allow Java developers to quickly learn and prototype J2ME applications for mobile phones.


Download

DescriptionNameSize
Sample files for this tutorialCode.zip14KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

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

 


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

All information submitted is secure.

Choose your display name



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

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

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

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

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=631080
ArticleTitle=Developing a web service and consuming it with J2ME Client
publish-date=03092011