Skip to main content

J2ME 101, Part 4: The Generic Connection Framework

DateFormat MIDlet

/*--------------------------------------------------
* DateFormat.java
*
* Get a date format from a servlet
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;

public class DateFormat extends MIDlet implements CommandListener
{
     private Display display = null;
     private TextBox tbMain;
     private Form fmMain;
     private Command cmExit;
     private Command cmRqst;
	private Alert alError;       // Alert to error message
     private String errorMsg = null;
     private String serverMsg = null;

     public DateFormat()
     {
       // Create commands
       cmExit = new Command("Exit", Command.EXIT, 1);
       cmRqst = new Command("Rqst", Command.SCREEN, 2);

       // Create the form, add commands, listen for events
       fmMain = new Form("");
       fmMain.addCommand(cmExit);
       fmMain.addCommand(cmRqst);
       fmMain.setCommandListener(this);
     }

     public void startApp()
     {
       if (display == null)
         display = Display.getDisplay(this);
       display.setCurrent(fmMain);
     }

     public void pauseApp()
     { }

     public void destroyApp(boolean unconditional)
     {
     }

     /*--------------------------------------------------
     * Call the servlet
     *-------------------------------------------------*/
     public void commandAction(Command c, Displayable s)
     {
       if (c == cmRqst)
       {
         try
         {
           serverMsg = null;
           callServlet();
           if (serverMsg != null)
             fmMain.append(serverMsg);
         }
         catch (Exception e)
         {
           System.err.println("Msg: " + e.toString());
         }
       }
       else if (c == cmExit)
	  {
	    destroyApp(false);
	    notifyDestroyed();
	  }
     }

     /*--------------------------------------------------
     * Simple message to console for debug/errors
     * When used with Exceptions we should handle the
     * error in a more appropriate manner.
     *-------------------------------------------------*/
     private void db(String str)
     {
       System.err.println("Msg: " + str);
     }

     /*--------------------------------------------------
     * Show an Alert
     *-------------------------------------------------*/
     private void showAlert(String msg)
     {
       // Create Alert, use message returned from servlet
       alError = new Alert("Error", msg, null, AlertType.ERROR);

       // Set Alert to type Modal
       alError.setTimeout(Alert.FOREVER);

       // Display the Alert. Once dismissed, display the form
       display.setCurrent(alError, fmMain);
     }

     /*--------------------------------------------------
     * Call the servlet
     *-------------------------------------------------*/
     private void callServlet() throws IOException
     {
       HttpConnection http = null;
       InputStream iStrm = null;
       boolean ret = false;

       // Examples - Data is passed at the end of url for GET
       String url = "http://www.mycgiserver.com/servlet/corej2me.DateFormatServlet?format=MMMM.dd.yyyy+'-'+hh:mm+aa"; 
//    String url = "http://www.mycgiserver.com/servlet/corej2me.DateFormatServlet?format=yyyy.MM.dd+'at'+hh:mm:ss+zzz";

       try
       {
         http = (HttpConnection) Connector.open(url);

         //----------------
         // Client Request
         //----------------
         // 1) Send request method
         http.setRequestMethod(HttpConnection.GET);
         // 2) Send header information - none
         // 3) Send body/data -  data is at the end of URL

         //----------------
         // Server Response
         //----------------
         iStrm = http.openInputStream();
         // Three steps are processed in this method call
         ret = processServerResponse(http, iStrm);
       }
       finally
       {
         // Clean up
         if (iStrm != null)
           iStrm.close();
         if (http != null)
           http.close();
       }

       // Process request failed, show alert
       if (ret == false)
         showAlert(errorMsg);
     }

     /*--------------------------------------------------
     * Process a response from a server
     *-------------------------------------------------*/
     private boolean processServerResponse(HttpConnection http,InputStream iStrm) throws IOException
     {
       //Reset error message
       errorMsg = null;

       // 1) Get status Line
       if (http.getResponseCode() == HttpConnection.HTTP_OK)
       {
         // 2) Get header information - none

         // 3) Get body (data)
         int length = (int) http.getLength();
         String str;
         if (length != -1)
         {
           byte servletData[] = new byte[length];
           iStrm.read(servletData);
           str = new String(servletData);
         }
         else  // Length not available...
         {
           ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

           int ch;
           while ((ch = iStrm.read()) != -1)
             bStrm.write(ch);

           str = new String(bStrm.toByteArray());
           bStrm.close();
         }

        // Save the server message
        serverMsg = str;
        return true;

       }
       else
         // Use message from the servlet
         errorMsg = new String( http.getResponseMessage());

       return false;
     }
}

Return to article