package com.sams.jws.chapter18;
import java.util.Vector;
import java.net.URL;
import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.SOAPException;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;

public class TimeServerClient {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://localhost:8080/soap/servlet/rpcrouter");
        String operationName = null;
        if (args.length == 0) {
            operationName = "synchronizeTime";
        } else if (args.length == 1) {
            operationName = "getTimeAtCity";
        } else {
            String className = TimeServerClient.class.getName();
            System.err.println("Usage: java " + className + " [zoneName]");
            System.err.println(
                "Eg: java "
                    + className
                    + "\t- Returns server system time as a long in units of millisec since epoch");
            System.err.println(
                "    java "
                    + className
                    + " America/Vancouver \t- Returns server's perspective on current date and time in Vancouver as a string");
            System.exit(0);
        }

        String encodingStyleURI = Constants.NS_URI_SOAP_ENC;

        // Build generic call.
        Call call = new Call();
        call.setTargetObjectURI("urn:TimeServer");
        call.setEncodingStyleURI(encodingStyleURI);

        // Set input argument for getTimeAtCity
        if (operationName.equals("getTimeAtCity")) {
            String zoneName = args[0];
            Vector parameters = new Vector();
            parameters.addElement(new Parameter("zoneName", String.class, zoneName, null));
            call.setParams(parameters);
        }
        // Build and execute call to synchronizeTime()
        call.setMethodName(operationName);

        Response response;
        try {
            response = call.invoke(url, "");
        } catch (SOAPException e) {
            System.err.println("Caught SOAPException:");
            e.printStackTrace();
            return;
        }

        // Check the response.
        if (!response.generatedFault()) {
            Parameter returnParam = response.getReturnValue();
            Object value = returnParam.getValue();
            System.out.println("Return value for " + operationName + "() is: " + value);

        } else {
            Fault fault = response.getFault();

            System.err.println("Caught fault: ");
            System.err.println("Code:" + fault.getFaultCode());
            System.err.println("Fault string: " + fault.getFaultString());
        }
        System.out.println("Done.");
    } // main()
} // Class TimeServerClient