/**
 * User: Clinton Begin
 * Date: Jul 24, 2003
 * Time: 8:13:12 PM
 */
package com.ibatis.jpetstore.service;

import com.ibatis.jpetstore.domain.*;
import com.ibatis.common.resources.*;
import org.apache.axis.client.*;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.*;

import javax.xml.rpc.*;
import javax.xml.namespace.*;
import java.util.*;
import java.io.*;

public class PetStoreClient {

  private static final String orderServiceEndpoint;

  static {
    try {
      Properties props = Resources.getResourceAsProperties("properties/petstore.properties");
      orderServiceEndpoint = props.getProperty("orderServiceEndpoint");
    } catch (IOException e) {
      throw new RuntimeException ("Could not configure PetStoreClient.  There was a problem retrieving the Order Service Endpoint (orderServiceEndpoint).");
    }
  }

  public Order getOrder(int orderId) throws Exception {

    // Create JAX-RPC setup
    Service service = new Service();
    Call call = (Call) service.createCall();

    call.setTargetEndpointAddress(
        new java.net.URL(orderServiceEndpoint));

    // Define the Order bean
    registerTypeMapping(call, "Product", Product.class);
    registerTypeMapping(call, "Item", Item.class);
    registerTypeMapping(call, "LineItem", LineItem.class);
    QName orderQname = registerTypeMapping(call, "Order", Order.class);


    call.setOperationName("getOrder");
    call.addParameter("orderNumber", XMLType.XSD_INT, ParameterMode.IN);
    call.setReturnType(orderQname);

    Object[] params = new Object[]{new Integer(orderId)};
    Order order = (Order) call.invoke(params);
    return order;

  }

  private QName registerTypeMapping(Call call, String name, Class type) {
    QName qn = new QName("urn:BeanService", name);
    call.registerTypeMapping(type, qn,
        new org.apache.axis.encoding.ser.BeanSerializerFactory
            (type, qn),
        new org.apache.axis.encoding.ser.BeanDeserializerFactory
            (type, qn));
    return qn;
  }

}
