package tutorial.sample23;

import java.util.Iterator;

import java.io.IOException;

import javax.xml.namespace.QName;

import javax.xml.rpc.JAXRPCException;
import javax.xml.rpc.handler.GenericHandler;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;

import javax.xml.soap.Name;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.MessageFactory;

public class RouterHandler extends GenericHandler{

  private HandlerInfo config;
  private String targetURL;

  public void init( HandlerInfo config ){
    this.config = config;
    targetURL = (String)config.getHandlerConfig().get( "target-url" );
  }

  public QName[] getHeaders(){
    return config.getHeaders();
  }

  public boolean handleRequest(MessageContext mc){
    SOAPMessageContext ctx = (SOAPMessageContext)mc;
    SOAPMessage request = ctx.getMessage();

    try{
      System.out.println( "handleRequest Called ............." );
      request.writeTo( System.out );
      SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
      SOAPConnection connection = factory.createConnection();
      SOAPMessage response = connection.call( request, targetURL );
      ctx.setMessage( response );
    }catch( SOAPException e ){
      sendFault( ctx, e );
    }catch( IOException e ){
      sendFault( ctx, e );
    }

    return true;
  }

  private void sendFault( SOAPMessageContext ctx, Throwable th ){
    try{
      MessageFactory factory = MessageFactory.newInstance();
      SOAPMessage response = factory.createMessage();

      SOAPFault fault = 
        response.getSOAPPart().getEnvelope().getBody().addFault();

      fault.setFaultCode( "Server.Unknown" );
      fault.setFaultString( "Router failed due to: " + th );

      ctx.setMessage( response );
    }catch( SOAPException e ){
      weblogic.utils.Debug.say( "(manoj):handle fault " + e );
    }
  }

  public boolean handleResponse( MessageContext mc ){
    System.out.println( "handleResponse Called ............." );
    SOAPMessageContext ctx = (SOAPMessageContext)mc;
    SOAPMessage response = ctx.getMessage();

    try{
      response.writeTo( System.out );
    }catch( SOAPException e ){
      weblogic.utils.Debug.say( "(manoj):handle exception:" + e );
    }catch( IOException e ){
      weblogic.utils.Debug.say( "(manoj):handle exception:" + e );
    }

    return true;
  }

}

