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

import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.jboss.aop.Advisor;
import org.jboss.aop.InstanceAdvisor;
import org.jboss.aop.advice.AspectFactory;
import org.jboss.aop.joinpoint.Joinpoint;
import org.jboss.security.AuthenticationManager;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.4.2.6 $
 */
public class AuthenticationInterceptorFactory implements AspectFactory
{
   public Object createPerVM()
   {
      throw new RuntimeException("PER_VM not supported for this interceptor factory, only PER_CLASS");
   }

   public Object createPerClass(Advisor advisor)
   {
      AuthenticationManager manager = (AuthenticationManager) advisor.getDefaultMetaData().getMetaData("security", "authentication-manager");
      if (manager == null)
      {
         SecurityDomain domain = (SecurityDomain) advisor.resolveAnnotation(SecurityDomain.class);
         if (domain == null) throw new RuntimeException("Unable to determine security domain");
         try
         {
            manager = (AuthenticationManager) new InitialContext().lookup("java:/jaas/" + domain.value());
         }
         catch (NamingException e)
         {
            throw new RuntimeException(e);  //To change body of catch statement use Options | File Templates.
         }
      }
      if (manager == null) throw new RuntimeException("Unable to find Security Domain");
      return new AuthenticationInterceptor(manager);
   }

   public Object createPerInstance(Advisor advisor, InstanceAdvisor instanceAdvisor)
   {
      throw new RuntimeException("PER_VM not supported for this interceptor factory, only PER_CLASS");
   }

   public Object createPerJoinpoint(Advisor advisor, Joinpoint jp)
   {
      throw new RuntimeException("PER_VM not supported for this interceptor factory, only PER_CLASS");
   }

   public Object createPerJoinpoint(Advisor advisor, InstanceAdvisor instanceAdvisor, Joinpoint jp)
   {
      throw new RuntimeException("PER_VM not supported for this interceptor factory, only PER_CLASS");
   }

   public String getName()
   {
      return getClass().getName();
   }
}
