HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

In Parts 1 and 2 of this series, we covered the basic features of the various MIDP APIs. We looked at creating and packaging a MIDlet, creating a user interface, and some basic graphics operations. We also discovered how to store data with the record management system and how to communicate over the network.

This time around, we're going to talk about MIDP in the enterprise sense (which has nothing to do with "Star Trek"), and put together a basic example that shows how a MIDlet fits into the big picture.

As mentioned before, and it bears repeating, a J2ME developer will undoubtedly not be spending all of his or her time developing on the client side. J2ME applications, particularly MIDlets, will involve a degree of interaction with the server - and unless you're working on an exceptionally large system with a very big team, it seems likely you'll be the developer with "fingers in many pies."

What does that mean exactly? To put it in the simplest terms possible: if you've been neglecting your J2EE and J2SE education in favor of Micro Edition, now's the time to dig out those dusty textbooks and old copies of JDJ and do some serious reading.

Client to Server Communications
In standard Java, there are a number of ways a client-side application can communicate with another machine. We have everything from raw socket connections where you have to pretty much write your own communications protocols yourself, up to Remote Method Invocation (RMI) from one VM to another, on the same or a different host. On MIDP, however, we're reduced to the basics of network communications (for an introduction to networking in MIDP, see my previous article, in JDJ (Vol. 6, issue 8) - where HTTP will probably be the most common methodology.

Typically we'll see the following configurations for basic enterprise MIDP applications: a servlet talking directly to the database (as shown in Figure 1)or a servlet talking to an application server that talks to the database (or in some cases, with no database at all) as seen in Figure 2.

Figure 1
Figure  1:

Figure 2
Figure  2:

Configurations aside, there should be a layer between the MIDlet and the enterprise data, however it's held, to preserve a level of abstraction. For example, an HTML-based interface may view hundreds of rows of data at any one time, whereas a MIDlet may want to view only 10 or 20. Assuming that the enterprise layer has already been written, there may be no real point in adding yet another method to an EJB, just to retrieve 10 rows at a time from the database for a new MIDlet application - rather than retrieving the entire data set. Instead, write a servlet "interface" to the EJB that loads the data into the client's session and then the MIDlet may call the servlet any number of times to get subsets of required data.

The Example So Far
As it stands, last month's example MIDlet - the PhoneBook application - is fairly simple. You can list the contents of the phone book and add or remove contacts. If you remove the MIDlet suite from the phone, however, the contents of your phone book are lost.

To fix this problem, we need a repository - somewhere to put the data. One possibility here is to store the data in a directory server and access it directly in a servlet, which can expose simple methods for the MIDlet (or any other interface) to access the data. Another option is a database, with an EJB to handle data access. Again a servlet becomes a middleman between MIDlet and EJB/Database.

Rather than go through the rigmarole of setting up a database, the EJB used in this month's example writes its state out to a text file, and I've used the Java 2 Enterprise Edition SDK as the EJB container. Please note, to use the EJB, you'll have to set File-Write permissions in the policy file for the AppServer (server.policy, located in the j2sdkee/ lib/security directory), which is a quick and dirty cludge I've used in this case, but wouldn't recommend in an actual system.

Note: Look for default permissions in the policy file and change the line:

permission java.io.FilePermission "*", "read";
permission java.io.FilePermission "*", "read,write";
Listing 1 shows the "guts" of the PhoneEJB (a stateful session bean). There are five implemented methods: ejbCreate, ejbRemove, add, remove and getPhoneBook.
  • ejbCreate: Called when the EJB is created, and takes one parameter - user. It loads names and phone numbers from a data file of the same name (if it exists), and stores the information in a map.
  • ejbRemove: Called at the end of the EJB life cycle, at which point the bean can be garbage collected. In this case, the method writes the data out into a data file using the user details.
    - Add: Takes a name and phone number as string parameters and saves these into the map.
    - Remove: Takes a name as a string parameter and removes the matching record from the map.
    - getPhoneBook: Returns the map to the caller.
Nothing too complicated here, of course. The next step is to provide an easy way for the MIDlet to call this EJB. Listing 2 shows part of the doGet method in TestPhoneServlet.java.

Lines 1-6 instantiate an instance of the Phone EJB.

Line 8 retrieves the "action" parameter from the servlet request.

If no action has been specified, we assume that the caller wants to retrieve the data, so lines 9-21 call the getPhoneBook method on the EJB, to return the map and then iterate through the keys in the map, writing the name and phone number to the servlet output stream, with one record per line.

If "add" has been specified as the action, lines 22-32 get the name and phone number parameters from the servlet request, check to make sure they're not null, and then call the add method on the EJB.

If "remove" has been specified as the action, lines 33-42 get the name parameter from the request, check that it's not null, and then call the remove method on the EJB to remove the associated record.

In both cases, the servlet writes out an empty line if it succeeds, or an error message beginning with "%ERROR" if an unrecognized action is sent.

(Note: For my testing purposes I've used Apache's Tomcat servlet container.)

MIDlet Revisited
We now need to add functionality to the PhoneBook MIDlet to access the servlet. Listing 3 shows the first of the new functionality - the initRecordStore method. This method calls the servlet using the URL:

You'll recall from the servlet code, if you pass no parameters in this manner, then a list of records is returned by the servlet. If no errors occurred (a return of "%ERROR" from the servlet indicates something went awry), then the current contents of the record store are deleted and replaced with this list.

To add each record to the store, the initRecordStore method calls save (implemented in last month's installment). Note that the save method has also been modified to take a Boolean parameter (sendToServer), which indicates whether the data should be saved to the server in addition to the record store. As we're initializing the record store, we don't want to save it to the server.

Listing 4 shows the changes to the save and erase methods. The main difference in these is that the send-to-server functionality has been implemented to ensure that any changes made at the client level are mirrored on the server.

Missing from This Version
Apart from a few more supporting methods and some minor changes, the MIDlet is essentially the same. Of course, the example is hardly what you would call an "enterprise application." It does demonstrate that adding this sort of capability to a MIDP application is fairly straightforward. If we were to extend this MIDlet into part of an enterprise Personal Information Manager suite (for example), then we might want to add more validation and include more data in the phone book (mobile number, fax number, e-mail address, etc).

One "buglet" in the current app is that duplicates are allowable in the client, but in the EJB they'll be overwritten (since the data is stored in a map and keyed on name, the phone number is overwritten in the case of a duplicate). Either we could store the information differently in the EJB, or disallow duplicates in the MIDlet.

Where to Go from Here?
Even if you're a seasoned embedded/mobile systems developer, J2ME (or in this case, MIDP) introduces new variables into what may have been, up until now, a fairly straightforward equation. Java's strong networking support means your enterprise application may be split across multiple platforms (client and multiple server tiers), in a way it might not have been with traditional development methods and languages.

Parts 1-3 introduced ways you might go about using the various MIDP packages. Of course, this doesn't help when you're actually trying to decide how your application should be distributed across your architecture. In the end, there's no substitute for good old hands-on experience - trying out small projects for yourself. Good luck, and let the MIDP production line roll!

Author Bio
Jason Briggs works as a Java analyst programmer in London. He's been officially developing in Java for three years - unofficially for just over four. [email protected]


Listing 1 PhoneEJB.java

import java.io.*;
import java.g.*;
import javax.ejb.*;

public class PhoneEJB implements SessionBean {

  String user;
  Map phoneBook;

  public void ejbCreate(String user) throws CreateException {

    DataInputStream dis = null;

    try {
      if (user == null) {
        throw new CreateException("Null user not allowed.");
      else {
        this.user = user;

      phoneBook = new HashMap();

      File f = new File(user + ".dat");
      if (f.exists() && f.canRead()) {
        dis = new DataInputStream(new FileInputStream(f));

        while (dis.available() > 0) {
          String name = dis.readUTF();
          String phone = dis.readUTF();

    catch (IOException e) {
      throw new CreateException("unable to read data file : " + e.getMessage());
    finally {
      if (dis != null) {
        try { dis.close(); } catch (Exception e) { }
        dis = null;


  public void ejbRemove() {
    DataOutputStream dos = null;
    try {
      dos = new DataOutputStream(new FileOutputStream(user + ".dat"));

      Iterator iter = phoneBook.keySet().iterator();
      String name, phone;
      while (iter.hasNext()) {
        name = (String)iter.next();
        phone = (String)phoneBook.get(name);


    catch (IOException e) {
    finally {
      if (dos != null) {
        try { dos.close(); } catch (Exception e) { }
        dos = null;


  public void add(String name, String phone) {
    phoneBook.put(name, phone);

  public void remove(String name) {
    if (phoneBook.containsKey(name)) {

  public Map getPhoneBook() {
    return phoneBook;

  public PhoneEJB() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void setSessionContext(SessionContext sc) {}


Listing 2 : TestPhoneServlet.java (part of doGet method)

1.    Context initial = new InitialContext();
2.    Object objref   = initial.lookup("MyPhoneEJB");
4.    PhoneHome home  = 
(PhoneHome)PortableRemoteObject.narrow(objref, PhoneHome.class);
6.    phoneejb  = home.create("test");
8.    action    = request.getParameter("action");
9.    if (action == null || action.equals("")) {
11.     Map phoneBook   = phoneejb.getPhoneBook();
13.     Iterator iter = phoneBook.keySet().iterator();
14.     while (iter.hasNext()) {
15.       String name = (String)iter.next();
16.       String phone = (String)phoneBook.get(name);
18.       out.println(name + phone);
19.     }
21.   }
22.   else if (action.equals("add")) {
23.     String name = request.getParameter("name");
24.     String phone = request.getParameter("phone");
25.     if (name == null || phone == null) {
26.       throw new Exception("missing name and/or phone");
27.     }
29.     phoneejb.add(name,phone);
31.     out.println("");
32.   }
33.   else if (action.equals("remove")) {
34.     String name = request.getParameter("name");
35.     if (name == null) {
36.       throw new Exception("missing name");
37.     }
39.     phoneejb.remove(name);
41.     out.println("");
42.   }
43.   else {
44.     out.println("%ERROR : unrecognized command");
45.   }

Listing 3 : PhoneBook.java (initRecordStore method)

private final void initRecordStore() throws Exception {
    store = RecordStore.openRecordStore("PhoneBook",true);

    String s = sendToServer("http://localhost:8080/servlet/TestPhoneServlet");

    if (s != null && !s.equals("") && !s.startsWith("%ERROR")) {
      recordEnum = store.enumerateRecords(null, pbcomp, false);
      while (recordEnum.hasNextElement()) {
        int id = recordEnum.nextRecordId();


      String line = "";
      for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == '\n') {
          if (line.length() > 0) {
save(line.substring(0,MAX_NAME_LENGTH),line.substring(MAX_NAME_LENGTH), false);

          line = "";
        else {
          line += s.charAt(i);
      if (line.length() > 0) {
save(line.substring(0,MAX_NAME_LENGTH),line.substring(MAX_NAME_LENGTH), false);

    recordEnum = store.enumerateRecords(null, pbcomp, false);

Listing 4 : PhoneBook.java (save and erase methods)

  * save a name and phone number to the record store
  private final void save(String name, String phone, boolean sendToServer) 
  throws Exception {
    if (isEmpty(name)) {
      throw new Exception("No name entered");
    else if (isEmpty(phone)) {
      throw new Exception("No phone entered");
    else if (name.length() > MAX_NAME_LENGTH) {
      throw new Exception("Name too long, max=" + MAX_NAME_LENGTH);
    else {
      byte n[] = rpad(name,10,' ').getBytes();
      byte p[] = rpad(phone,0,' ').getBytes();
      byte rec[] = new byte[n.length + p.length];

      if (sendToServer) {
        String send = "http://localhost:8080/servlet/TestPhoneServlet?action=add&name=" 
+ rpad(replace(name,' ','+'),10,'+') + "&phone=" + phone;
        String rtn = sendToServer(send);

        if (rtn != null && !rtn.trim().equals("")) {
          throw new Exception("Server error : "+ rtn);


      n = null;
      p = null;
      rec = null;

  * erase the current record
  private final void erase(boolean sendToServer) throws Exception {
    if (currentRecordID < 0) {

    try {
      if (sendToServer) {
        String send =  "http://localhost:8080/servlet/TestPhoneServlet?action=remove&name=" 
+ rpad(replace(list.getName(),' ','+'),10,'+');
        String rtn = sendToServer(send);

        if (rtn != null && !rtn.trim().equals("")) {
          throw new Exception("Server error : "+ rtn);

      if (store.getNumRecords() < 1) {
        currentRecordID = -1;
    catch (InvalidRecordIDException irie) {
      throw new Exception("Invalid record");
    catch (Exception e) {
      throw new Exception("Unhandled.");



All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.