/*
* JBoss, the OpenSource J2EE webOS
*
* 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 java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ClientHandler extends GenericHandler
{
   protected QName[] headers;

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

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

   public boolean handleResponse(MessageContext msgContext)
   {
      try
      {
         processMessage(msgContext);
         return true;
      }
      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());

      System.out.println(msgStr);

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