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

Jini provides simple and reliable access to services over any network, independent of platform, protocol, or application technology. Enterprises can use Jini to develop a resilient service-oriented architecture that can be accessed from a broad range of clients.

Java 2 Micro Edition (J2ME) enables developers to build portable rich-client solutions that can operate in either connected or disconnected modes. The combination of J2ME-enabled devices interacting with enterprise systems through Jini services provides a flexible architecture for building highly reliable, end-to-end mobile solutions.

However, for any client to directly access and/or run Jini services, it must be capable of dynamically downloading and executing Java classes and be able to participate in Jini Discovery and Join protocols. Currently, many J2ME-enabled devices with limited resources don't have this capability and can't directly participate in a Jini network. This article provides an overview of the technologies, and, with the help of an example, illustrates how to overcome the limitations of J2ME to develop an effective mobile architecture based on J2ME and Jini.

Jini Primer
From the official Jini architecture specification, wwws.sun.com/software/jini/specs, the Jini system is defined as:

...a distributed system based on the idea of federating groups of users and the resources required by those users. The focus of the system is to make the network a more dynamic entity that better reflects the dynamic nature of the workgroup by enabling the ability to add and delete services flexibly.

A Jini system uses the network as a foundation to enable service discovery and service execution. Traditional systems attempt to mask the appearance of the network; in contrast, Jini uses the dynamic, flexible nature of the network to form communities and register, discover, and invoke services. Unlike traditional systems, Jini is founded on the assumptions that networks are unreliable, change frequently, and should not require substantial maintenance by an administrator.

To address the assumption that networks are unreliable, Jini systems are self-healing. Jini services repair themselves using the concept of leasing. Leasing ensures that Jini services are automatically removed from the community after a specified time period, without the need for administrator intervention. The network topology can change, but Jini will continue to work without the need to update the URLs referenced in services, change properties files, or perform manual administration. Jini services adapt to such changes automatically. Communication with a Jini service occurs through service proxies that are downloaded to the client machine automatically without administrator involvement, a practice that is normally required in traditional architectures.

Jini Architecture
The Jini architecture (see Figure 1) is comprised of the following elements:

Figure 1

Jini Service
A Jini service is an entity that can be a hardware device or a software component that provides functions like printing a report, looking up a stock quote, or executing an algorithm. Applications and other Jini services can use a Java interface and a Java proxy class to access a Jini service. The Java interface provides the definition of the methods that are available from the Jini service. The Java proxy provides the communication channel between the client and the actual service. Jini services are registered with the lookup service and are capable of being invoked through their public interface, which is defined via a Java remote interface. In most cases, the underlying system that allows Jini services to communicate is RMI. A Jini service may also use protocols such as SOAP, XML/HTTP, or CORBA.

Lookup Service
The lookup service, which is a Jini service, keeps track of the Jini services and provides proxies to communicate with the services. Sun provides a lookup service called Reggie (used for developing this example) as part of the Jini development kit.

Jini Client
The Jini client is any software that requests the proxy from the lookup service in order to invoke the Jini service.

RestaurantFinder Application
Now that you have a good understanding of Jini and J2ME, let's move on to an example application that uses Jini and J2ME to provide a valuable service to mobile users. We'll use this example to show you how to develop a complete Jini/J2ME solution that overcomes the limitations of MIDP.

DineOut Corporation has a comprehensive database of restaurant listings, reviews, and ratings in different cities in the continental United States. DineOut wants to build a system called RestaurantFinder that enables DineOut's subscribers to access these listings using their J2ME-capable cellphones. The software architecture for the RestaurantFinder system is shown in Figure 2.

Figure 2

The core components of the RestaurantFinder system are as follows.

RestaurantFinder Jini Service
The RestaurantFinder Jini service provides the ability to search for restaurant listings by city and cuisine. The definition for this service is given by the interface rf.service.RestaurantFinder (see Listing 1) and the Java proxy for this service is provided by the class rf.service.RestaurantFinderImpl (see Listing 2). Using Jini to develop the RestaurantFinder service has the following benefits:
1.   Provides a fault tolerant infrastructure by hosting multiple instances of the RestaurantFinder service on different nodes in the network. Thus, if there's a failure of one node, users will not lose access to the service.
2.   Enables an administrator to add, remove, and move instances of the RestaurantFinder service from the network without affecting the overall operation of the system.

Jini Lookup Service
The lookup service manages a persistent store of service registrations. The J2ME client uses the Jini lookup service to find and locate the RestaurantFinder Jini service. Using the lookup service decouples the J2ME client from the actual service instance, enabling the Jini server to use multiple service instances to handle requests from the client.

J2ME Client
The MIDP client shown in Figure 3 will access the RestaurantFinder Jini service.

Figure 3

A Jini client developed using the J2ME technology has the following advantages over a traditional thin-client WAP-enabled cellphone:
1.   It provides a rich user interface to DineOut's subscribers by supporting features such as on-device validation (as opposed to server-side validation) and persistence to save restaurant listings. Thus, users get a more responsive and easier-to-use solution.
2.   The client can operate in connected or disconnected mode. Although users won't have access to all capabilities when operating in disconnected mode, they can at least browse through saved listings, and could potentially also perform searches if restaurant data were persisted to the device.

J2ME Client Proxy
A MIDP device runs on the Connected Limited Device Configuration (CLDC). The CLDC doesn't allow the user to load classes at runtime. This prevents the MIDP client from acting like a regular Jini client, which has the ability to download and execute the service proxy classes. To work around this restriction, the RestaurantFinder service uses a Java servlet given by class rf.servlet.ControllerServlet (see Listing 3) as a Jini proxy. This proxy communicates with the RestaurantFinder Jini service on behalf of the MIDP client. The communication between the servlet and the MIDP client takes place over HTTP as shown in Figure 2.

Developing the RestaurantFinder System
Now that we're familiar with RestaurantFinder's architecture, let's have a closer look at what's involved in developing the RestaurantFinder system.

Developing the Jini Service
The first step in developing the RestaurantFinder service is defining the service interface rf.service.RestaurantFinder (see Listing 1). This interface defines the method getRestaurants, which takes a city name and cuisine as an argument, and returns an array of rf.service.Restaurant objects. This interface defines the contract between the Jini client and the Jini service.

Next, we develop the Java proxy class rf.service.RestaurantFinderImpl (see Listing 2) that implements the RestaurantFinder interface. During service registration, this Java proxy is uploaded from the RestaurantFinder service (see Listing 4) to the lookup service as shown in Figure 4. The proxy shields the client from the actual communication with the Jini service. When a client looks up a service, the lookup service returns the proxy object for the service. Any classes required by the proxy are dynamically loaded over the network. In our example, the RestaurantFinder service is executed locally as part of the Jini client's (J2ME Client Proxy in our case) virtual machine. However, the Java proxy could easily be changed to communicate using RMI with a remote RestaurantFinder service.

Finally, the RestaurantFinder service is registered with the Jini lookup service (Reggie). The class ServiceRegistrationClient (see Listing 4) performs this operation.

Consider the following lines of code

ldm = new LookupDiscoveryManager(new String[]
{"iguanas"}, null, null);
jm = new JoinManager(new rf.service.RestaurantFinderImpl(),
null , new ServiceRegistrationListener(),
ldm, null);

The first line creates an instance of LookupDiscoveryManager to locate the group "iguanas". This is a utility class provided by the Jini reference implementation for discovering groups that a service is interested in joining. Groups provide a partition mechanism for the physical Jini network. A Jini service can belong to one or more groups. A Jini client has to join a group before accessing the services of the group. The RestaurantFinder service will join the "iguanas" group. This group is created and serviced by Reggie. The names of the group(s) to be serviced by a Reggie are provided as command-line arguments while starting Reggie as shown below.

java -Djava.security.policy=%JINIHOME%\policy\policy.all -jar
%JINIHOME%\lib\reggie.jar http://%DOWNLOADHOST%/reggie-dl.jar
%JINIHOME%\policy\policy.all %JINITEMP%\reggie.log iguanas
-Dnet.jini.discovery.interface=%ADAPTERIP%

The next line creates an instance of JoinManager. This is another utility class that provides a convenient way to register a Jini service with Reggie (lookup service). In our example, an instance of the JoinManager is instantiated with an instance of RestaurantFinderImpl proxy, rf.service.ServiceRegistrationListener, and LookupDiscoveryManager. The JoinManager will register the RestaurantFinder service and upload the Java proxy for the server to the lookup service.

Developing the J2ME Client Proxy
Listing 3 shows the source code for the servlet rf.servlet.ControllerServlet that acts as a proxy for the J2ME client. Upon initialization, this servlet locates the RestaurantFinder service using the lookup service and dynamically loads the Java proxy from the Jini lookup service (see Figure 4).

Figure 4

The doPost method of the servlet decodes the request from a J2ME client, invokes the RestaurantFinder service, and returns the results back to the J2ME client. Note that the ControllerServlet only accesses the Jini service through the interface rf.service.RestaurantFinder, thus decoupling the servlet from the implementation of the Jini service.

Developing the J2ME Client
The last piece of the puzzle is the J2ME client, which is developed as a MIDlet (see Listing 5) called rf.midlet.RestaurantFinderMIDlet. MIDlets are classes that extend the class javax.microedition.midlet.MIDlet and run on J2ME devices that support the MIDP profile. The execution and the life cycle of a MIDlet are controlled by special software on J2ME devices, called Application Management Software. MIDlets are developed on regular desktops and then deployed to smaller devices. The example in this article was developed using the MIDP reference implementation from Sun.

Execution of the RestaurantFinderMIDlet starts with the invocation of the startAPP method by the Application Management Software. This method initializes the J2ME client and sets up a search form as the current display for the application (see Figure 3). Using this form the user can select the name of the city and the type of cuisine for his or her restaurant search criteria. After selecting the criteria, the user can click on the "find" button to perform a search for restaurants.

Clicking the "find" button triggers the command findCommand. In J2ME, a command is something a user can use to interact with the client, e.g., clicking on the "find" button. In response to the command, the MIDlet opens up a connection to the J2ME Proxy Servlet and performs an HTTP GET as shown in method getResult. The J2ME Proxy Servlet (rf.servlet.ControllerServlet) returns a list of restaurants in the form of an encoded string. We've used an encoded string to keep the application simple; however, in real systems XML can be used for exchanging information between the J2ME client and the servlet.

On receiving the results of the search query, the list of restaurants is displayed to the user (see Figure 5).

figure 5

The Road Ahead
Using a servlet as a proxy between the J2ME client and the Jini service is a step in the right direction for integrating J2ME clients in a Jini network. However, to fully enable J2ME clients as "true" Jini citizens, we can use the surrogate architecture (http://surrogate.jini.org). This architecture enables the J2ME clients to be part of the Jini network using a surrogate executing within a surrogate host. The surrogate knows of the device's capabilities and operates within the Jini federation. Services in the federation may use the surrogate just as they would use any other service in the federation. The IP Interconnect Adapter specification identifies the requirements of how the surrogate communicates with the device. This surrogate architecture combined with J2ME enhancements, like the MIDP 2.0 push API, can lead to the development of rich wireless clients that can not only leverage the Jini infrastructure but can also be managed as Jini services. (At the time this article was written, the specification for the surrogate architecture and the Interconnect adapters was not yet fully defined.)

Conclusion
J2ME and Jini can be used to develop a highly portable, resilient service-oriented architecture that meets the needs of mobile users. By providing some simple workarounds to current limitations with J2ME, it's possible to build these powerful solutions today.

References

  • Edwards, W. K. (2001). Core Jini (2nd Edition). Prentice Hall PTR.
  • Edwards, W. K., and Rodden, T. (2001). Jini Example by Example. Prentice Hall PTR.
  • http://java.sun.com/j2me/
  • Knudsen, J. (2003). Wireless Java: Developing with J2ME. APress.

    About The Authors
    Ron Dearing is a senior software engineer at Cysive, Inc., based in Reston, VA. He has worked in the software industry for over six years, and is currently working in the product development group on the Cymbio Interaction Server. Ron has a BS in computer science from North Carolina A&T. rdearing@cysive.com

    Nikhil Patil has worked in the software industry for over six years, and is a product manager at Cysive, Inc., where he works on developing the strategic vision for the Cymbio Interaction Server. A Sun Certified Java Developer, Nikhil has an MS in industrial engineering and a BE in mechanical engineering.
    npatil@cysive.com

    "J2ME Clients with Jini Services"
    Vol. 8, Issue 6, p. 70

    	
    
    
    
    Listing 1
    
    package rf.service;
    
    import java.rmi.RemoteException;
    
    /**
     * Interface for the RestaurantFinder Jini Service. Jini clients using the RestaurantFinder 
     * service will be program against this interface.
     * 
     * @author Nikhil Patil
     */
    public interface RestaurantFinder
    {
        /**
         * Returns an array of Restaurants based on the name of the city and type of cuisine.
         */
        public Restaurant[] getRestaurants(String city, String cuisine) throws RemoteException;
    }
    
    Listing 2
    
    package rf.service;
    
    import java.rmi.RemoteException;
    
    /**
     * Java proxy for the RestaurantFinder Jini Service.
     This class is uploaded to the Jini Lookup Service
     * during registration by <code>ServiceRegistrationClient</code>.
     Jini clients using this service, download
     * this proxy and use to communicate with the Jini Service.
     This Java proxy will execute the Jini
     * Service in the Jini client's VM.
     * 
     * @author Nikhil Patil
     */
    public class RestaurantFinderImpl implements RestaurantFinder, java.io.Serializable
    {
        /**
         * Returns an array of Restaurants based on the name of the city and type of cuisine.
         */
    	public Restaurant[] getRestaurants(String city, String cuisine)
    	throws RemoteException
    	{
    		if ("chicago".equalsIgnoreCase(city))
    		{
    			if ("italian".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Joes Diner", "Chicago", "Italian", "772-123-4560"),
    	new Restaurant("Magianos", "Chicago", "Italian", "772-123-4560"),
    	new Restaurant("Magianos", "Chicago", "Italian", "772-123-4560")};
    			}
    			else if ("chinese".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Mings", "Chicago", "Chinese", "772-123-4560"),
    	new Restaurant("China Garden", "Chicago", "Chinese", "772-123-4560"),
    	new Restaurant("China Palace", "Chicago", "Chinese", "772-123-4560")};
    			}
    			else if ("american".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Mortons", "Chicago", "American", "772-123-4560"),
    	new Restaurant("McCormiks", "Chicago", "American", "772-123-4560"),
    	new Restaurant("Rubys", "Chicago", "American", "772-123-4560")};
    			}
    			else
    			{
    				return new Restaurant[0];
    			}
    		}
    		else if ("Atlanta".equalsIgnoreCase(city))
    		{
    			if ("italian".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Saraceno", "Atlanta", "Italian", "111-222-3333"),
    	new Restaurant("Paolos", "Atlanta", "Italian", "111-222-3333"),
    	new Restaurant("Siciliana", "Atlanta", "Italian", "111-222-3333")};
    			}
    			else if ("chinese".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Hunan", "Atlanta", "Chinese", "772-123-4560"),
    	new Restaurant("Canton", "Atlanta", "Chinese", "772-123-4560"),
    	new Restaurant("Fan Yu", "Atlanta", "Chinese", "772-123-4560")};
    			}
    			else if ("american".equalsIgnoreCase(cuisine))
    			{
    				return new Restaurant[] {
    	new Restaurant("Plaza", "Atlanta", "American", "772-123-4560"),
    	new Restaurant("Atlanta Grill", "Atlanta", "American", "772-123-4560"),
    	new Restaurant("Marks", "Atlanta", "American", "772-123-4560")};
    			}
    			else
    			{
    				return new Restaurant[0];
    			}
    		}
    		else
    		{
    			return new Restaurant[0];
    		}
    	}
    }
    
    Listing 3
    
    package rf.servlet;
    
    import java.io.IOException;
    import java.rmi.RemoteException;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import net.jini.core.lookup.ServiceMatches;
    import net.jini.core.lookup.ServiceRegistrar;
    import net.jini.core.lookup.ServiceTemplate;
    import net.jini.discovery.DiscoveryEvent;
    import net.jini.discovery.DiscoveryListener;
    import net.jini.discovery.LookupDiscovery;
    import rf.service.Restaurant;
    import rf.service.RestaurantFinder;
    
    /**
     * Proxy Servlet for managing communication between the J2ME client
     and the Restaurant Finder
     * Jini service. 
     * 
     * @author Nikhil Patil
     */
    public class ControllerServlet extends HttpServlet implements DiscoveryListener
    {
    	private ServiceRegistrar[] registrars;
    	static final int MAX = 10;
    	private LookupDiscovery discover = null;
    	private RestaurantFinder finder = null;
    
    	/**
    	 * Initializes the servlet and locates the RestaurantFinder Jini service.
    	 */
    	public void init(ServletConfig servletConfig) throws ServletException
    	{
    		super.init(servletConfig);
    		try
    		{
                System.out.println("Locating Jini Service");         
                // Search for the group "iguanas". On discovery of this group the method
                // <code>discovered</code> will be invoked by the class
    			<code>LookupDiscovery</code>.
    		discover = null;
    		discover = new LookupDiscovery(LookupDiscovery.NO_GROUPS);
    		discover.addDiscoveryListener(this);
    		discover.setGroups(new String[] { "iguanas" });
    		}
    		catch (Exception e)
    		{
    			throw new ServletException("Error in locating Service:", e);
    		}
    	}
    
    	/**
    	 * Transfers control to the doPost method.
    	 */
    	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
    	throws ServletException, IOException
    	{
    		doPost(arg0, arg1);
    	}
    
    	/**
    	 * Services a request from the J2ME client.
    	 This method will use the Jini Service on behalf
         * of the J2ME client to conduct a restaurant search
    	 and return the results back to the client.
    	 */
    	protected void doPost(HttpServletRequest request,
    	HttpServletResponse response)
    	throws ServletException, IOException
    	{
            System.out.println("Finding Restaurants..");
            if (finder == null)
            {
    	response.getWriter().println("Restaurant Finder Service Unavailable");
            }
            else
            {
                // Extract the city and the cuisine type.
                String city = request.getParameter("city");
                String cuisine = request.getParameter("cuisine");
                // Find the list of restaurants by invoking the Jini Service.
                Restaurant[] restaurants = finder.getRestaurants(city, cuisine);
                // Construct an output message for the J2ME client.
                StringBuffer buffer = new StringBuffer();
                for (int i = 0; i < restaurants.length; i++)
                {
                    Restaurant restaurant = restaurants[i];
    buffer.append("Name - " + restaurant.getName()+
    ":Phone-"+restaurant.getPhone()+";");
                }
                if (buffer.length() == 0)
                {
                    buffer.append("No Restaurants Found");
                }
                response.getWriter().println(buffer.toString());
            }
    	}
    
        /**
         * Invoked when the group "iguanas" is discovered by the utility class
    	  <code>LookupDisovery</code>.
         * This method will locate the RestaurantFinder service in the group "iguanas".
         * 
         * @see rf.service.RestaurantFinder
         */
    	public synchronized void discovered(DiscoveryEvent evt)
    	{
    		try
    		{
                // Get a list of service registrars.
    			registrars = evt.getRegistrars();
                // Find the RestaurantFinder service.
    			performLookup(registrars);
    		}
    		catch (Exception ex)
    		{
    			ex.printStackTrace();
    		}
    
    	}
    
    	public void discarded(DiscoveryEvent evt)
    	{
    	}
    
        /**
         * Searches for the RestaurantFinder service.
         */
        private void performLookup(ServiceRegistrar[]
    	registrars) throws RemoteException
    	{
    		ServiceMatches matches = null;
    		String[] groups;
    		String msg = null;
    		if (registrars.length > 0)
    		{
                // Conduct the search based on the interface definition.
    			All jini services can be discovered
                // by the interface they support.
    			Class[] myClassType = { RestaurantFinder.class };
    			matches = registrars[0].lookup(new ServiceTemplate
    			(null, myClassType, null), MAX);
                if (matches.items.length > 0)
    			{
                   finder = (RestaurantFinder) matches.items[0].service;
                   finder.getRestaurants(null, null);
                    System.out.println("Restaurant Finder Service Intialized...");
    			}
                else
                {
                    System.out.println("No match found");
                }
    		}
    		else
    		{
    			System.out.println("No Service Found");
    
    		} 
    	}
    }
    
    Listing 4
    
    import net.jini.lookup.JoinManager;
    import net.jini.discovery.*;
    import java.rmi.RMISecurityManager;
    
    /**
     * Driver for registering the RestaurantFinder service with the Jini lookup
     * service.
     *
     * @author Nikhil Patil
     */
    public class ServiceRegistrationClient
    {
    	LookupDiscoveryManager ldm = null;
    	JoinManager jm = null;
    
    	public static void main(String args[])
    	{
    		try
    		{
    			// Set the RMI Security Manager.
    			if (System.getSecurityManager() == null)
    			{
    			System.setSecurityManager(new RMISecurityManager());
    			}
    			// Register the service.
    		ServiceRegistrationClient myApp = new ServiceRegistrationClient();
    			myApp.register();
    			synchronized (myApp)
    			{
    				myApp.wait(0);
    			}
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    			System.exit(1);
    		}
    	}
    
        /**
         * Registers the RestaurantFinder service with the Jini Lookup Service.
         */
    	public void register() throws Exception
    	{
    		String[] groupsToDiscover = LookupDiscovery.NO_GROUPS;
    
            // Discover the group "iguanas".
    		ldm = new LookupDiscoveryManager(new String[]
    		{ "iguanas" }, null, null);
            // Join the group "iguanas".
    		jm = new JoinManager
    		(new rf.service.RestaurantFinderImpl(),
    				             null,
    				             new ServiceRegistrationListener(),
    				             ldm,
    				             null);
    	}
    }
    
    Listing 5
    
    package rf.midlet;
    
    import java.io.InputStream;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeException;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    
    /**
     * J2ME client for finding restaurant listings.
     * 
     * @author Nikhil Patil
     * @since 3.1
     */
    public class RestaurantFinderMIDlet extends MIDlet implements CommandListener
    {
    	private String url = "http://localhost:8080/restaurantfinder/rf";
    	private ChoiceGroup cityList;
    	private ChoiceGroup cuisineList;
    	private Form form;
    	private Command exitCommand;
    	private Command findCommand;
    	private Command backCommand;
    	private TextBox result;
    
        /**
         * Intializes the MIDlet.
         */
    	protected void startApp() throws MIDletStateChangeException
    	{
    		initializeComponents();
    		Display.getDisplay(this).setCurrent(form);
    	}
    
    	protected void pauseApp()
    	{
    	}
    
    	protected void destroyApp(boolean arg0) throws MIDletStateChangeException
    	{
    	}
    
    	private void initializeComponents()
    	{
            // Populate the list of cities.
    		cityList =
    			new ChoiceGroup("City: ", List.POPUP, new String[]
    			{ "atlanta", "chicago" }, null);
            // Populate the cusine types.
    		cuisineList =
    			new ChoiceGroup(
    				"Cuisine: ",
    				List.POPUP,
    				new String[] { "american", "chinese", "italian" },
    				null);
            // Initialize the commands.
    		exitCommand = new Command("Exit", Command.EXIT, 0);
    		findCommand = new Command("Find", Command.SCREEN, 0);
    		backCommand = new Command("Back", Command.BACK, 0);
            // Build the search form.
    		form = new Form("Search");
    		form.append(cityList);
    		form.append(cuisineList);
    		form.addCommand(exitCommand);
    		form.addCommand(findCommand);
    		form.setCommandListener(this);
            // Intialize the result screen.
    		result = new TextBox("Results", "", 250, TextField.ANY |
    		TextField.UNEDITABLE);
    		result.addCommand(backCommand);
    		result.setCommandListener(this);
    	}
    
        /**
         * Invoked in response to a user initiated action.
    	 A user can click a button to exit
         * the application (Exit), or search for restaurant
    	 listings ("Find") or go back from
         * the results screen(Back).
         */
    	public void commandAction(Command c, Displayable arg1)
    	{
    		if (c == exitCommand)
    		{
    			notifyDestroyed();
    		}
    		if (c == findCommand)
    		{
                // Search for restaurant listings.
    	result.setString("Finding Restaurants ...");
    	Display.getDisplay(this).setCurrent(result);
    	String city = cityList.getString(cityList.getSelectedIndex());
    	String cuisine = cuisineList.getString(cuisineList.getSelectedIndex());
    	String urlString = url + "?city=" + city + "&cuisine=" + cuisine;
    	String resultString = getResult(urlString);
    	result.setString(resultString);
    
    		}
    		if (c == backCommand)
    		{
    			Display.getDisplay(this).setCurrent(form);
    		}
    	}
    
    	private String getResult(String url)
    	{
    		HttpConnection c = null;
    		InputStream is = null;
    		int rc;
    
    		try
    		{
                // Make an HTTP GET request to the Proxy Servlet.
    			c = (HttpConnection) Connector.open(url);
                // Check to ensure that the request was successful.
    			rc = c.getResponseCode();
    			if (rc != HttpConnection.HTTP_OK)
    			{
    				return "Error: HTTP response code: " + rc;
    			}
                // Read the response and build a list of restaurants to be displayed
                // to the user.
    			is = c.openInputStream();			
    			int ch;
    			StringBuffer buffer = new StringBuffer();
    			while ((ch = is.read()) != -1)
    			{
    				char ch1 = (char) ch;
    				if (ch1 == ';')
    				{
    					buffer.append("\n\n");
    				}
    				else if (ch1 == ':')
    				{
    					buffer.append("\n");
    				}
    				else
    				{
    
    					buffer.append((char) ch);
    				}
    			}
    			return buffer.toString();
    		}
    		catch (ClassCastException e)
    		{
    			throw new IllegalArgumentException("Not an HTTP URL");
    		}
    		catch (java.io.IOException e)
    		{
    			return "Error " + e.getMessage();
    		}
    		finally
    		{
    			try
    			{
    				if (is != null)
    					is.close();
    				if (c != null)
    					c.close();
    			}
    			catch (Exception e)
    			{
    			}
    		}
    
    	}
    
    }
    
     
    

    All Rights Reserved
    Copyright ©  2004 SYS-CON Media, Inc.
      E-mail: info@sys-con.com

    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.