/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2010, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.ws.jaxws.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.jboss.logging.Logger;
import org.jboss.wsf.common.DOMUtils;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Dispatch;

public final class JAXWS_Util
{
   private static final Logger log = Logger.getLogger(JAXWS_Util.class);

   public static DOMResult getSourceAsDOMResult(Source s) throws Exception
   {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMResult result = new DOMResult();
      transformer.transform(s, result);
      return result;
   }

   public static String getDOMResultAsString(DOMResult dr) throws Exception
   {
      DOMSource ds = new DOMSource(dr.getNode());
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      Writer out = new StringWriter();
      StreamResult streamResult = new StreamResult();
      streamResult.setWriter(out);
      transformer.transform(ds, streamResult);
      return streamResult.getWriter().toString();
   }

   public static void dumpSOAPMessage(final SOAPMessage msg, final boolean logOnly)
   {
      final StringBuilder sb = new StringBuilder();

      try
      {
         sb.append("--------------------\n");
         sb.append("DUMP OF SOAP MESSAGE\n");
         sb.append("--------------------\n");
         String soapMsgString = DOMUtils.node2String(msg.getSOAPPart());
         sb.append(soapMsgString);
      }
      catch (Exception e)
      {
         log.error(e.getMessage(), e);
         e.printStackTrace();
      }

      if (logOnly)
      {
         log.debug(sb.toString());
      }
      else
      {
         System.err.print(sb.toString());
      }
   }

   public static Source makeSource(String msg, String type)
   {
      Reader reader = new StringReader(msg);
      if (type.equals("StreamSource"))
         return new StreamSource(reader);
      else if (type.equals("DOMSource"))
         return new DOMSource(createDOMNode(reader));
      else if (type.equals("SAXSource"))
         return new SAXSource(new InputSource(reader));
      else
         return null;
   }

   public static Node createDOMNode(Reader reader)
   {

      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setValidating(false);
      try
      {
         DocumentBuilder builder = dbf.newDocumentBuilder();
         try
         {
            return builder.parse(new InputSource(reader));
         }
         catch (SAXException e)
         {
            e.printStackTrace();
         }
         catch (IOException e)
         {
            e.printStackTrace();
         }
      }
      catch (ParserConfigurationException pce)
      {
         IllegalArgumentException iae = new IllegalArgumentException(pce.getMessage());
         iae.initCause(pce);
         throw iae;
      }
      return null;
   }

   public static SOAPMessage makeSOAPMessage(String msg)
   {
      try
      {
         Source srcMsg = makeSource(msg, "StreamSource");
         MessageFactory factory = MessageFactory.newInstance();
         SOAPMessage message = factory.createMessage();
         message.getSOAPPart().setContent((Source) srcMsg);
         message.saveChanges();
         return message;
      }
      catch (Exception e)
      {
         return null;
      }
   }

   public static String getSOAPMessageAsString(SOAPMessage message)
   {
      return getMsgAsString(message);
   }

   public static String getMsgAsString(SOAPMessage message)
   {
      String msg = null;
      try
      {
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         message.writeTo(baos);
         msg = baos.toString();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      return msg;
   }

   public static void setSOAPACTIONURI(Object o, String action)
   {
      BindingProvider bp = (BindingProvider) o;
      Map<String, Object> requestContext = bp.getRequestContext();
      if (requestContext == null)
      {
         log.error("setSOAPACTIONURI:getRequestContext() returned null");
         throw new IllegalStateException();
      }
      else
      {
         requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, action);
         requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, true);
         log.debug("SOAPACTION_USE_PROPERTY being set to: "
               + requestContext.get(BindingProvider.SOAPACTION_USE_PROPERTY));
         log.debug("SOAPACTION_URI_PROPERTY being set to: "
               + requestContext.get(BindingProvider.SOAPACTION_URI_PROPERTY));
      }
   }
}
