//6.1.3  ӣStreamConnectionͨ
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class GetURLContent extends MIDlet {

    private Display display;

    String url = "http://www.javacourses.com/hello.txt";

    public GetURLContent() {
       display = Display.getDisplay(this);
    }

    /**
     * MIDletʼʱ򽫻ִ
     */
    public void startApp() {
        try {
            getViaStreamConnection(url);
        } catch (IOException e) {
            //쳣
            System.out.println("IOException " + e);
            e.printStackTrace();
        }
    }

    /**
     * MIDletͣ
     */
    public void pauseApp() {
        
    }

    /**
     * ͷѾԴ
     */
    public void destroyApp(boolean unconditional) {
    }

    /**
     * ͨStream ConnectionȡURL
     */
    void getViaStreamConnection(String url) throws IOException {
        StreamConnection c = null;
        InputStream s = null;
        StringBuffer b = new StringBuffer();
        TextBox t = null;
        try {
          c = (StreamConnection)Connector.open(url);
          s = c.openInputStream();
          int ch;
          while((ch = s.read()) != -1) {
             b.append((char) ch);
          }
          System.out.println(b.toString());
          t = new TextBox("hello....", b.toString(), 1024, 0);
        } finally {
           if(s != null) {
              s.close();
           }
           if(c != null) {
              c.close();
           }
        }
        // ıʵļ
        display.setCurrent(t);
    }
}


//6.2.2  ӣWeb Service
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class HTTPSample extends MIDlet implements CommandListener {

/*
* ȱʡURL
* http://www.webyu.com/servlets/webyu/wirelessdevnetHTTPSample
*/

private static String defaultURL = 
"http://www.webyu.com/servlets/webyu/wirelessdevnetHTTPSample";

// ûַĻ
private Display myDisplay = null;
private Form mainScreen;
private TextField requestField;

// ʾͷϢĻ
private Form resultScreen;
private StringItem resultField;

// "SEND"ť
Command sendCommand = new Command("SEND", Command.OK, 1);

// "BACK" ť
Command backCommand = new Command("BACK", Command.OK, 1);

public HTTPSample(){
	// ʼURLĻ
	myDisplay = Display.getDisplay(this);
	mainScreen = new Form("Type in a string:");
	requestField = 
		new TextField(null, "HELLO WORD", 100, TextField.ANY);
	mainScreen.append(requestField);
	mainScreen.addCommand(sendCommand);
	mainScreen.setCommandListener(this);
}

public void startApp() {
	myDisplay.setCurrent(mainScreen);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void commandAction(Command c, Displayable s) {
	if (c == sendCommand) {
		// ûַ
		String requeststring = requestField.getString();
		// POSTWeb
		String resultstring = sendPostRequest(requeststring);
		// ʾWebӦ
		resultScreen = new Form("Result String:");
		resultField = new StringItem(null, resultstring);
		resultScreen.append(resultField);
		resultScreen.addCommand(backCommand);
		resultScreen.setCommandListener(this);
		myDisplay.setCurrent(resultScreen);
	} else if (c == backCommand) {
		requestField.setString("SOMETHING GOOD");
		myDisplay.setCurrent(mainScreen);
	}
}

//POSTWeb
public String sendPostRequest(String requeststring) {
	HttpConnection hc = null;
	DataInputStream dis = null;
	DataOutputStream dos = null;
	StringBuffer messagebuffer = new StringBuffer();
	try {
		// WebһԷͺͽݵHttp
		hc = (HttpConnection)
		Connector.open(defaultURL, Connector.READ_WRITE);
		// ʽΪPOST
		hc.setRequestMethod(HttpConnection.POST);
		// һֽһֽڵطûַ
		dos = hc.openDataOutputStream();
		byte[] request_body = requeststring.getBytes();
		for (int i = 0; i < request_body.length; i++) {
			dos.writeByte(request_body[i]);
		}
		dos.flush();
		dos.close();
		// ȡ÷ϵservletصӦ
		dis = new DataInputStream(hc.openInputStream());
		int ch;
		// ȼContent-Length 
		long len = hc.getLength(); 
		if(len!=-1) {
			for(int i = 0;i<len;i++)
				if((ch = dis.read())!= -1)
					messagebuffer.append((char)ch);
				} else {
					// Content-LengthЧ
					while ((ch = dis.read()) != -1)
						messagebuffer.append((char) ch);
				}
		dis.close();
	} catch (IOException ioe) {
		messagebuffer = new StringBuffer("ERROR!");
	} finally {
		// ͷIO streams Http 
		try { 
			if (hc != null) hc.close();
		} catch (IOException ignored) {}
		try { 
			if (dis != null) dis.close();
		} catch (IOException ignored) {}
		try { 
			if (dos != null) dos.close();
		} catch (IOException ignored) {}
	}
	return messagebuffer.toString();
}
}


//6.3.4  ˵ĳ
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SampleServer extends HttpServlet {
    public void doPost( HttpServletRequest request,
                     HttpServletResponse response )
            throws IOException, ServletException {

        // ȡMIDlet͵

        ServletInputStream in = request.getInputStream();
        DataInputStream din = new DataInputStream( in );

        String text = din.readUTF();
        din.close();

        // ȡݣУ 
        // ǽַȫתΪд

        text = text.toUpperCase();

        StringTokenizer tok = new StringTokenizer(text );
        Vector v = new Vector();
        while( tok.hasMoreTokens() ){
            v.addElement( tok.nextToken() );
        }

        // γӦݣͷתַ

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream( bout );

        int size = v.size();
        dout.writeInt( size );
        for( int i = 0; i < size; ++i ){
            dout.writeUTF( (String) v.elementAt( i ) );
        }

        byte[] data = bout.toByteArray();

        // Ӧͷ

        response.setContentType("application/octet-stream" );
        response.setContentLength( data.length );
        response.setStatus( response.SC_OK );

        OutputStream out = response.getOutputStream();
        out.write( data );
        out.close();
    }
}


//6.3.5  1ʹHTTPЭ鷢ͺͽı
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class SampleClient extends MIDlet implements CommandListener {
  // ǷURLԸʵġ
  private static String url =
  "http://localhost:8080/servlet/j2me.techtips.SampleServer";
  private Display display;
  private Command exitCommand = new Command( "Exit", Command.EXIT, 1 );
  private Command okCommand = new Command( "OK", Command.OK, 1 );
  private Command sendCommand = new Command( "Send", Command.OK, 1 );
  private TextBox entryForm;
  public SampleClient(){}

  protected void destroyApp(boolean unconditional )
                 throws MIDletStateChangeException {
        exitMIDlet();
  }

    protected void pauseApp(){
    }

    protected void startApp() 
                 throws MIDletStateChangeException {
        if( display == null ){
                             // һη
            initMIDlet();
        }
    }

    private void initMIDlet(){
        display = Display.getDisplay( this );
        entryForm = new EntryForm();
        display.setCurrent( entryForm );
    }

    public void exitMIDlet(){
        notifyDestroyed();
    }

    public void commandAction( Command c, Displayable d ){
        if( c == sendCommand ){
            StatusForm f = 
              new StatusForm( entryForm.getString() );
            display.setCurrent( f );
            f.start();
        } else if( c == okCommand ){
            display.setCurrent( entryForm );
        } else {
            exitMIDlet();
        }
    }

    // ı봰
    class EntryForm extends TextBox {
        EntryForm(){
            super( "Enter some text", "", 80, 0 );
            addCommand( exitCommand );
            addCommand( sendCommand );
            setCommandListener( SampleClient.this );
        }
    }

    // 뷢ͺʾǰݵ״̬

    class StatusForm extends Form 
                   implements Runnable, 
                     HttpConnectionHelper.Callback {
        StatusForm( String text ){
            super( "Status" );

            // ַתΪֽ 
            try {
                ByteArrayOutputStream bout = 
                        new ByteArrayOutputStream();
                DataOutputStream      dout = 
                       new DataOutputStream( bout );

                dout.writeUTF( text );
                data = bout.toByteArray();

                dout.close();
            }
            catch( IOException e ){
                // 
            }
        }

        // ʾ
        void display( String text ){
            if( message == null ){
                message = new
                           StringItem( null, text );
                append( message );
            } else {
                message.setText( text );
            }
        }

        void done( String msg ){
            display( msg != null ? msg : "Done." );
            addCommand( okCommand );
            setCommandListener( SampleClient.this );
        }

        // HTTP ӵCallback 

        public void prepareRequest( 
              String originalURL, HttpConnection conn ) 
              throws IOException
        {
            conn.setRequestMethod( 
                                 HttpConnection.POST );
            conn.setRequestProperty( 
                                "User-Agent", 
           "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
            conn.setRequestProperty( 
                         "Content-Language", "en-US" );
            conn.setRequestProperty( 
                "Accept", "application/octet-stream" );
            conn.setRequestProperty( 
                               "Connection", "close" );
            conn.setRequestProperty( 
                         "Content-Length", 
                     Integer.toString( data.length ) );

            OutputStream os = conn.openOutputStream();
            os.write( data );
            os.close();
        }

        // ڽӵʱʹõһ̣߳ 
        // ûԼʹû

        public void run(){
            HttpConnection conn = null;

            display( 
               "Obtaining HttpConnection object..." );

            try {
                conn = HttpConnectionHelper.connect( 
                                          url, this );

                display( 
                      "Connecting to the server..." );
                int rc = conn.getResponseCode();

                if( rc == HttpConnection.HTTP_OK ){
                    StringBuffer text = new StringBuffer();

                    // ǶȡݵĴ
                    try {
                        DataInputStream din = 
                           new DataInputStream(
                             conn.openInputStream() );

                        int n = din.readInt();
                        while( n-- > 0 ){
                            text.append( 
                                      din.readUTF() );
                            text.append( '\n' );
                        }
                    }
                    catch( IOException e ){
                    }

                    done("Response is:\n" + text.toString() );
                } else {
                    done("Unexpected return code: " + rc );
                }
            }
            catch( IOException e ){
                done( "Exception " + e + " trying to connect." );
            }
        }

        // ں̨ʼϴ
        void start(){
            display( "Starting..." );

            Thread t = new Thread( this );
            try {
                t.start();
            }
            catch( Exception e ){
                done( "Exception " + e + " trying to start thread." );
            }
        }

        private StringItem message;
        private byte[]     data;
    }
}


//6.3.6  2ʹHTTPЭ鷢Ͷ
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class UploadMIDlet2 extends MIDlet implements CommandListener {
    private static String url =
          "http://localhost:8080/servlet/j2me.techtips.SampleServer";
    private Display display;
private Command exitCommand = new Command( "Exit", Command.EXIT, 1 );
private Command sendCommand = new Command( "Send", Command.OK, 1 );
private Form mainForm;
private TextField urlField;
private byte[] Image;
private int i;

public UploadMIDlet2() {
}

protected void destroyApp(boolean arg0) throws
MIDletStateChangeException {
exitMIDlet();
}

protected void pauseApp() {
}

protected void startApp() throws MIDletStateChangeException {
               initMIDlet();
}

private void initMIDlet(){
display = Display.getDisplay( this );
urlField = new TextField( "ͼ·","",30,TextField.ANY );
 mainForm = new Form("ͼϴ");
mainForm.append(urlField);
mainForm.addCommand( sendCommand );
mainForm.addCommand( exitCommand );
display.setCurrent(mainForm);
mainForm.setCommandListener(this);
}

public void exitMIDlet(){
    notifyDestroyed();
}

public void commandAction( Command c, Displayable d ){
if( c == sendCommand ){
String localurl = urlField.getString();
sendimage(localurl);
} else {
exitMIDlet();
}
}

void sendimage(String aurl){
try {
InputConnection pconn = (InputConnection)
Connector.open("file://localhost/"+"aurl",
Connector.READ);
InputStream p = pconn.openInputStream();
int c=p.read();
for(i=0;c!=-1;i++){
Image[i]=(byte)c;
c=p.read();
}
HttpConnection conn = (HttpConnection)Connector.open( url );
conn.setRequestMethod( HttpConnection.POST );
conn.setRequestProperty( 
                        "Accept", "application/octet-stream" );
         conn.setRequestProperty( 
                        "Connection", "close" );
conn.setRequestProperty( 
                        "Content-Length", "i" );
OutputStream os = conn.openOutputStream();
         for(int j=0;j<=i;j++)
                       os.write( Image[j] );
         os.close();
}catch( IOException ioe ){
      // 
} 
    }
}


//6.4.3  һࡪ Encryptor
import org.bouncycastle.crypto.*;
import org.bouncycastle.crypto.engines.*;
import org.bouncycastle.crypto.modes.*;
import org.bouncycastle.crypto.params.*;

// ʹBouncy Castle 
// APIִκݵDESܹ
public class Encryptor {

    private BufferedBlockCipher cipher;
    private KeyParameter        key;

    // ʼ
    // key Ҫ8ֽڳ
    public Encryptor( byte[] key ){
        cipher = new PaddedBlockCipher(
                    new CBCBlockCipher(
                       new DESEngine() ) );

        this.key = new KeyParameter( key );
    }

    // ʼ
    // ַܵ8 ַ
    public Encryptor( String key ){
        this( key.getBytes() );
    }

    // ܵĸ
    private byte[] callCipher( byte[] data )
                        throws CryptoException {
        int    size = 
                   cipher.getOutputSize( data.length );
        byte[] result = new byte[ size ];
        int    olen = cipher.processBytes( data, 0,
                              data.length, result, 0 );
        olen += cipher.doFinal( result, olen );

        if( olen < size ){
            byte[] tmp = new byte[ olen ];
            System.arraycopy( 
                             result, 0, tmp, 0, olen );
            result = tmp;
        }

        return result;
    }

    // ֽ飬һֽз
    // ܺĽ

    public synchronized byte[] encrypt( byte[] data )
                  throws CryptoException {
        if( data == null || data.length == 0 ){
            return new byte[0];
        }

        cipher.init( true, key );
        return callCipher( data );
    }

    // һַ
    public byte[] encryptString( String data )
                  throws CryptoException {
        if( data == null || data.length() == 0 ){
            return new byte[0];
        }

        return encrypt( data.getBytes() );
    }

    // 
    public synchronized byte[] decrypt( byte[] data )
                  throws CryptoException {
        if( data == null || data.length == 0 ){
            return new byte[0];
        }

        cipher.init( false, key );
        return callCipher( data );
    }

    // һʹencryptString ɵַ
    public String decryptString( byte[] data )
                    throws CryptoException {
        if( data == null || data.length == 0 ){
            return "";
        }

        return new String( decrypt( data ) );
    }
}


//6.4.5  ݼܵ
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;

import org.bouncycastle.crypto.*;

// Լܺͽܷ
public class CryptoTest extends MIDlet {

    private Display display;
    private Command exitCommand =
                         new Command( "Exit", Command.EXIT, 1 ); 
    private Command okCommand =
                         new Command( "OK", Command.OK, 1 );

    private Encryptor   encryptor;
    private RecordStore rs;

    public CryptoTest(){
    }

    protected void destroyApp( boolean unconditional )
                   throws MIDletStateChangeException {
        exitMIDlet();
    }

    protected void pauseApp(){
    }

    protected void startApp()
                   throws MIDletStateChangeException {
        if( display == null ){ // һ
            initMIDlet();
        }
    }

    private void initMIDlet(){
        display = Display.getDisplay( this );

        // һRecord Store

        try {
            rs = RecordStore.openRecordStore( "test",
                                    true );
        }
        catch( RecordStoreException e ){
            // 
        }

        display.setCurrent( new AskForKey() );
    }

    public void exitMIDlet(){
        try {
            if( rs != null ){
                rs.closeRecordStore();
            }
        }
        catch( RecordStoreException e ){
        }

        notifyDestroyed();
    }
        // 쳣
    private void displayException( Exception e ){
        Alert a = new Alert( "Exception" );
        a.setString( e.toString() );
        a.setTimeout( Alert.FOREVER );
        display.setCurrent( a, new AskForKey() );
    }

    class AskForKey extends TextBox implements CommandListener {
        public AskForKey(){
            super( "Enter a secret key:", "", 8, 0 );
            setCommandListener( this );
            addCommand( okCommand );
            addCommand( exitCommand );
        }

        public void commandAction( Command c,
                                   Displayable d ){
            if( c == exitCommand ){
                exitMIDlet();
            } 

            String key = getString();
            if( key.length() < 8 ){
                Alert a = new Alert( "Key too short" );
                a.setString( "The key must be " +
                             "8 characters long" );
                setString( "" );
                display.setCurrent( a, this );
                return;
            }

            encryptor = new Encryptor( key );  // ɼ

            try {
                if( rs.getNextRecordID() == 1 ){
                    display.setCurrent(
                                  new EnterMessage() );
                } else {
                    byte[] data = rs.getRecord( 1 );
                    String str = 
                       encryptor.decryptString( data );

                    Alert a = 
                        new Alert( "Decryption" );
                    a.setTimeout( Alert.FOREVER );
                    a.setString( 
                        "The decrypted string is '" +
                                 str + "'" );
                    display.setCurrent( a, this );
                }
            }
            catch( RecordStoreException e ){
                displayException( e );
            }
            catch( CryptoException e ){
                displayException( e );
            }
        }
    }
    // ַı
    class EnterMessage extends TextBox
                       implements CommandListener {
        public EnterMessage(){
            super( "Enter a message to encrypt:", "", 100, 0 );
            setCommandListener( this );
            addCommand( okCommand );
        }

        public void commandAction( Command c,
                                   Displayable d ){
            String msg = getString();

            try {
                byte[] data =
                      encryptor.encryptString( msg );
                rs.addRecord( data, 0, data.length );
            }
            catch( RecordStoreException e ){
                displayException( e );
            }
            catch( CryptoException e ){
                displayException( e );
            }

            display.setCurrent( new AskForKey() );
        }
    }
}


//6.5.1  Webȡһҳ
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

/**
 * ʹHttpConnectionWebȡһҳ
 */
public class FetchPage extends MIDlet {

    private Display display;
    private String url = "http://www.javacourses.com/hello.txt";

    public FetchPage() {
        display = Display.getDisplay(this);
    }

    public void startApp() {
        // urlָҳ
        try {
           downloadPage(url);
        } catch(IOException e) {
           // 쳣
        }
    }
    // ҳĹ
    private void downloadPage(String url) throws IOException {
        StringBuffer b = new StringBuffer();
        InputStream is = null;
        HttpConnection c = null;
        TextBox t = null;
        try {
            long len = 0 ;
            int ch = 0;

            c = (HttpConnection)Connector.open(url);  // 
            is = c.openInputStream();

            len =c.getLength() ;
            if ( len != -1) {
                // ȡContent-Lengthָȵֽ
                for (int i =0 ; i < len ; i++ )
                    if ((ch = is.read()) != -1)
                        b.append((char) ch);
            } else {
                // ȡֱӹر
                while ((ch = is.read()) != -1) {
                    len = is.available() ;
                    b.append((char)ch);
                }
            }
            t = new TextBox("hello again....", b.toString(), 1024, 0);
        }  finally {
           is.close();
           c.close();
        }

        display.setCurrent(t);
    }

    /**
     * MIDletͣ
     */
    public void pauseApp() {
    }

    /**
     * ͷѾԴ
     */
    public void destroyApp(boolean unconditional) {
    }

}


//6.5.2  ƶ绰ϷServletý
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

/**
 * ִзһCGIű
 */

public class InvokeCGI extends MIDlet {

    private Display display;
    // CGIűURL
    String url = "http://www.javacourses.com/cgi-bin/getgrade. cgi? idnum=182016";

    public InvokeCGI() {
       display = Display.getDisplay(this);
    }

    /**
     * MIDletʼʱִ
     */
    public void startApp() {
	try {
            getGrade(url);
	} catch (IOException e) {
	    System.out.println("IOException " + e);
	    e.printStackTrace();
	}
    }

    /**
     * MIDletͣ
     */
    public void pauseApp() {
	
    }

    /**
     * ͷѾԴ
     */
    public void destroyApp(boolean unconditional) {
    }

    /**
     * ȡһֳɼ
     */
     void getGrade(String url) throws IOException {
        HttpConnection c = null;
        InputStream is = null;
        OutputStream os = null;
        StringBuffer b = new StringBuffer();
        TextBox t = null;
        int x = 5, y =7;
        try {
          c = (HttpConnection)Connector.open(url);  // 
          c.setRequestMethod(HttpConnection.GET);
          c.setRequestProperty("IF-Modified-Since", 
                             "10 Nov 2000 17:29:12 GMT");
          c.setRequestProperty("User-Agent",
                            "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
          c.setRequestProperty("Content-Language", "en-CA");
          os = c.openOutputStream();
          is = c.openDataInputStream();
          int ch;
          while ((ch = is.read()) != -1) {  // ȡ
            b.append((char) ch);
            System.out.println((char)ch);
          }
          t = new TextBox("Final Grades", b.toString(), 1024, 0);
        } finally {
           if(is!= null) {
              is.close();
           }
           if(os != null) {
              os.close();
           }
           if(c != null) {
              c.close();
           }
        }
        display.setCurrent(t);
    }     
}


//6.5.3  Websocket
import java.io.*;
import javax.microedition.io.*;

public class TestHTTP {
    public static void main( String[] args ){
        try {
            String uri =
              "testhttp://www.ericgiguere.com/index.html";
            ContentConnection conn = (ContentConnection)
               Connector.open( uri );  // 

            InputStream in = conn.openInputStream();
            int ch;

            System.out.println( "Content type is "
                               + conn.getType() );

            while( ( ch = in.read() ) != -1 ){  // ȡ
                System.out.print( (char) ch );
            }

            in.close();
            conn.close();
        }
        catch( ConnectionNotFoundException e ){
            System.out.println("URI could not be opened" );  // 쳣
        }
        catch( IOException e ){
            System.out.println( e.toString() );
        }

        System.exit( 0 );
    }
} 


//6.5.4  YahooùƱϢ
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class QuotesMIDlet extends MIDlet implements CommandListener {
    Display display = null;
    List menu = null; // ˵
    List choose = null;
    TextBox input = null;
    Ticker ticker = new Ticker("Database Application");
    // Yahooַ
    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;

    // Ʊ
    String name, date, price;

    StockDB db = null;

    public QuotesMIDlet() {
    }

    public void startApp() throws MIDletStateChangeException {
      display = Display.getDisplay(this);
      // һƱݿ
      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")) {
              // ݿ
            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")) {
            // ˵
            mainMenu();
          } else if(currentMenu.equals("Add")) {
            // ˵
            mainMenu();
          }

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