/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, 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.soa.bpel.tests;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.management.MBeanServerConnection;
import javax.naming.NamingException;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;

import org.jboss.logging.Logger;

/**
 * A test setup that deploys/undeploys archives
 *
 * @author Thomas.Diesler@jboss.org
 * @since 14-Oct-2004
 */
public class RiftSawTestSetup extends TestSetup
{
   // provide logging
   private static Logger log = Logger.getLogger(RiftSawTestSetup.class);

   private RiftSawTestHelper delegate = new RiftSawTestHelper();
   private String[] archives = new String[0];
   private ClassLoader originalClassLoader;
   private String m_testName=null;

   public RiftSawTestSetup(Class<?> testClass, String testName, String archiveList) {
      super(new TestSuite(testClass));
      getArchiveArray(archiveList);
      m_testName = testName;
   }

   public RiftSawTestSetup(Test test, String archiveList)
   {
      super(test);
      getArchiveArray(archiveList);
   }

   public RiftSawTestSetup(Test test)
   {
      super(test);
   }

   public File getArchiveFile(String archive)
   {
      return delegate.getTestFile(m_testName, archive);
   }

   public URL getArchiveURL(String archive) throws MalformedURLException
   {
      return delegate.getTestFile(m_testName, archive).toURL();
   }

   private void getArchiveArray(String archiveList)
   {
      if (archiveList != null)
      {
         StringTokenizer st = new StringTokenizer(archiveList, ", ");
         archives = new String[st.countTokens()];

         for (int i = 0; i < archives.length; i++)
            archives[i] = st.nextToken();
      }
   }

   protected void setUp() throws Exception {

      List<URL> clientJars = new ArrayList<URL>();
      for (int i = 0; i < archives.length; i++)
      {
         String archive = archives[i];
         try
         {
            delegate.deploy(m_testName, archive);
         }
         catch (Exception ex)
         {
            ex.printStackTrace();
            delegate.undeploy(m_testName, archive);
         }

         if (archive.endsWith("-client.jar"))
         {
            URL archiveURL = getArchiveURL(archive);
            clientJars.add(archiveURL);
         }
      }

      ClassLoader parent = Thread.currentThread().getContextClassLoader();
      originalClassLoader = parent;
      // add client jars to the class loader
      if (!clientJars.isEmpty())
      {
         URL[] urls = new URL[clientJars.size()];
         for (int i = 0; i < clientJars.size(); i++)
         {
            urls[i] = clientJars.get(i);
         }
         URLClassLoader cl = new URLClassLoader(urls, parent);
         Thread.currentThread().setContextClassLoader(cl);
      }
      
      // Temporary wait until able to sync detect deployed ok
		try {
			synchronized(this) {
				wait(40* 1000);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}

   }

   protected void tearDown() throws Exception
   {
	   
	   // Temporarily move the deployed files - this is to ensure the server actually undeploys
	   // the archive
	   java.util.Map<java.io.File, java.io.File> mapping=new java.util.HashMap<java.io.File, java.io.File>();

	      try
      {
         for (int i = 0; i < archives.length; i++)
         {
            String archive = archives[archives.length - i - 1];

            java.io.File file=delegate.getTestFile(m_testName, archive);
            
            URL archiveURL = file.toURL();
            
	         java.io.File newfile=new java.io.File(file.getParentFile(), "_"+file.getName());
	         file.renameTo(newfile);
	         
	         mapping.put(newfile, file);
	         
            delegate.undeploy(m_testName, archiveURL);
            
         }
      }
      finally
      {
         Thread.currentThread().setContextClassLoader(originalClassLoader);
      }
      
      // Temporary wait until able to sync detect deployed ok
		try {
			synchronized(this) {
				wait(3000);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		// Move files back to original location
	      for (java.io.File file : mapping.keySet()) {
	         java.io.File newfile=mapping.get(file);
	         file.renameTo(newfile);    
	      }
   }

   public MBeanServerConnection getServer() throws NamingException
   {
      return RiftSawTestHelper.getServer();
   }
}
