/*
 * @author:      snoopy
 * @date:        10/06/2003
 * @file:        ue4.java
 * @course:      Embedded Systems
 * @environment: Java 2 (1.4.1), J2ME, Midp 2
 *
 * @comment: Die Midp-Klasses sendet 2 Strings an den Soft-Server, der Server
 *           antwortet mit einer Antwort-Html-Seite, die im Emulator angezeigt
 *           wird.
 *
 * @ablauf:  start in %midp_home%\\ue4
 *           javac -classpath ..\classes ue4.java
 *           ..\bin\preverify -classpath ..\classes -d . .
 *           jar -cmf ue4.mf ue4.jar ue4.class
 *           dir ue4.jar   (Die Größe von ue4.jar muß in ue4.jad angegeben werden.)
 *           JAR-URL in ue4.jad ist http://localhost/ues4.jad
 *           ue4.jar und ue4.jad ins webserver-homeverzeichnis kopieren
 *           mimetypes im webserver-config-file anpassen: jar und jad (--> ue-skript)
 *           ..\bin\midp -transient -force http://localhost/ue4.jad
 *           das instslliert das jad file im emulator
 *           direktes installieren funktioniert nicht.
 *           emulator schließen.
 *           ..\bin\midp  (ohne argumente neu starten).
 *           apps auswählen, eigene applikation auswählen, menu button klicken,
 *           "application settings" auswählen, alles auf "yes, always" setzen.
 *           ok-button klicken --> speichert die settings.
 *           jetzt applikation starten (launch).
 *           jetzt erst gehts.
 */

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

public class ue4 extends MIDlet
implements CommandListener {

  // server address
  //private static String url = "http://www.soft.uni-linz.ac.at/~vogl/es/newpos.php";
  private static String url = "http://localhost/cgi-bin/testcgi.exe";

  // GUI component for user to enter String
  private Display myDisplay = null;
  private Form mainScreen;
  private TextField requestField;
  private TextField requestField2;
  private Form resultScreen;
  private StringItem resultField;
  Command sendCommand = new Command("SEND", Command.OK, 1);
  Command backCommand = new Command("BACK", Command.OK, 1);

  public ue4(){
    // initialize GUI
    myDisplay = Display.getDisplay(this);
    mainScreen = new Form("Type in a string:");
    requestField = new TextField(null, "#MATRNR", 100, TextField.ANY);
    requestField2 = new TextField(null, "POS", 100, TextField.ANY);
    mainScreen.append(requestField);
    mainScreen.append(requestField2);
    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 = "matrnr=" + requestField.getString() + "&pos=" + requestField2.getString();
      String resultstring = sendPostRequest(requeststring);

      // display the response
      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) {
      // do it all over again
      requestField.setString("next one");
      myDisplay.setCurrent(mainScreen);
    }
  }

  public String sendPostRequest(String requeststring) {
    HttpConnection hc = null;
    OutputStream dos = null;
    InputStream dis = null;
    StringBuffer messagebuffer = new StringBuffer();
    try {
      hc = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
      hc.setRequestMethod(HttpConnection.POST);

      // Send the string
      dos = hc.openOutputStream();
      byte[] request_body = requeststring.getBytes();
      dos.write( request_body );
      dos.flush();

      dis = hc.openInputStream();
      int ch;
      long len = hc.getLength(); // Check the Content-Length
      if(len!=-1) {
        for(int i = 0;i<len;i++)
          if((ch = dis.read())!= -1)
            messagebuffer.append((char)ch);
      } else { // length is not available
          while ((ch = dis.read()) != -1)
            messagebuffer.append((char) ch);
      }
    }
    catch (IOException ioe) {
      messagebuffer = new StringBuffer("ERROR!");
    }
    catch (Exception e) {
      messagebuffer = new StringBuffer(e.toString());
    }
    finally {
        try {
          if (hc != null) hc.close();
          if (dis != null) dis.close();
          if (dos != null) dos.close();
        } catch (IOException ignored) {}
    }
    return messagebuffer.toString();
  }

}
