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

import java.security.PrivilegedAction;
import java.security.AccessController;

/** An encapsulation of thread context class loader PrivilegedAction for
 * getting and setting the TCL. 
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1.2.1 $
 */
class TCLActions
{
   private static class GetTCLAction implements PrivilegedAction
   {
      static PrivilegedAction ACTION = new GetTCLAction();
      public Object run()
      {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         return loader;
      }
   }
   private static class GetClassLoaderAction implements PrivilegedAction
   {
      Class c;
      GetClassLoaderAction(Class c)
      {
         this.c = c;
      }
      public Object run()
      {
         ClassLoader loader = c.getClassLoader();
         c = null;
         return loader;
      }
   }
   private static class SetTCLAction implements PrivilegedAction
   {
      ClassLoader loader;
      SetTCLAction(ClassLoader loader)
      {
         this.loader = loader;
      }
      public Object run()
      {
         Thread.currentThread().setContextClassLoader(loader);
         loader = null;
         return null;
      }
   }

   static ClassLoader getContextClassLoader()
   {
      ClassLoader loader = (ClassLoader) AccessController.doPrivileged(GetTCLAction.ACTION);
      return loader;
   }
   static ClassLoader getClassLoader(Class c)
   {
      GetClassLoaderAction action = new GetClassLoaderAction(c);
      ClassLoader loader = (ClassLoader) AccessController.doPrivileged(action);
      return loader;
   }
   static void setContextClassLoader(ClassLoader loader)
   {
      PrivilegedAction action = new SetTCLAction(loader);
      AccessController.doPrivileged(action);
   }
}
