Mega Code Archive

 
Categories / Java / J2ME
 

Use Java servlets sessions to tally golf scores

/*-------------------------------------------------- * Url_rewrite.java  * * Use Java servlets sessions to tally golf scores. * Session management is done using url-rewriting. * * Example from the book:     Core J2ME Technology * Copyright John W. Muchow   http://www.CoreJ2ME.com * You may use/modify for any non-commercial purpose *-------------------------------------------------*/ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class Url_rewrite extends MIDlet implements CommandListener {   private Display display;      // Reference to display object    private Form fmMain;          // The main form   private TextField tfScore;    // Enter new score   private int indxTextField;    // Index on of the textfield   private StringItem siTotal;   // Running total   private Command cmExit;       // A Command to exit the MIDlet     private Command cmUpdate;     // Update score on servlet   private int holeNumber = 1;   // Current hole   private static final int MAX_HOLES = 18;   private String url = "http://www.mycgiserver.com/servlet/corej2me.Url_rewriteServlet";   public Url_rewrite()   {     display = Display.getDisplay(this);     // Enter scores         tfScore = new TextField("Enter score for Hole #1", "", 2, TextField.NUMERIC);          // Current running total     siTotal = new StringItem("Total: ", "");     // Commands     cmExit = new Command("Exit", Command.EXIT, 1);     cmUpdate = new Command("Send", Command.SCREEN,2);     // Create Form, add components, listen for events     fmMain = new Form("");          // Save index of textfield, it is removed      // after entering 18 values     indxTextField = fmMain.append(tfScore);     fmMain.append(siTotal);     fmMain.addCommand(cmExit);     fmMain.addCommand(cmUpdate);     fmMain.setCommandListener(this);      }   public void startApp()   {     display.setCurrent(fmMain);   }            public void pauseApp()   { }   public void destroyApp(boolean unconditional)   { }   /*--------------------------------------------------   * Process events   *-------------------------------------------------*/     public void commandAction(Command c, Displayable s)   {     if (c == cmExit)     {       destroyApp(false);       notifyDestroyed();     }      else if (c == cmUpdate)  // Send score for next hole     {       // If nothing in the text field or max scores entered       if (tfScore.getString().equals("") || holeNumber > MAX_HOLES)         return;       else       {         try         {           // Update the score on remote server           updateTotal(tfScore.getString());                    // If entered the maximum, remove the            // textfield from the form           if (++holeNumber > MAX_HOLES)           {             fmMain.delete(indxTextField);             return;           }              // Change the label & reset contents           tfScore.setLabel("Enter score for Hole #" + holeNumber);           tfScore.setString("");         }         catch (Exception e)         {           System.err.println("Msg: " + e.toString());         }       }     }        }   /*--------------------------------------------------   * Send client request. Receive server response   *   * Client: Send score for next hole.   *   * Server: Check for custom header 'Custom-newURL'   *         If found, update the MIDlet URL for all   *         future requests. Any data returned is    *         current total for all scores entered.   *-------------------------------------------------*/   private void updateTotal(String score) throws IOException   {     HttpConnection http = null;     InputStream iStrm = null;         boolean ret = false;           try     {       // When using GET, append data onto the url       String completeURL = url + "?" + "score=" + score;              http = (HttpConnection) Connector.open(completeURL);              //----------------       // Client Request       //----------------       // 1) Send request method       http.setRequestMethod(HttpConnection.GET);       // 2) Send header information - none              // If you experience connection/IO problems, try        // removing the comment from the following line       //http.setRequestProperty("Connection", "close");                    // 3) Send body/data -  data is at the end of URL       //----------------       // Server Response       //----------------       iStrm = http.openInputStream();             // 1) Get status Line - ignore for now         // System.out.println("Msg: " + http.getResponseMessage());                           // System.out.println("Code: " + http.getResponseCode());                              // 2) Get header information        // See if header includes a rewritten url       // if yes, update url for all future servlet requests       String URLwithID = http.getHeaderField("Custom-newURL");              if (URLwithID != null)         url = URLwithID;             // 3) Get body/data - the new running total is returned       String str;       int length = (int) http.getLength();       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();                                }       // Update the stringitem that shows total       siTotal.setText(str);     }     finally     {       // Clean up       if (iStrm != null)         iStrm.close();       if (http != null)         http.close();     }   } } /*-------------------------------------------------- * Url_rewriteServlet.java * * Use url-rewriting to manage sessions. * Keeps a running total of golf scores for a  * round of 18 holes (client sends score for each * hole, one at a time). * * Example from the book:     Core J2ME Technology * Copyright John W. Muchow   http://www.CoreJ2ME.com * You may use/modify for any non-commercial purpose *-------------------------------------------------*/ //package corej2me; // Required for mycgiserver.com import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Url_rewriteServlet extends HttpServlet {   /*--------------------------------------------------   * Initialize the servlet   *-------------------------------------------------*/     public void init(ServletConfig config) throws ServletException   {     super.init(config);   }   /*--------------------------------------------------   * Handle a GET request from client   *-------------------------------------------------*/     protected void doGet(HttpServletRequest req, HttpServletResponse res)                         throws ServletException, IOException   {     try     {       // Get session information       HttpSession session = req.getSession(true);              // If a new session, we need to rewrite the URL for client       if (session.isNew())       {         // Get the URL that got us here         String incomingURL = HttpUtils.getRequestURL(req).toString();                  // Encode by adding session ID onto URL         String URLwithID = res.encodeURL(incomingURL);                  // Send back a header to client with new re-written URL         res.setHeader("Custom-newURL", URLwithID);       }       // Get the next score (parameter) passed in       int nextScore = Integer.parseInt(req.getParameter("score"));          // Get the ongoing total saved as part of the session       // Convert to an integer "object"       Integer sessionTotal = (Integer) session.getValue("sessionTotal");             // Running total from session and score passed in                   int runningTotal = nextScore;       if (sessionTotal != null)         runningTotal += sessionTotal.intValue();       // Update the session total, must save as an "object"             session.putValue("sessionTotal", new Integer(runningTotal));       // Send back to client the new running total       res.setContentType("text/plain");       PrintWriter out = res.getWriter();       out.write(Integer.toString(runningTotal));       out.close();     }     catch (Exception e)     {       System.err.println("Msg: " + e.toString());     }   }   /*--------------------------------------------------   * Information about servlet   *-------------------------------------------------*/   public String getServletInfo()   {     return "Url_rewriteServlet 1.0 - John W. Muchow - www.corej2me.com";   } }