/*
* JBoss, Home of Professional Open Source
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.test.webservice.jbws83;

import javax.xml.namespace.QName;
import javax.xml.rpc.handler.GenericHandler;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.handler.soap.SOAPMessageContext;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import org.jboss.logging.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ClientHandler extends GenericHandler
{
   // provide logging
   private static final Logger log = Logger.getLogger(ClientHandler.class);
   
   protected QName[] headers;

   public QName[] getHeaders()
   {
      return headers;
   }

   public boolean handleRequest(MessageContext msgContext)
   {
      try
      {
         processMessage(msgContext);
         return true;
      }
      catch (RuntimeException rte)
      {
         throw rte;
      }
      catch (Exception e)
      {
         throw new IllegalArgumentException(e.toString());
      }
   }

   public boolean handleResponse(MessageContext msgContext)
   {
      try
      {
         processMessage(msgContext);
         return true;
      }
      catch (RuntimeException rte)
      {
         throw rte;
      }
      catch (Exception e)
      {
         throw new IllegalArgumentException(e.toString());
      }
   }

   /** Process request/response message
    */
   private void processMessage(MessageContext msgContext) throws SOAPException, IOException
   {
      SOAPMessageContext soapContext = (SOAPMessageContext)msgContext;
      SOAPMessage soapMessage = soapContext.getMessage();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      soapMessage.writeTo(baos);
      String msgStr = new String(baos.toByteArray());

      log.debug(msgStr);

      String expElement = "<my-msg>Kermit</my-msg>";
      if (msgStr.indexOf(expElement) < 0)
         throw new SOAPException("Cannot find " + expElement + " in SOAPMessage");
   }
}
