package examples.mega.client;

import java.rmi.RemoteException;

import weblogic.webservice.async.FutureResult;
import weblogic.webservice.async.AsyncInfo;
import weblogic.webservice.async.ResultListener;
import weblogic.webservice.async.InvokeCompletedEvent;

public class AsyncClient{

  private boolean gotCallback = false;

  public void invoke( SimpleTestSoap echoPort ) throws Exception{

    {//callback style 
      AsyncInfo wsContext = new AsyncInfo();

      wsContext.setResultListener( new ResultListener(){
        public void onCompletion( InvokeCompletedEvent event ){

          SimpleTestSoap source = (SimpleTestSoap)event.getSource();

          try{
            String result = source.endEchoString( event.getFutureResult() );
            weblogic.utils.Debug.say( "callback result: " + result ); 
            gotCallback = true;
          }catch( RemoteException e ){
            e.printStackTrace( System.out );
          }
        }
      });

      echoPort.startEchoString( "94501", wsContext );
    }
  
    {//normal sync invoke style 
      String result = echoPort.echoString( "94501" );
      weblogic.utils.Debug.say( "normal result: " + result );
    }

    {//async poll style 
      FutureResult futureResult = echoPort.startEchoString( "94501", null );

      while( !futureResult.isCompleted() ){
        weblogic.utils.Debug.say( "async polling  ..." );
        Thread.sleep( 300 );
      }

      String result = echoPort.endEchoString( futureResult );
      weblogic.utils.Debug.say( "poll result: " + result ); 
    }

    {//sync invoke using async style
      FutureResult futureResult = echoPort.startEchoString( "94501", null );
      String result = echoPort.endEchoString( futureResult );
      weblogic.utils.Debug.say( "sync result: " + result );
    }

    while( !gotCallback ){
      weblogic.utils.Debug.say( "waiting  for result ..." );
      Thread.sleep( 300 );
    }
  }
}

