/*
 * 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.FileOutputStream;
import org.jboss.aop.AOPClassPool;
import org.jboss.aop.AspectManager;
import org.jboss.mx.loading.RepositoryClassLoader;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.8.2.3 $
 */
public class JBossClassPool extends AOPClassPool
{
   /**
    * Used for dynamically created classes (see loadClass(String, byte[]), ClassLoader)
    */
   protected File tempdir = null;
   // For loadClass tmpdir creation for UCL
   protected final Object tmplock = new Object();

   protected JBossClassPool(ClassLoader cl, ClassPool src, AspectManager manager, File tmp)
   {
      super(cl, src, manager);
      tempdir = tmp;
   }

   protected JBossClassPool(ClassPool src, AspectManager manager)
   {
      super(src, manager);
   }

   public boolean isUnloadedClassLoader()
   {
      if (dcl instanceof RepositoryClassLoader)
      {
         RepositoryClassLoader rcl = (RepositoryClassLoader) dcl;
         return rcl.getLoaderRepository() == null;
      }
      return false;
   }

   

   public Class toClass(CtClass cc, ClassLoader loader)
   throws CannotCompileException
   {
      lockInCache(cc);
      if (dcl == null || tempdir == null)
      {
         return super.toClass(cc);
      }
      Class dynClass = null;
      try
      {
         File classFile = null;
         String classFileName = cc.getName().replace('.', '/') + ".class";
         // Write the clas file to the tmpdir
         synchronized (tmplock)
         {
            classFile = new File(tempdir, classFileName);
            File pkgDirs = classFile.getParentFile();
            pkgDirs.mkdirs();
            FileOutputStream stream = new FileOutputStream(classFile);
            stream.write(cc.toBytecode());
            stream.flush();
            stream.close();
            classFile.deleteOnExit();
         }
         // We have to clear Blacklist caches or the class will never
         // be found
         //((UnifiedClassLoader)dcl).clearBlacklists();
         // To be backward compatible
         RepositoryClassLoader rcl = (RepositoryClassLoader) dcl;
         rcl.clearClassBlackList();
         rcl.clearResourceBlackList();

         // Now load the class through the cl
         dynClass = dcl.loadClass(cc.getName());
      }
      catch (Exception ex)
      {
         ClassFormatError cfe = new ClassFormatError("Failed to load dyn class: " + cc.getName());
         cfe.initCause(ex);
         throw cfe;
      }

      return dynClass;
   }

}
