package org.fireproject.axissample;

import java.io.StringWriter;
import java.util.Calendar;
import java.util.Vector;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;

import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.soap.SOAPConstants;
import org.apache.axis.utils.XMLUtils;

public class DateFormatClient {
    /**
     * 指定されたURL,メソッド名にてWebサービスを呼び出す.
     * 
     * @param args [0]:URL
     *
     */
    public static void main(String [] args) {
	if (args.length < 1) {
	    printUsage();
	    System.exit(1);
	}
	String endpoint = args[0];

	try {
	    Service service = new Service();
	    Call call = (Call)service.createCall();
	    call.setTargetEndpointAddress(new java.net.URL(endpoint));

	    SOAPBodyElement[] input = new SOAPBodyElement[1];
	    input[0] = createReqSOAPBodyElement();

            Object result = call.invoke(input);

	    System.out.println("className of result = " + result.getClass().getName());
	    System.out.println("result.size = " + ((Vector)result).size());
	    System.out.println("className of result[0] = " + ((Vector)result).get(0).getClass().getName());
	    System.out.println("result = " + result);

	    MessageContext context = call.getMessageContext();
	    Message res = context.getResponseMessage();
	    SOAPEnvelope resEnvelope = res.getSOAPEnvelope();
	    SOAPBodyElement resBody = resEnvelope.getFirstBody();

	    StringWriter writer = new StringWriter();
	    XMLUtils.ElementToWriter(resBody, writer);
	    System.out.println("elementBody = " + writer.toString());

	} catch (Exception e) {
	    System.err.println(e.toString());
	    e.printStackTrace();
	    System.exit(1);
	}

	System.exit(0);
    }

    /**
     * 要求用SOAP電文Body作成.
     * &lt;Request&gt;
     *   &lt;parameter&gt;
     *     &lt;value&gt;システム日付のミリ秒&lt;/value&gt;
     *     &lt;format&gt;日付フォーマット&lt;/format&gt;
     *   &lt;/parameter&gt;
     * &lt;/Request&gt;
     * @return 要求用SOAP電文Body
     *
     */
    private static SOAPBodyElement createReqSOAPBodyElement() throws SOAPException { 
	SOAPBodyElement resultElement = new SOAPBodyElement();
	resultElement.setQName(new QName("", "requestMessage"));
	SOAPElement parameterElement = resultElement.addChildElement("parameter");
	SOAPElement valueElement = parameterElement.addChildElement("value");
	valueElement.addTextNode(Long.toString(Calendar.getInstance().getTimeInMillis()));
	SOAPElement formatElement = parameterElement.addChildElement("format");
	formatElement.addTextNode("yyyy-MM-dd");
	return resultElement;
    }

    /**
     * 使用方法出力メソッド
     *
     */
    private static void printUsage() {
	System.err.println("Specify target url(example : http://servername/context/services/serivceName).");
    }

}