/*
 * Created on 19.11.2003
 *
 * (c) Stabsstelle IKT-Strategie des Bundes
 */
package at.gv.egovernment.moa.spss.slinterface.moainvoker;

import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.Vector;

import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.ServiceFactory;

import org.apache.axis.message.SOAPBodyElement;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;

import at.gv.egovernment.moa.spss.slinterface.Constants;

/**
 * @author Gregor Karlinger (mailto:gregor.karlinger@cio.gv.at) 
 */
public class MOAInvoker
{
  /**
   * Invokes MOA SP.
   * 
   * @param request The XML request to be sent to MOA SP.
   * 
   * @param endpoint The endpoint of the SOAP service where to send the XML request to. 
   * 
   * @return the XML response from the service.
   * 
   * @throws Exception if getting the XML response from the SOAP response body fails.
   * 
   * @throws RemoteException if MOA SP signals an error.
   * 
   * @throws ServiceException if the SOAP client invoking MOA SP signals an error.
   */
  public static Document invokeSP(Document request, String endpoint) 
    throws Exception, RemoteException, ServiceException
  {
    QName serviceQName = new QName(Constants.MI_SP_QNAME_);
    return invoke(request, endpoint, serviceQName);
  }
 
  /* ---------------------------------------------------------------------------------------------------- */

  private static Document invoke(Document request, String endpoint, QName serviceQName) throws Exception
  {
    // Instantiate AXIS service
    Service service = ServiceFactory.newInstance().createService(serviceQName);
      
    // Create and configure service call
    Call call = service.createCall();
    call.setTargetEndpointAddress(endpoint);
      
    // Create SOAP body
    SOAPBodyElement body = new SOAPBodyElement(request.getDocumentElement());
    SOAPBodyElement[] params = new SOAPBodyElement[] {body};
      
    // Make call
    Vector responses = (Vector) call.invoke(params);
      
    // Get response
    SOAPBodyElement responseBody = (SOAPBodyElement) responses.get(0);
    Document response = responseBody.getAsDocument();
    return response;
  }
 
  /* ---------------------------------------------------------------------------------------------------- */

  public static void serializeDocument(Document doc, OutputStream out) throws IOException
  {
    OutputFormat format = new OutputFormat(doc);

    format.setLineSeparator("\n");
    format.setIndenting(false);
    format.setPreserveSpace(true);
    format.setOmitXMLDeclaration(false);
    format.setEncoding("UTF-8");
  
    XMLSerializer serializer = new XMLSerializer(out, format);
    serializer.serialize(doc);
  }
}