O'Reilly    
 Published on O'Reilly (http://www.oreilly.com/)
 http://java.oreilly.com/news/j2me_0201.html
 See this if you're having trouble printing code examples


The Big Small Platform

by Jonathan Knudsen
02/28/2001

The Java platform is rapidly expanding above and below the desktop. On the larger side of things, technologies like servlets, Enterprise JavaBeans, and JDBC (Java Database Connectivity) are taking enterprise computing to a new level. On the small device front, Java is maturing rapidly. In this article, Jonathan Knudsen explores the Connected Limited Device Configuration (CLDC) of Java 2, Micro Edition (J2ME) and explains how all the acronyms fit together. He'll also explain how networking works in the new javax.microedition.io package.

Java 2, Micro Edition (J2ME) is a version of the Java 2 platform targeted at small devices like mobile phones and PDAs. Up until now, these devices were usually programmed in C, C++, or assembly language. Java is a good alternative for two reasons:

  1. Java is a good choice for portable code. You might, for example, want to easily and safely install or update software in your mobile phone. Java's talents in the arena of downloadable code are widely acclaimed; as a platform, Java is well-known for its ability to run untrusted code safely. As you'll see later in this article, however, the constraints of small devices mean that most of this benefit is erased in J2ME.

  2. Java's Write Once, Run Anywhere promise holds true, to a degree, in the J2ME world. You shouldn't have to port your application to dozens of different mobile-phone platforms, or at least you shouldn't have to port much of it.

Configurations and the CLDC

What is J2ME, exactly? It's simply the Java 2 platform for small devices, where "small device" means anything from a mobile phone up to a television set-top box. Because there are so many different kinds of small devices, Sun has split J2ME into a collection of Configurations and Profiles.

A J2ME Configuration defines a version of Java suitable for a class of devices, such as set-top boxes. All this means, really, is that a Configuration specifies which parts of the standard Java platform will be used--which features are supported, which features are thrown overboard. A Configuration is basically a list of which paragraphs of the Java Virtual Machine Specification and the Java Language Specification do not apply to the Configuration.

One important Configuration is the Connected Limited Device Configuration. The CLDC specifies a version of Java for small devices that have the ability to connect intermittently to some network, possibly the Internet. Specifically, the CLDC is targeted at devices with 160Kb to 512Kb of memory available for the Java platform. If you've ever watched a Java application gulp down megabytes of memory on your desktop computer, you'll appreciate the challenges Sun Microsystems is facing with J2ME.

The CLDC specification is not bad reading, for a specification, and it's only about 60 pages. If you're interested in the small device space and Java, I recommend taking a look through this document.


Jonathan Knudsen will speak about J2ME and XML at the O'Reilly Conference on Enterprise Java, March 26-29, 2001, in Santa Clara, California.


What It Is and What It Is Not

The CLDC is defined by starting with the Java Virtual Machine Specification and the Java Language Specification and taking stuff out. For example, the CLDC says it won't support any floating-point variables or operations because most of the target devices don't have floating-point support. There are a few other omissions: no object finalization, no native methods, no reflection, and no application-defined classloaders.

The CLDC also specifies a subset of the core APIs that will be available. This means that your application running on a CLDC-compliant device can rely on a well-defined subset of the java.lang, java.io, and java.util packages. Furthermore, the CLDC also defines a new package, javax.microedition.io, which includes some generalized interfaces for network communications. I'll talk more about this later in this article.

Profiles

The CLDC does not specify anything about application deployment or user interface. These things are left to a Profile. A Profile is a lot like a Configuration, only more specific. A particular profile might start with a Configuration as a building block, then specify user-interface APIs and development tools and procedures. For instance, it would make sense to define a Palm OS Profile based on the CLDC by adding user interface APIs and development tools.

One Profile based on the CLDC has already been finished: the Mobile Information Device Profile (MIDP). Although a port of MIDP to Palm OS is planned for the future, this article (and the one that follows next week) are based on the CLDC 1.0 release, which includes a working implementation for Palm OS.

Classloading Conundrum

I said before that one of the reasons you might want to use Java is that it is good at portable code. In a standard desktop Web browser, you can download Java classes from anywhere in the world and run them. Two layers of technology protect you from harm: the bytecode verifier makes sure classes follow certain rules, and a security sandbox prevents downloaded code from erasing your hard disk or perpetrating other nastiness.

Unfortunately, the constraints of small devices means that you cannot use dynamically loaded classes inside a CLDC application. Applications cannot define their own classloaders, for one thing. Furthermore, the bytecode verifier is too heavy to fit in the CLDC. The CLDC splits class verification into two steps: on a desktop computer or a server, a preverify step is performed to run checks on classes and leaves them in a partially verified state. Then, on the actual mobile phone or PDA, a lightweight verification step is performed.

If you're paying attention, you'll notice that the CLDC doesn't allow dynamic classloading, which is one of the reasons you might have wanted to use Java in the first place. Sure, you can install and remove Java applications on your small device, but that kind of thing is handled outside the Java platform using device-specific controls. However, a CLDC application is still a step up from using binary executables, for security reasons.

Security

The desktop version of Java (Java 2, Standard Edition, or J2SE) has sophisticated security mechanisms to allow you to run code you don't really trust without fearing for the health and safety of your computer and your data. It would be nice if the same mechanisms could be used in J2ME, but they are too large to fit in a small device.

Suppose you have a mobile phone running J2ME. One day you download an application that's supposed to show a real-time stock ticker in the phone's tiny screen. Unfortunately, the stock ticker turns out to be a Trojan horse. Instead of showing a ticker, it empties your telephone list and transmits all the numbers to your competitor's company.

The CLDC doesn't offer a way around this type of problem. This means that external systems will need to be set up so that you can obtain new applications for your mobile phone in a safe way.

The only security the CLDC really offers is the assurance that a Java application will not be able to mess up other applications or the device itself.

Let's Play

The actual software that we'll examine is a Palm OS implementation of the CLDC. It's based around a tiny Java Virtual Machine called the KVM. I used the 1.0 version of this software, available from Sun. If you follow the links to download the software, you'll have to go through a free registration with Sun. Download both the base CLDC file as well as the Palm overlay file. Unpack the CLDC file first, then unzip the Palm overlay file into the same directory.

This CLDC implementation should run on any Palm OS device, including the Palm III, Palm V, Palm VII, and Handspring Visor. Additionally, it runs on the Palm OS Emulator (POSE).

The first thing you'll need to do is install the KVM itself. Install both the KVM.prc and KVMutil.prc files from the bin directory of the CLDC installation. (These files come from the Palm overlay download, which you should have unpacked into the CLDC base directory.)

Cross Compiling

Building applications for the Palm OS implementation of the CLDC is a four-step process.

  1. First, write the Java source code as usual. Make sure you use only API methods from the CLDC and whatever Profile you're using. In our case, the Palm OS CLDC implementation includes a package of user-interface classes, com.sun.kjava.

  2. Compile the source code. This is a little tricky. Your desktop machine has J2SE installed, but you're trying to produce class files for J2ME. The trick is the java compiler's -bootclasspath option, which allows you to specify the core classes you wish to compile against. This is a subtle example of cross compiling--in this case, we're using J2SE to build J2ME classes.

  3. Perform part of the bytecode verification of the class file using the preverify tool shipped with the Palm OS CLDC implementation.

  4. Package the class files into a format acceptable to your small device. Here, we'll be using a tool called MakePalmApp to create a Palm OS executable (a .prc file) from a Java class file. You'll have to build the MakePalmApp tool first, oddly enough. To do this, change directories to the tools\palm\src directory underneath the base CLDC directory. Then type the following:

javac palm\database\*.java

Steps 2 and 3 are delicate enough that you should probably create a shell script to automate them. Once you go through the pain of figuring out all the command-line options, you probably won't want to do it again. On Windows, I use a batch file for this purpose. It looks like this:

@setlocal
@set cldc=\j2me_cldc
@set lib=%cldc%\bin\api\classes
@set palm_lib=%cldc%\tools\palm\src

javac -bootclasspath %lib% -classpath .;%lib% %1.java
%cldc%\bin\preverify -classpath .;%lib% -d . %1
java -classpath .;%palm_lib% palm.database.MakePalmApp -bootclasspath \
     %lib% -o %cldc%\bin\%1.prc -networking %1

@endlocal

You should, of course, adjust this based on the location of your base CLDC directory.

The javac line compiles the source code and creates a class file. It expects to find the source code in the current directory and places compiled classes in the current directory. Notice how the -bootclasspath option is used to compile the source code against the CLDC classes in bin\api\classes.

The next line uses the preverify tool to perform the first steps of bytecode verification. The modified class file is stored back in the current directory, overwriting the class file we just generated with javac.

The java line uses the MakePalmApp utility to convert the class file into a Palm executable (.prc). The -bootclasspath option tells MakePalmApp where to find the CLDC classes we want to use. The generated .prc file is placed in the bin subdirectory. The -networking flag is very important; without it, any applications we build will not be able to make network connections.

Reaching the Network

Let's look at a simple networking example. All network access in the CLDC is based around a set of interfaces in the javax.microedition.io package. The Connection interface is the grandpappy of them all--a series of subinterfaces define more specific functionality. For example, there are InputConnection and OutputConnection subinterfaces, which both inherit from Connection and provide methods for accessing input and output streams. A further specialization, StreamConnection, extends both InputConnection and OutputConnection. It's the interface we're interested in because it can be used to represent a network socket connection. The following figure shows the relationship between the different Connection interfaces.

Image 1

A single class, javax.microedition.io.Connector, provides factory methods for obtaining Connection objects. You feed a URL-style connection string to one of Connector's factory methods and it spits back a Connection object. The CLDC specification gives all kinds of possible connection strings, like HTTP and FTP URLs, as well as less standard "socket:" and "comm:" strings, representing network sockets and serial communications, respectively.

Exactly which types of connections are supported is left to the Profile. In this case, we're not really working with a Profile, just a Palm OS implementation of the CLDC. The supported connection strings are:

socket://host:port

This string opens a standard TCP/IP socket to the named host and port number. For example, using "socket://www.oreilly.com:80" would make a connection to O'Reilly's Web server. The returned Connection object can be cast to a StreamConnection.

datagram://host:port

Use this type of string for a UDP (User Datagram Protocol) datagram connection to the named host and port number.

comm:0

This string opens a connection with the Palm's serial port.

The connection types that didn't work are "http," "ftp," "file," and "nfs." But these were only listed as possibilities in the CLDC specification.

In the world of the CLDC, then, making a network connection looks like this:

String url = "socket://www.oreilly.com:80";
StreamConnection s = (StreamConnection)Connector.open(url);
OutputStream out = s.openOutputStream();
InputStream in = s.openInputStream();

Just Wait Until Next Time

By now you should have enough information to get started with J2ME on Palm OS. You can install the CLDC on your Palm OS device (or perhaps the emulator) and compile and run your own applications. In my next article, I'll present a working networked chat client application written with the CLDC.

Conclusion

The CLDC is fairly stable technology. Already, one Profile (the Mobile Information Device Profile, or MIDP) has been built on the CLDC. I'm expecting J2ME to be a compelling platform. Imagine writing a networked application and having the client-side run, without modification, on a dozen different brands of mobile phone! That is powerful medicine indeed.


Jonathan Knudsen is the author of an upcoming book, Mobile Java, about the J2ME Mobile Information Device Profile. Currently, he is the Director of Courseware Development for LearningPatterns.com. Prior to that he was an author and editor at O'Reilly & Associates. His books include The Unofficial Guide to LEGO MINDSTORMS Robots, Java 2D Graphics, and Learning Java. While at O'Reilly he also wrote a monthly column called Bite-Size Java. Jonathan works at his home in Princeton, New Jersey, with his wife, one cat, and four children.

Copyright © 2007 O'Reilly Media, Inc.