package WShandler;

import java.util.Iterator;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.soap.SOAPElement;
import javax.xml.rpc.handler.HandlerInfo;
import javax.xml.rpc.handler.GenericHandler;
import javax.xml.namespace.QName;

/**
* Purpose: Log all messages to the Server console 
*/
public class WShandler extends GenericHandler 
{
  HandlerInfo hinfo = null;

  public void init (HandlerInfo hinfo) {
    this.hinfo = hinfo;
    System.out.println("*****************************");
    System.out.println("ConsoleLoggingHandler r: init");
    System.out.println(
          "ConsoleLoggingHandler : init HandlerInfo" + hinfo.toString());
    System.out.println("*****************************");
   }

   /**
    * Handles incoming web service requests and outgoing callback requests
   */
   public boolean handleRequest(MessageContext mc) {
          logSoapMessage(mc, "handleRequest");
          return true;
    }

    /**
    * Handles outgoing web service responses and 
    * incoming callback responses
    */
    public boolean handleResponse(MessageContext mc) {
       this.logSoapMessage(mc, "handleResponse");
       return true;
    }

    /**
    * Handles SOAP Faults that may occur during message processing
    */
    public boolean handleFault(MessageContext mc){
      this.logSoapMessage(mc, "handleFault");
      return true;
    }

    public QName[] getHeaders() {
      QName [] qname = null;
      return qname;
    }

     /**
     * Log the message to the server console using System.out
     */
     protected void logSoapMessage(MessageContext mc, String eventType){
      try{
        System.out.println("*****************************");
        System.out.println("Event: "+eventType);
        System.out.println("*****************************");
       }
       catch( Exception e ){
         e.printStackTrace();
       }
     }

     /**
     * Get the method Name from a SOAP Payload.
     */
     protected String getMethodName(MessageContext mc){

       String operationName = null;

       try{
         SOAPMessageContext messageContext = (SOAPMessageContext) mc;
         // assume the operation name is the first element
         // after SOAP:Body element
         Iterator i = messageContext.
              getMessage().getSOAPPart().getEnvelope().getBody().getChildElements();
         while ( i.hasNext() )
         {
           Object obj = i.next();
           if(obj instanceof SOAPElement)
           {
             SOAPElement e = (SOAPElement) obj;
             operationName = e.getElementName().getLocalName();
             break;
           }
         }
       }
       catch(Exception e){
         e.printStackTrace();
       }
         return operationName;
     }
  }