/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt 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.smoke.tools;

import org.jboss.wsf.common.DOMUtils;
import org.jboss.wsf.spi.tools.WSContractProvider;
import org.jboss.wsf.test.JBossWSTest;
import org.w3c.dom.Element;

import javax.xml.bind.annotation.XmlRootElement;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author Heiko.Braun@jboss.com
 * @version $Revision: 14403 $
 */
public class WSProviderTestCase extends JBossWSTest
{
   // tools delegate
   WSContractProvider provider;

   // redirect tools message to System.out ? 
   boolean toogleMessageOut = false;

   // relative to test execution
   File outputDirectory;

   protected void setUp() throws Exception
   {
      super.setUp();

       // create a new consumer for every test case
      provider = WSContractProvider.newInstance();
      if(toogleMessageOut) provider.setMessageStream(System.out);

      // shared output directory, relative to test execution
      outputDirectory = new File("wsprovide/java");
      
   }

   private ClassLoader getArtefactClassLoader() throws Exception {
      URLClassLoader loader = new URLClassLoader(new URL[] {
        new URL("file:"+System.getProperty("user.dir")+"/wsprovide/java/") }
      );

      return loader;
   }

   /**
    * Enables/Disables WSDL generation.
    *
    */
   public void testGenerateWsdl() throws Exception
   {
      provider.setGenerateWsdl(true);
      provide();

      verifyWSDL(outputDirectory);
   }
   
   public void testGenerateWsdlWithExtension() throws Exception
   {
      provider.setGenerateWsdl(true);
      provider.setExtension(true);
      File outputDir = new File(outputDirectory.getAbsolutePath() + "/soap12");
      provider.setOutputDirectory(outputDir);
      provider.provide(CalculatorBean.class);

      verifyWSDL(outputDir, true);
   }

   /**
    * Enables/Disables Java source generation.
    *
    */
   public void testGenerateSource() throws Exception
   {
      provider.setGenerateSource(true);
      provide();

      verifyJavaSource(outputDirectory);

   }

   private void verifyJavaSource(File directory)
   {
      File javaSource = new File(
        directory.getAbsolutePath()+
          "/org/jboss/test/ws/jaxws/smoke/tools/jaxws/AddResponse.java"
        );

      assertTrue("Source not generated", javaSource.exists());
   }

   /**
    * Sets the main output directory.
    * If the directory does not exist, it will be created.    
    */
   public void testOutputDirectory() throws Exception
   {
      provide();
      ClassLoader loader = getArtefactClassLoader();
      Class responseWrapper = loader.loadClass("org.jboss.test.ws.jaxws.smoke.tools.jaxws.AddResponse");
      XmlRootElement rootElement = (XmlRootElement) responseWrapper.getAnnotation(XmlRootElement.class);
      assertNotNull("@XmlRootElement missing form response wrapper", rootElement);
      assertEquals("Wrong namespace", rootElement.namespace(), "http://foo.bar.com/calculator");
   }

   /**
    * Sets the resource directory. This directory will contain any generated
    * WSDL and XSD files. If the directory does not exist, it will be created.
    * If not specified, the output directory will be used instead.
    *     
    */
   public void testResourceDirectory() throws Exception
   {
      File directory = new File("wsprovide/resources");
      provider.setResourceDirectory(directory);
      provide();

      verifyWSDL(this.outputDirectory);
   }

   private void verifyWSDL(File directory) throws Exception
   {
      verifyWSDL(directory, false);
   }
   
   private void verifyWSDL(File directory, boolean soap12) throws Exception
   {
      
      File wsdl = new File(directory.getAbsolutePath() + "/CalculatorBeanService.wsdl");
      assertTrue("WSDL not generated", wsdl.exists());
      Element root = DOMUtils.parse(new FileInputStream(wsdl));
      Element serviceElement = DOMUtils.getFirstChildElement(root, "service");
      assertEquals(serviceElement.getAttribute("name"), "CalculatorBeanService");
      Element bindingElement = DOMUtils.getFirstChildElement(root, "binding");
      Element soapBindingElement = DOMUtils.getFirstChildElement(bindingElement, "binding");
      if (soap12)
      {
         assertEquals("http://schemas.xmlsoap.org/wsdl/soap12/", soapBindingElement.getNamespaceURI());
      }
      else
      {
         assertEquals("http://schemas.xmlsoap.org/wsdl/soap/", soapBindingElement.getNamespaceURI());
      }
   }

   /**
    * Sets the source directory. This directory will contain any generated Java source.
    * If the directory does not exist, it will be created. If not specified,
    * the output directory will be used instead.
    *
    */
   public void testSourceDirectory() throws Exception
   {
      File sourceDir = new File("wsprovide/sources");
      provider.setSourceDirectory(sourceDir);
      provider.setGenerateSource(true);
      provide();

      verifyJavaSource(sourceDir);
   }

   /**
    * Sets the ClassLoader used to discover types.
    * This defaults to the one used in instantiation.
    *
    */
   public void testClassLoader()
   {
      System.out.println("FIXME [JBWS-1776]: Verify isolated classloading with WSProvide");
   }

   /**
    * Sets the PrintStream to use for status feedback. The simplest example
    * would be to use System.out.
    *
    */
   public void testMessageStream() throws Exception
   {

      if(isIntegrationSunRI())
      {
         System.out.println("FIXME [JBWS-1777]: WSProvide output is not correctly redirected");
         return;
      }

      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      PrintStream pout = new PrintStream(bout);

      provider.setMessageStream(pout);
      provide();

      String messageOut = new String(bout.toByteArray());
      
      System.out.println("-- Begin captured output --");
      System.out.println(messageOut);
      System.out.println("-- End captured output --");

      assertTrue("Provider messages not correctly redirected",
        messageOut.indexOf("org/jboss/test/ws/jaxws/smoke/tools/jaxws/Add.class") != -1 );
   }

   private void provide() throws Exception
   {
      //provider.setGenerateSource(true);
      provider.setOutputDirectory(outputDirectory);
      provider.provide(CalculatorBean.class);
   }

	 /**
    * Filter sun jaxws implementation because it clashes
    * with the native one (ServiceLoader...)
    * @param jarName
    * @return
    */
   protected boolean filtered(String jarName)
   {
      return (isIntegrationNative() &&
        (jarName.indexOf("jaxws-rt")!=-1 || jarName.indexOf("jaxws-tools")!=-1)
        );
   }

}