/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.webservice.wsdlimport;

// $Id: SimpleFileImportTestCase.java,v 1.1.2.1 2004/11/09 16:54:09 tdiesler Exp $

import junit.framework.TestCase;
import org.jboss.net.protocol.URLStreamHandlerFactory;
import org.jboss.webservice.WSDLDefinitionFactory;

import javax.wsdl.Definition;
import javax.xml.namespace.QName;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import java.io.File;
import java.net.URL;

/**
 * Test a wsdl import functionality.
 * 
 * @author Thomas.Diesler@jboss.org
 * @since 11-May-2004
 */
public class SimpleFileImportTestCase extends TestCase
{
   public static final String WSDL_LOCATION = "resources/webservice/wsdlimport/simplefile/SimpleFile.wsdl";

   public SimpleFileImportTestCase(String name)
   {
      super(name);
   }

   public void testFileURL() throws Exception
   {
      File wsdlFile = new File(WSDL_LOCATION);
      assertTrue("File does not exist: " + wsdlFile.getCanonicalPath(), wsdlFile.exists());

      // Setting the URLStreamHandlerFactory simulates the behaviour in JBoss
      internalInitURLHandlers();

      URL wsdlURL = wsdlFile.toURL();
      Definition wsdlDefinition = WSDLDefinitionFactory.newInstance().parse(wsdlURL);
      assertNotNull(wsdlDefinition);

      QName serviceName = (QName)wsdlDefinition.getServices().keySet().iterator().next();

      // test construction of the client service
      ServiceFactory serviceFactory = ServiceFactory.newInstance();
      Service service = serviceFactory.createService(wsdlURL, serviceName);
      assertNotNull(service);
   }

   /**
    * Set up our only URLStreamHandlerFactory.
    * This is needed to ensure Sun's version is not used (as it leaves files
    * locked on Win2K/WinXP platforms.
    */
   private void internalInitURLHandlers()
   {
      // Install a URLStreamHandlerFactory that uses the TCL
      URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory());

      // Preload JBoss URL handlers
      URLStreamHandlerFactory.preload();

      // Include the default JBoss protocol handler package
      String handlerPkgs = System.getProperty("java.protocol.handler.pkgs");
      if (handlerPkgs != null)
      {
         handlerPkgs += "|org.jboss.net.protocol";
      }
      else
      {
         handlerPkgs = "org.jboss.net.protocol";
      }
      System.setProperty("java.protocol.handler.pkgs", handlerPkgs);
   }
}