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

import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.jboss.aop.AOPClassPool;
import org.jboss.aop.AspectManager;
import org.jboss.aop.ClassPoolFactory;
import org.jboss.mx.loading.RepositoryClassLoader;
import javassist.ClassPool;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.3.2.3 $
 *
 **/
public class JBossClassPoolFactory implements ClassPoolFactory
{
   protected File tmpClassesDir;

   public JBossClassPoolFactory(File tmpClassesDir) throws IOException
   {
      this.tmpClassesDir = tmpClassesDir;

   }
   public AOPClassPool create(ClassLoader cl, ClassPool src, AspectManager manager)
   {
      try
      {
         if (cl instanceof RepositoryClassLoader)
         {
            File tempdir = createTempDir(cl);
            return new JBossClassPool(cl, src, manager, tempdir);
         }
         return new AOPClassPool(cl, src, manager);
      }
      catch (IOException e)
      {
         throw new RuntimeException(e);
      }
   }

   public AOPClassPool create(ClassPool src, AspectManager manager)
   {
      return new JBossClassPool(src, manager);
   }

   public File createTempDir(ClassLoader cl) throws IOException
   {
      File tempdir = File.createTempFile("ucl", "", tmpClassesDir);
      tempdir.delete();
      tempdir.mkdir();
      tempdir.deleteOnExit();
      RepositoryClassLoader ucl = (RepositoryClassLoader) cl;
      URL tmpURL = tempdir.toURL();
      URL tmpCP = new URL(tmpURL, "?dynamic=true");

      // We may be undeploying.
      if (ucl.getLoaderRepository() != null) ucl.addURL(tmpCP);
      return tempdir;
   }

}
