import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class Conn3 extends MIDlet implements CommandListener
{
  private Display display;
  private Form form;
  private Command cmConnect;
  private Command cmExit;
  private StringItem teksti;

  public Conn3()
  {
     display = Display.getDisplay(this);

     cmConnect = new Command("Connect", Command.SCREEN, 1);
     cmExit = new Command("Exit", Command.EXIT, 1);
     teksti = new StringItem(null, "If you want servlet connection, select Connect");
     form = new Form("Servlet connection");
     form.addCommand(cmExit);
     form.addCommand(cmConnect);
     form.append(teksti);
     form.setCommandListener(this);
  }
  public void startApp()
  {
     display.setCurrent(form);
  }
  public void pauseApp()
  { }
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
     if (c == cmConnect)
     {
       Thread t = new Thread(){
          public void run(){
            try{
               connect();
            } catch (Exception e){
               System.err.println("Msg: " + e.toString());
            }
         }
       };
       t.start();
     }
      else if (c == cmExit)
     {
       destroyApp(false);
       notifyDestroyed();
     }
  }
  private void connect() throws IOException
  {
     HttpConnection conn = null;
     InputStream input = null;
     String url = "http://localhost:8080/servlet/example1";
     try
     {
        conn = (HttpConnection) Connector.open(url);
        input = conn.openInputStream();
        if (conn.getResponseCode() == HttpConnection.HTTP_OK)
        {
           int length = (int) conn.getLength();
           String str;
           if (length != -1)
           {
              byte data[] = new byte[length];
              input.read(data);
              str = new String(data);
           }
           else  // no length of the message
           {
              ByteArrayOutputStream bStream = new ByteArrayOutputStream();
              int ch;
              while ((ch = input.read()) != -1)
                      bStream.write(ch);
              str = new String(bStream.toByteArray());
              bStream.close();
           }
           teksti.setText(str);
        } else
           teksti.setText(new String(conn.getResponseMessage()));
     }
     finally
     {
      if (input != null)
         input.close();
      if (conn != null)
         conn.close();
     }
  }
}

