QuotesMIDlet.java Source code

Java tutorial

Introduction

Here is the source code for QuotesMIDlet.java

Source

 /* License
  * 
  * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  *  
  *  * Redistribution of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  * 
  *  * Redistribution in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the
  *      documentation and/or other materials provided with the distribution.
  * 
  * Neither the name of Sun Microsystems, Inc. or the names of contributors
  * may be used to endorse or promote products derived from this software
  * without specific prior written permission.
  *  
  * This software is provided "AS IS," without a warranty of any kind. ALL
  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  *  
  * You acknowledge that this software is not designed, licensed or intended
  * for use in the design, construction, operation or maintenance of any
  * nuclear facility. 
  */

 import java.io.ByteArrayOutputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
 import java.io.InputStream;

 import javax.microedition.io.Connector;
 import javax.microedition.io.StreamConnection;
 import javax.microedition.lcdui.Choice;
 import javax.microedition.lcdui.Command;
 import javax.microedition.lcdui.CommandListener;
 import javax.microedition.lcdui.Display;
 import javax.microedition.lcdui.Displayable;
 import javax.microedition.lcdui.List;
 import javax.microedition.lcdui.TextBox;
 import javax.microedition.lcdui.TextField;
 import javax.microedition.lcdui.Ticker;
 import javax.microedition.midlet.MIDlet;
 import javax.microedition.midlet.MIDletStateChangeException;
 import javax.microedition.rms.RecordEnumeration;
 import javax.microedition.rms.RecordStore;
 import javax.microedition.rms.RecordStoreException;
 import javax.microedition.rms.RecordStoreNotOpenException;

 public class QuotesMIDlet extends MIDlet implements CommandListener {
     Display display = null;
     List menu = null; // main menu
     List choose = null;
     TextBox input = null;
     Ticker ticker = new Ticker("Database Application");
     String quoteServer = "http://quote.yahoo.com/d/quotes.csv?s=";
     String quoteFormat = "&f=slc1wop";

     static final Command backCommand = new Command("Back", Command.BACK, 0);
     static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
     static final Command saveCommand = new Command("Save", Command.OK, 2);
     static final Command exitCommand = new Command("Exit", Command.STOP, 3);
     String currentMenu = null;

     // Stock data
     String name, date, price;

     StockDB db = null;

     public QuotesMIDlet() {
     }

     public void startApp() throws MIDletStateChangeException {
         display = Display.getDisplay(this);
         // open a db stock file
         try {
             db = new StockDB("stocks");
         } catch (Exception e) {
         }
         menu = new List("Stocks Database", Choice.IMPLICIT);
         menu.append("List Stocks", null);
         menu.append("Add A New Stock", null);
         menu.addCommand(exitCommand);
         menu.setCommandListener(this);
         menu.setTicker(ticker);

         mainMenu();
     }

     public void pauseApp() {
         display = null;
         choose = null;
         menu = null;
         ticker = null;

         try {
             db.close();
             db = null;
         } catch (Exception e) {
         }
     }

     public void destroyApp(boolean unconditional) {
         try {
             db.close();
         } catch (Exception e) {
         }
         notifyDestroyed();
     }

     void mainMenu() {
         display.setCurrent(menu);
         currentMenu = "Main";
     }

public String tickerString() {
   StringBuffer ticks = null;
   try {
      RecordEnumeration enum = db.enumerate();
      ticks = new StringBuffer();
      while (enum.hasNextElement()) {
         String stock1 = new String(enum.nextRecord());
         ticks.append(Stock.getName(stock1));
         ticks.append(" @ ");
         ticks.append(Stock.getPrice(stock1));
         ticks.append("    ");
      }
   } catch (Exception ex) {
   }
   return (ticks.toString());
}

     public void addStock() {
         input = new TextBox("Enter a Stock Name:", "", 5, TextField.ANY);
         input.setTicker(ticker);
         input.addCommand(saveCommand);
         input.addCommand(backCommand);
         input.setCommandListener(this);
         input.setString("");
         display.setCurrent(input);
         currentMenu = "Add";
     }

     public String getQuote(String input) throws IOException, NumberFormatException {
         String url = quoteServer + input + quoteFormat;
         StreamConnection c = (StreamConnection) Connector.open(url, Connector.READ_WRITE);
         InputStream is = c.openInputStream();
         StringBuffer sb = new StringBuffer();
         int ch;
         while ((ch = is.read()) != -1) {
             sb.append((char) ch);
         }
         return (sb.toString());
     }

     public void listStocks() {
         choose = new List("Choose Stocks", Choice.MULTIPLE);
         choose.setTicker(new Ticker(tickerString()));
         choose.addCommand(backCommand);
         choose.setCommandListener(this);
         try {
             RecordEnumeration re = db.enumerate();
             while (re.hasNextElement()) {
                 String theStock = new String(re.nextRecord());
                 choose.append(Stock.getName(theStock) + " @ " + Stock.getPrice(theStock), null);
             }
         } catch (Exception ex) {
         }
         display.setCurrent(choose);
         currentMenu = "List";
     }

     public void commandAction(Command c, Displayable d) {
         String label = c.getLabel();
         if (label.equals("Exit")) {
             destroyApp(true);
         } else if (label.equals("Save")) {
             if (currentMenu.equals("Add")) {
                 // add it to database
                 try {
                     String userInput = input.getString();
                     String pr = getQuote(userInput);
                     db.addNewStock(pr);
                     ticker.setString(tickerString());

                 } catch (IOException e) {
                 } catch (NumberFormatException se) {
                 }
                 mainMenu();
             }

         } else if (label.equals("Back")) {
             if (currentMenu.equals("List")) {
                 // go back to menu
                 mainMenu();
             } else if (currentMenu.equals("Add")) {
                 // go back to menu
                 mainMenu();
             }

         } else {
             List down = (List) display.getCurrent();
             switch (down.getSelectedIndex()) {
             case 0:
                 listStocks();
                 break;
             case 1:
                 addStock();
                 break;
             }

         }
     }
 }

 class StockDB {

     RecordStore recordStore = null;

     public StockDB() {
     }

     public StockDB(String fileName) {
         try {
             recordStore = RecordStore.openRecordStore(fileName, true);
         } catch (RecordStoreException rse) {
             rse.printStackTrace();
         }
     }

     public void close() throws RecordStoreNotOpenException, RecordStoreException {
         if (recordStore.getNumRecords() == 0) {
             String fileName = recordStore.getName();
             recordStore.closeRecordStore();
             recordStore.deleteRecordStore(fileName);
         } else {
             recordStore.closeRecordStore();
         }
     }

     public synchronized void addNewStock(String record) {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         DataOutputStream outputStream = new DataOutputStream(baos);
         try {
             outputStream.writeUTF(record);
         } catch (IOException ioe) {
             System.out.println(ioe);
             ioe.printStackTrace();
         }
         byte[] b = baos.toByteArray();
         try {
             recordStore.addRecord(b, 0, b.length);
         } catch (RecordStoreException rse) {
             System.out.println(rse);
             rse.printStackTrace();
         }
     }

     public synchronized RecordEnumeration enumerate() throws RecordStoreNotOpenException {
         return recordStore.enumerateRecords(null, null, false);
     }

 }

 /*
  * License
  * 
  * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
  * 
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are met:
  *  * Redistribution of source code must retain the above copyright notice, this
  * list of conditions and the following disclaimer.
  *  * Redistribution in binary form must reproduce the above copyright notice,
  * this list of conditions and the following disclaimer in the documentation
  * and/or other materials provided with the distribution.
  * 
  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
  * be used to endorse or promote products derived from this software without
  * specific prior written permission.
  * 
  * This software is provided "AS IS," without a warranty of any kind. ALL
  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS
  * LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A
  * RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  * IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT
  * OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
  * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
  * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
  * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  * 
  * You acknowledge that this software is not designed, licensed or intended for
  * use in the design, construction, operation or maintenance of any nuclear
  * facility.
  */
 class Stock {
     private static String name, time, price;

     public static void parse(String data) {
         int index = data.indexOf('"');
         name = data.substring(++index, (index = data.indexOf('"', index)));
         index += 3;
         time = data.substring(index, (index = data.indexOf('-', index)) - 1);
         index += 5;
         price = data.substring(index, (index = data.indexOf('<', index)));
     }

     public static String getName(String record) {
         parse(record);
         return (name);
     }

     public static String getPrice(String record) {
         parse(record);
         return (price);
     }

 }