package samples.simple;

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

/**
 * See README for info.
 *
 * @author Sanjiva Weerawarana (sanjiva@watson.ibm.com)
 */
public class GetQuote {
  public static void main (String[] args) throws Exception {
    if (args.length != 2
        && (args.length != 3 || !args[0].startsWith ("-"))) {
      System.err.println ("Usage: java " + GetQuote.class.getName () +
                          " [-encodingStyleURI] SOAP-router-URL symbol");
      System.exit (1);
    }

    // Process the arguments.
    int offset = 3 - args.length;
    String encodingStyleURI = args.length == 3
                              ? args[0].substring(1)
                              : Constants.NS_URI_SOAP_ENC;
    URL url = new URL (args[1 - offset]);
    String symbol = args[2 - offset];

    // Build the call.
    Call call = new Call ();
    call.setTargetObjectURI ("urn:simple:stockQuoteService#stockQuoteServiceBP#caller#urn:simple:stockQuoteService#StockQuotePT");
    call.setMethodName ("gimmeQuote");
    call.setEncodingStyleURI(encodingStyleURI);
    Vector params = new Vector ();
    params.addElement (new Parameter("symbol", String.class, symbol, null));
    call.setParams (params);

    // make the call: note that the action URI is empty because the 
    // XML-SOAP rpc router does not need this. This may change in the
    // future.
    Response resp = call.invoke (/* router URL */ url, /* actionURI */ "" );

    // Check the response.
    if (resp.generatedFault ()) {
      Fault fault = resp.getFault ();
      System.out.println ("Ouch, the call failed: ");
      System.out.println ("  Fault Code   = " + fault.getFaultCode ());  
      System.out.println ("  Fault String = " + fault.getFaultString ());
      System.out.println ("  Fault        = " + fault);
    } else {
      Parameter result = resp.getReturnValue ();
      if (result != null)
	System.out.println(result.getValue());
      else
	System.out.println("No response was returned.  Perhaps there was an error with the flow.");
    }
  }
}
