|
|
DEVELOPMENT
Building J2ME Applications for the Extended Enterprise
Learn how J2ME fits into the extended enterprise and examine some of the issues -- such as communication mechanisms and security -- you'll have to consider when architecting a J2ME application.
Java 2 Micro Edition (J2ME) is finding widespread use in many different devices. J2ME is directed at devices that have hardware and bandwidth limitations that make them otherwise unsuitable to be used with the full-feature Java 2 Standard Edition (J2SE). In this article, I'll discuss the J2ME architecture in brief and then show you how J2ME fits into the extended enterprise. I'll look at some of the issues -- such as communication mechanisms, reliability, and security -- you'll have to consider when architecting J2ME solutions. I'll also walk you through building a sample application and take a look at the Wireless Messaging APIs (WMA).
 |
| Figure 1: The elements of J2ME -- A J2ME environment is a combination of a configuration, a profile, and any optional packages. |
 |
| Figure 2: Enter a stock symbol -- After you install the example application, the device should look like this. |
 |
| Figure 3: View the 20-minute delayed stock value -- The example application makes a Web service call to a remote server to get the stock value. |
J2ME
J2ME defines a set of technologies for limited-resource devices. As I mentioned, these devices have hardware and bandwidth limitations that make them unsuitable for use with the full-feature J2SE edition. Even among these devices, some are more capable than others. To allow for such variations in device capabilities and features, the J2ME specification defines configurations and profiles. A J2ME environment is a combination of a configuration, a profile, and any optional packages (figure 1). Each environment is optimized towards a set of devices with similar features and capabilities.
Configuration
A configuration is aimed at a horizontal set of devices with similar hardware features. The configuration defines the minimal set of Java libraries that must be present as well as the features of the K Virtual Machine (KVM). Currently available configurations are the Connected Device Configuration (CDC) and the Connected Limited Device Configuration (CLDC). You use the CLDC on devices with lesser capabilities, such as cell phones, whereas you use the CDC on more capable devices, such as high-end PDAs.
The KVM is a virtual machine designed to demonstrate the basic functionalities of the CLDC specification in conjunction with the CLDC libraries.
Profile
A profile is always implemented on top of a configuration. It defines additional features and APIs for a specific vertical segment. Some examples of profiles are the Mobile Information Device Profile (MIDP, used with CLDC), Foundation Profile (used with CDC), Personal Basis Profile (used with CDC), and the Personal Profile (used with CDC). Refer to http://java.sun.com/j2me for more details on configurations and profiles.
For the rest of the article, I'll use J2ME with the CLDC/MIDP environment.
The extended enterprise
Users no longer access enterprise applications only from dedicated terminals. They have to access these applications anytime, anywhere, and often from different types of devices. Often, these devices are wireless devices such as cell phones, PDAs, etc. Consider a situation where workers on the shop floor need reliable access to applications on their handheld devices. The challenge is to have useful applications running on these different devices, which often have hardware and bandwidth constraints.
Your options are to build the application based on the programming environment for each of those device types or build one J2ME application that will run on all of them, assuming that all the devices have a supported J2ME implementation. If you choose the first approach, then you have a maintenance nightmare of actually supporting the different application platforms. It's obviously beneficial to build the application once and deploy it on all of these varying device types. That's exactly what J2ME can do. Because the J2ME architecture assumes a certain set of device capabilities exist, you could build the application using J2ME and have it installed on all the devices.
In the remaining part of this article, I'll explore different aspects of writing a J2ME client application.
Message exchange mechanisms (between client and server)
How do you exchange messages between the J2ME client application and the server? I'll discuss some possible solutions. The actual solution you use will depend on your application's requirements and architecture.
The CLDC/MIDP lets you make HTTP and HTTPS calls to remote servers, so all communication with the server can take place via HTTP. The message format can be either plain text or XML, although the latter requires that you have an XML parser on the J2ME devices. Lightweight XML parsers, such as kXML, are available for mobile devices.
Listing 1 shows a code sample of how to communicate using HTTP from a J2ME device.
Listing 1: HTTP-based communication between a server and J2ME device.
HttpConnection conn = null;
InputStream is = null;
OutputStream os = null;
try
{
String url = ...;
byte[] body = ...;
// --set up the connection
conn = (HttpConnection)Connector.open(url, Connector.READ_WRITE,true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", "" + body.length);
os = conn.openOutputStream();
os.write(body);
// -- resolve the response
is = conn.openInputStream();
int code = conn.getResponseCode();
// --Check http response code
if (code != HttpConnection.HTTP_OK))
{
// something went wrong...handle that
}
// --get the response
ByteArrayOutputStream stream = new ByteArrayOutputStream(100);
byte buffer[] = new byte[100];
int read = 0;
while ((read = is.read(buffer)) != -1)
{
stream.write(buffer, 0, read);
}
}
finally
{
// close http connection
conn.close();
// close the streams 'is' and 'os'
is.close();
os.close();
}
Web services
Web services are a standards-based technology you can use to communicate between distributed and heterogeneous applications within the enterprise and with external entities. Web services use Simple Object Access Protocol (SOAP) as the XML-based protocol to communicate between applications. Applications advertise their services using Web Services Definition Language (WSDL). WSDL is an XML document that describes the services and where to find them. Using SOAP and WSDL, you can expose individual application services as Web services. And finally, Universal Description, Discovery, and Integration (UDDI) lets you publish the Web service definitions so that customers can find the services.
Your J2ME clients can communicate with the server using Web services as the underlying communication mechanism. You'll need a SOAP toolkit for your J2ME device. For a quick example (listing 2), you can use the open-source kSOAP 1.2 (see http://ksoap.enhydra.org), which is designed to work on CLDC/MIDP devices. kSOAP also requires the kXML parser for parsing XML (you can get it at http://www.kxml.org).
Listing 2: A short example of communicating with the server from a J2ME client using Web services as the underlying communication mechanism.
import org.ksoap.*;
import org.ksoap.http.*;
.....
String symbol = "IBM";
SoapObject soapRequest = new SoapObject("urn:xmethods-delayed-quotes", "getQuote");
soapRequest.addProperty ("symbol", symbol);
Object result =
new HttpTransport("http://services.xmethods.net/soap",
"urn:xmethods-delayed-quotes#getQuote").call (soapRequest);
.....
Building a sample application using J2ME
I strongly recommend that you download and make use of the J2ME Wireless Toolkit, available at http://java.sun.com/products/j2mewtoolkit. This toolkit is invaluable for development purposes.
My example application is simple. It returns the 20-minute delayed stock value for the symbol you enter. I'll make a Web service call to a remote server to get the stock value. I don't go into details of Sun's MIDP 2.0 and its programming environment (for more information, go to http://java.sun.com/products/midp). I'll leave it upon the reader to learn the finer points of the API and the environment.
The following are the steps required to build an application:
- Create a new project using the J2ME toolkit. This generates a project tree where you can place files. Name the project StockMidlet.
- Write your Midlet java class (and any supporting helper classes). Place the source files in the <project>/src folder. For my example, you can also place the StockMidlet.java source code, which is listed with this article (also listed is the StockMidlet.jad file for your reference).
- Place the kSOAP library in the <project>/lib folder.
- Specify the permissions required for your MIDlet suite in the .JAD file, using Project > Settings > Permissions. Give your application "http" permissions.
- Build your project.
- Now you can run the application. Enter the stock symbol, and you should get back the 20-minute delayed value.
I'll walk you through the StockMidlet.java source shown in listing 3. You can view the full listing in the download for this article.
Listing 3: The source code for StockMidlet.java.
1. import javax.microedition.midlet.*;
2. import javax.microedition.lcdui.*;
3. import org.ksoap.*;
4. import org.ksoap.transport.*;
5.
6. public class StockMidlet extends MIDlet implements CommandListener
7. {
8. ... other members here ...
9. private Command cmdExitBtn;
10. private Command cmdOkBtn;
11. private Form queryForm;
12. private TextField stockSymbol;
13.
14. public StockMidlet ()
15. {
16. // build the user interface elements
17. ....
18. }
19.
20. public void commandAction(Command c, Displayable d)
21. {
22. ... other code ...
23.
24. if (c == cmdOkBtn)
25. {
26. String symbol = stockSymbol.getString().trim();
27. SoapObject rpc = new SoapObject("urn:xmethods-delayed-quotes", "getQuote");
28. rpc.addProperty("symbol", symbol);
29.
30. HttpTransport http =
31. new HttpTransport("http://66.28.98.121:9090/soap",
32. "urn:xmethods-delayed-quotes#getQuote");
33. ... other code ...
34. Object result = http.call(rpc);
35. Alert alert = new Alert("Result", symbol+"="+result, null, AlertType.INFO);
36. alert.setTimeout(Alert.FOREVER);
37. display.setCurrent(alert);
38. ... other code ...
39. }
Line 26: Collect the user-entered stock symbol.
Line 27: Build a SoapObject that identifies the Web service.
Line 28: Add the parameter named "symbol" with the stock symbol. This is what the Web service expects.
Line 30: Initialize the HttpTransport you'll use to make the Web service call.
Line 34: Make the call. The result is returned in the variable named "Result."
Line 35 to 37: Display the result.
If you want to distribute this application to clients, then you'll have to create a MIDlet suite. That is just a .JAR of your complete application, which will include your classes, any libraries, and the .JAD file. The application descriptor (.JAD) file contains information the application management software on the device will use to identify the application. For example, the application management software can look at the .JAD and verify the size of the actual MIDlet suite (the .JAR file). If the size exceeds any limits the device imposes, then it can notify the client. The J2ME Wireless Toolkit generates the .JAD file for you. To package an application, select menu option Project > Package > Create Package. The StockMidlet.jad and the StockMidlet.jar files are generated to the <project>/bin folder.
When you execute the application, it should like figures 2 and 3 on the device.
Reliable message delivery
Now that you're running enterprise applications on wireless devices, the next issue is reliability. For an enterprise application, the client and server must exchange messages reliably. These wireless devices often don't have a reliable connection to the server. You have to factor in the problem of intermittent connections when designing applications for these devices.
What happens if the client makes a credit card payment over the wireless phone and the server accepts the transaction, but the client doesn't receive the response acknowledgement? There's a real danger that the client will submit the same request again. For enterprise applications, reliability is of the utmost importance, and you have to architect applications to take this into consideration.
I'll introduce the notion of a request manager that sits between the client and the server. It's the request manager's task to make sure messages are delivered reliably and only once. When the application submits requests, it does so via the request manager APIs and not directly using the MIDP APIs (or kSOAP, as in my earlier example). The request manager first stores the request and then tries to forward the request to the server. The server also has to store information about the request, such as if the request has finished processing. That way, if the client doesn't get a response, the request manager can later check the server directly for the status.
Using the above or similar mechanism, you can fulfill the reliability requirement to some extent.
Security
MIDP 2.0 adds quite a bit more in terms of security compared to MIDP 1.0. In MIDP 1.0, MIDlet suites ran in a closed environment. Different MIDlet suites can't share common classes or the same RMS data store. Each MIDlet suite runs in complete isolation from others installed on the same device.
MIDP 2.0 introduces the concept of trusted and untrusted MIDlet suites. An untrusted suite is one whose origin and integrity can't be verified. All MIDP 1.0 MIDlet suites automatically run as untrusted. Untrusted MIDlets have access to the following without any user intervention: javax.microedition.rms, javax.microedition.midlet, javax.microedition.lcdui, javax.microedition.lcdui.game, javax.microedition.media, and javax.microedition.media.control.
In the untrusted mode, certain resources such as network connections aren't allowed or the user must explicitly allow them. The device can detect that an untrusted application is requesting network access and then query the user to allow or disallow the network access.
In trusted mode, the application explicitly lists the permissions it requires by listing them in the application descriptor (.JAD). The .JAD entries are MIDlet-Permissions and MIDlet-Permissions-Opt. The later entry describes optional permissions, meaning the application can still work without them. The actual mechanism that determines whether the application is trusted is left up to the device and network providers. One approach is to use X.509 PKI to sign the MIDlet suites. Using the J2ME Wireless Toolkit, you can sign your MIDlet suites before distributing them.
Wireless Messaging API (WMA)
The Wireless Messaging API (WMA) is an optional package (javax.wireless.messaging) that lets you send and receive messages using protocols such as Short Message Service (SMS) or Cell Broadcast Short Message Service (CBS). Note that vendors can choose to implement additional protocols. WMA is written for the CLDC configuration, which makes it portable to CDC, as the CDC is a superset of CLDC.
WMA lets you send either text (javax.wireless.messaging.TextMessage) or binary (javax.wireless.messaging.BinaryMessage). Both of these implement the javax.wireless.messaging.Message interface. For my example in this article, I'll send a text message (listing 4).
Listing 4: With WMA, you can send either text or binary. This example sends text.
String address = "sms://+5550000";
MessageConnection conn = (MessageConnection) Connector.open(address);
TextMessage message =
(TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
message.setPayloadText("your SMS message here");
conn.send(message);
Notice the only place the message protocol appears is in the address URL. In this example, I use the SMS protocol. The MessageConnection belongs to the Generic Connection Framework (GCF), which lets the URL identify the protocol. The underlying J2ME implementation can then select the appropriate implementation classes.
Similarly, to receive message, you can do something like:
Listing 5: This code shows you how to receive a message in the example using the SMS protocol.
Message message = conn.receive();
if (message instanceof TextMessage)
{
TextMessage textMsg = (TextMessage)message;
textMsg.getPayloadText(); // will give you the text received
}
Provisioning applications (Over The Air)
How do you get your applications onto client devices? Distributing applications to wireless devices can be quite a challenge. Different vendors have different methods for installing applications.
Users can use a serial connection to the device to install applications, but sometimes network providers don't let you install certain types of applications via this approach. Also, most users won't be comfortable using this method to install applications. Imagine the average cell phone user using a serial connection to load applications on the device.
Ideally, you could require that applications be provisioned wirelessly. The MIDP 2.0 specification describes Over The Air (OTA) user-initiated provisioning and requires that the devices that support it be compliant with MIDP 2.0. When you implement the MIDP 2.0 OTA guidelines, they provide a common set of mechanisms to manage applications on devices.
The MIDP 2.0 specification requires that there be some type of application management software (AMS) on the device that manages the lifecycle of applications. The device must also have a discovery application (DA) that lets the user locate new applications. The device will download either the .JAD or the .JAR itself if it can't find the application descriptor. If the device downloads the application descriptor file (.JAD), it can make decisions based on the contents of that file or even present the user with information so that he can make an informed decision on whether to install. For example, some cell phone network providers limit the size of the application. An entry in the .JAD file tells the AMS the size of the application, and the AMS informs the user that the application exceeds the maximum allowed size. Finally, if all is good, the device downloads and installs the application.
The OTA specification also requires that the AMS let users remove applications and update existing applications with newer versions.
Mathew Thomas has worked in the software industry for more than six years and is a senior software engineer at Cysive, where he works in product development on the Cymbio Interaction Server. A Sun Certified Programmer and Sun Certified Developer, Mathew has a B.E. degree in computer engineering from Pune University, India, and is currently pursuing an M.S. degree in information systems and technology from Johns Hopkins University.
ARTICLE INFO
Web Edition: 2003.09.17, Doc #12697
FREE ACCESS
Keyword Tags: application development, Application Development, collaboration, development, E-Mail, ibm, it networking, java, J2ME, J2ME - Java 2 Micro Edition, Java, messaging, microsoft .net framework, mobile, mobile business, mobile development, Mobile, Mobile Development, Programming, security, software development, SOAP - Simple Online Access Protocol, wireless, Web Services, Wireless, Wireless Development, WSDL - Web Services Description Language, xml
ADVISORAMA All these new girls are so trashy... and do I get a thank-you note? -- Bette Midler
|
|