Welcome!

Cloud Expo Authors: Maureen O'Gara, Jim Kaskade, Elizabeth White, Jill Tummler Singer , Pat Romanski

Related Topics: Java

Java: Article

A Beginner's Guide to Writing Applications for the MID Profile

A Beginner's Guide to Writing Applications for the MID Profile

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.

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";
to
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:

http://localhost:8080/servlet/TestPhoneServlet
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!

More Stories By Jason R Briggs

As well as being a contributing editor for Java Developers Journal, Jason R Briggs is a Java programmer and Development Manager for a wireless technology company, based in Auckland, New Zealand.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Cloud Expo Breaking News
Cloud is a shift from the focus on underlying technology implementation to leveraging existing implementations and further building upon them. Cloud orchestration or a network of clouds is the wave of the future where these clouds can operate with elasticity, scalability, and efficiency. Effective service management is an important aspect of managing such networks. The transition to the cloud will enable the further aggregation of composite web services and enhanced business-to-business capabili...
The focus of Java EE 7 is on the cloud, and specifically it aims to bring Platform-as-a-Service providers and application developers together so that portable applications can be deployed on any cloud infrastructure and reap all its benefits in terms of scalability, elasticity, multitenancy, etc. The existing specifications in the platform such as JPA, Servlets, EJB, and others will be updated to meet these requirements. Java EE 7 continues the ease of development push that characterized prior ...
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and strategy sessions for you every day from June 11 through June 14 dealing with every nook and cranny of Cloud Computing and Big Data, but what of those who are presenting? Who are they, where do they work, what else h...
Wide and cheap availability of cloud-based media services is upon us. With the transformations these services are already bringing to the consumption of music, video and interactive media, change has likewise come to professional workflows. Documents in 2012 are read, written, collaborated on, and distributed anywhere an Internet-enabled device can reach – which is to say, everywhere. In his session at the 10th International Cloud Expo, Christopher Kenneally, Director of Business Development a...
CONGRATULATIONS to National Reconnaissance Office (NRO) CIO Jill T. Singer for being selected as one of the 10 winners of the first annual CloudNOW awards presented in Santa Clara, California earlier this week.

From the NRO Press Release:
"Considered one of the top women leaders in Federal IT, Ms. Singer was recognized for her innova...
I've been working on Enterprise Cloud Strategy and in the course of this work identified some interesting and non-obvious opportunities in the Cloud. One solution I’ve examined is the well-crafted solution that is enStratus. enStratus has built a SaaS Cloud Management / Governance product focused on providing critical management, monitoring, governance capabilities tailored to the needs of the Global 2000 market, rather than the startup market. As I have worked with a current Fortune 500 clie...
With Cloud Expo 2012 New York (10th Cloud Expo) now under four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and strategy sessions for you every day from June 11 through June 14 dealing with every nook and cranny of Cloud Computing and Big Data, but what of those who are presenting? Who are they, where do they work, what e...
2011 was a year of rapid adoption for public and private cloud services. Instant and on-demand server provisioning was the driving force behind the massive growth. On top, cloud server templates and script automation simplified application installation for simple and pre-defined application stacks, but have not targeted more complex enterprise application environments. In his session at the 10th International Cloud Expo, John Yung, CEO of Appcara, will discuss how 2012 will be the year for app...
"Having been in the IT field for many years, I believe the cloud computing chapter in the industry is an exciting one and I am proud to be a part of it," said National Reconaissance Office (NRO) Chief Information Officer Jill T. Singer Tuesday, as it was announced that she was one of 10 winners of the 2012 CloudNOW "Top Ten Women in Cloud" Awards.
As more enterprises are adopting clouds, the nature of cloud computing is changing. Previously, clouds were used to test applications or for non-mission critical applications. Today, enterprises are using clouds for cost-saving advantages and launching more mission critical applications that have defined performance needs. In his session at the 10th International Cloud Expo, Eric Shepcaro, CEO and Chairman of the Board of Telx, will discuss how distributed computing has many advantages. It wou...