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
 

"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: [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.