// Test sample 2.

package oracle.wireless.me.sample1;

import java.util.Vector;
import java.util.Enumeration;

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

import oracle.wireless.me.core.*;

/**
 * Sample2 calls methods in TestWebService to test maximum
 * packet size and null or void returns.
 */
public class Sample2 extends MIDlet implements CommandListener
{
    private Display display;
    private Form form;
    private Command exitCommand;
    private Command goCommand;
    private Command goPieceCommand;
    private Command clearCCommand;
    private Command clearSCommand;
    private Command goNullCommand;
    private Command goVoidCommand;
    private Command goNoSessCommand;

    private ServiceFactory serviceFactory;
    private Service service;

    public Sample2()
    {
    }

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

    protected void pauseApp()
    {
      try {
        ServiceManager.getInstance().close();
      }
      catch (Exception e) {
      }
      //System.out.println("Sample2 paused");
    }

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

    public void commandAction(Command c, Displayable d)
    {
      if (c == exitCommand) {
	      exitMIDlet();
	    }
	    else if (c == goCommand) {
	      callService();
	    }
	    else if (c == goPieceCommand) {
	      callPieceService();
	    }
	    else if (c == clearCCommand) {
	      clearCache();
	    }
	    else if (c == clearSCommand) {
	      clearScreen();
	    }
	    else if (c == goNullCommand) {
	      callNullService();
	    }
	    else if (c == goVoidCommand) {
	      callVoidService();
	    }
	    else if (c == goNoSessCommand) {
	      callNoSession();
	    }
    }

    private void initMIDlet()
    {
      // Get the URL of the J2ME proxy server.
      String servURL = getAppProperty("oracle-j2me-server-url");

      if (servURL == null) {
	      servURL = "http://localhost:7777/mcs/wsproxy/proxy";
	      //System.out.println("Unable to get j2me_proxy app property, using default: " + servURL);
      }

      serviceFactory = ServiceFactory.getInstance();
      service = serviceFactory.createService(servURL, "DEFAULT", "TestWebService");

      // Display, etc.
      display = Display.getDisplay(this);

      exitCommand = new Command("Exit", Command.EXIT, 1);
      goCommand = new Command("hello", Command.SCREEN, 1);
      goPieceCommand = new Command("hello packets", Command.SCREEN, 2);
      clearCCommand = new Command("Clear Cache", Command.SCREEN, 2);
      clearSCommand = new Command("Clear Screen", Command.SCREEN, 2);
      goNullCommand = new Command("hellonull", Command.SCREEN, 3);
      goVoidCommand = new Command("hellovoid", Command.SCREEN, 3);
      goNoSessCommand = new Command("hello no session", Command.SCREEN, 1);

      form = new SimpleForm();
      display.setCurrent( form );
    }

  // On exit from the midlet, clear cache.
  private void exitMIDlet()
  {
    clearCache();
    try {
      ServiceManager.getInstance().close();
    }
    catch (Exception e) {
    }

    notifyDestroyed();
  }


  // Make a normal remote procedure call.
  private void callService()
  {
    // Disable max request size (set it to 0).
    // Max request size is 0 (disabled) by default, but in this sample,
    // it may have been set by a call to callPieceService().
    service.setProperty( Service.MAX_REQUEST_SIZE, new Integer(0) );

    // Enable session support.
    // Session are enabled by default, but in this sample, they
    // may have been disabled by a call to callNoSession().
    service.setProperty( Service.SESSION_MAINTAIN, new Boolean(true) );

    // Set cache timeout to 1 minute.
    Call call = service.createCall("hello", 1);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new String("World") );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      
      try {
	      String respStr = res.getString();
	
	      // Display the result of the call.
	      form.append( respStr + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }

  
  // Make a call sent in packets to overcome network limitations.
  // Some wireless networks drop requests and responses if they
  // exceed a certain size.
  private void callPieceService()
  {
    // Set service max request size.  
    service.setProperty( Service.MAX_REQUEST_SIZE, new Integer(500) );

    // Disable session support.
    // Session are enabled by default, and sending a request in pieces
    // forces sessions to be enabled.  Disable sessions here to test
    // that this is in fact ignored and the request succeeds.
    service.setProperty( Service.SESSION_MAINTAIN, new Boolean(false) );

    // Send piece request with multiple HTTP requests?
    service.setProperty( Service.MULTIPLE_HTTP, new Boolean(false) );

    // Set cache timeout to 1 minute.
    Call call = service.createCall("testVector2", 1);

    Vector param = new Vector();
    param.addElement( new String("Vector test") );
    param.addElement( new String("success") );

    // Try sending a big request.
    for (int i = 0; i < 30; i++) {
      param.addElement( new String("More info") );
    }

    // Send true to get big response, false to get small response.
    Boolean param2 = new Boolean(true);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( param );
    params.addElement( param2 );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      
      try {
	      Vector respVec = res.getVector();
	
	      // Display the result of the call.
	      form.append( respVec.toString() + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }
  
  // Call a method that returns null.
  private void callNullService()
  {
    // Disable max request size (set it to 0).
    // Max request size is 0 (disabled) by default, but in this sample,
    // it may have been set by a call to callPieceService().
    service.setProperty( Service.MAX_REQUEST_SIZE, new Integer(0) );

    // Enable session support.
    // Session are enabled by default, but in this sample, they
    // may have been disabled by a call to callNoSession().
    service.setProperty( Service.SESSION_MAINTAIN, new Boolean(true) );

    // Set cache timeout to 1 minute.
    Call call = service.createCall("hellonull", 1);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new String("World") );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      
      try {
	      String respStr = res.getString();
	
	      // Display the result of the call.
	      form.append( respStr + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }


  // Call a method with a void return.
  // Caller knows when the method has a void return.
  private void callVoidService()
  {
    // Disable max request size (set it to 0).
    // Max request size is 0 (disabled) by default, but in this sample,
    // it may have been set by a call to callPieceService().
    service.setProperty( Service.MAX_REQUEST_SIZE, new Integer(0) );

    // Enable session support.
    // Session are enabled by default, but in this sample, they
    // may have been disabled by a call to callNoSession().
    service.setProperty( Service.SESSION_MAINTAIN, new Boolean(true) );

    // Set cache timeout to 0 minutes: never cache.
    Call call = service.createCall("hellovoid", 0);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new String("World") );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      
      try {
	      String respStr = res.getString();
	
	      // Display the result of the call.
	      form.append( respStr + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }
  

  // Make a normal remote procedure call,
  // but turn off session support.
  private void callNoSession()
  {
    // Disable max request size (set it to 0).
    // Max request size is 0 (disabled) by default, but in this sample,
    // it may have been set by a call to callPieceService().
    service.setProperty( Service.MAX_REQUEST_SIZE, new Integer(0) );

    // Disable session support.
    service.setProperty( Service.SESSION_MAINTAIN, new Boolean(false) );

    // Set cache timeout to 1 minute.
    Call call = service.createCall("hello", 1);

    // Put the parameters in a Vector.
    Vector params = new Vector();
    params.addElement( new String("World") );

    Response res = makeCall( call, params );

    // Continue only if response is not null.
    if (res != null) {
      
      try {
	      String respStr = res.getString();
	
	      // Display the result of the call.
	      form.append( respStr + "\n" );
      }
      catch (Exception e) {
	      // Display the error.
	      form.append( e.getMessage() + "\n" );
      }
    }
  }

  // Invoke a call.
  private Response makeCall( Call call, Vector params )
  {
    int retCode;
    String msg = null;
    
    Response response;

    if (call == null) {
      msg = "Call object is null!";
    }
    else {
      try {
	      //System.out.println("About to make call...");

	      // Make the remote method invokation.
	      // Response is returned.
	      response = call.invoke(params, false);
	
	      //System.out.println("Call made!");
	
	      if (response == null) {
	        //System.out.println("Response object is null!");
	        msg = "Response object is null.";
	      }
	      else {
	        // Check if the response is valid (0 = OK).
	        retCode = response.getReturnCode();
	  
	        //System.out.println("Return code is: " + retCode);
	  
	        if (retCode == 0) {
	          // Check if the returned object is null.
	          if (response.getObject() == null) {
	            msg = "Null or void return.";
	          }
	          else {
	            return response;
	          }
	        }
	        else {  // return code not 0
	          msg = "Call unsuccessful: " + response.getErrorMsg();
	        }
	      }
      }
      catch (ServiceException e) {
	      msg = "Error with code: " + e.getErrorCode() + ", message: " + e.getMessage();
      }
    }

    // Display the result of the call.
    form.append( msg + "\n" );

    return null;
  }


  // Clear ALL entries from the response cache.
  void clearCache()
  {
    try {
      ServiceManager sm = ServiceManager.getInstance();
      sm.clearCache();
      form.append( "Cache cleared.\n" );
    }
    catch (ServiceException e) {
      //System.out.println("Error clearing cache: " + e.getErrorCode() + " " + e.getMessage());
      form.append("Error with code: " + e.getErrorCode() + ", clearing cache, message: " + e.getMessage() + "\n");
    }
  }

  // Clear the screen.
  void clearScreen()
  {
    for (int i = (form.size() - 1); i >= 0; i--) {
      form.delete(i);
    }
  }


    class SimpleForm extends Form
    {
      SimpleForm() {
	      super( "Sample2" );

	      addCommand(exitCommand);
	      addCommand(goCommand);
	      addCommand(goPieceCommand);
	      addCommand(clearCCommand);
	      addCommand(clearSCommand);
	      addCommand(goNullCommand);
	      addCommand(goVoidCommand);
	      addCommand(goNoSessCommand);

	      setCommandListener(Sample2.this);
	    }
    }
}
