/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.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.logging.Logger;
import org.jboss.security.AuthenticationManager;
import org.jboss.security.RealmMapping;
import org.jboss.ejb3.Container;

public class RunAsSecurityInterceptorFactory implements AspectFactory
{
   private static final Logger log = Logger.getLogger(RunAsSecurityInterceptorFactory.class);
   
   public Object createPerVM()
   {
      throw new RuntimeException("PER_VM not supported for this interceptor factory, only PER_CLASS");
   }

   public Object createPerClass(Advisor advisor)
   {
      Object domain = null;
      try
      {
         Container container = (Container)advisor;
         InitialContext ctx = container.getInitialContext();
         org.jboss.annotation.security.SecurityDomain securityAnnotation = (org.jboss.annotation.security.SecurityDomain) advisor.resolveAnnotation(org.jboss.annotation.security.SecurityDomain.class);
         domain = ctx.lookup("java:/jaas/" + securityAnnotation.value());
      }
      catch (NamingException e)
      {
         throw new RuntimeException(e);
      }
      AuthenticationManager manager = (AuthenticationManager) domain;
      RealmMapping mapping = (RealmMapping) domain;
      if (manager == null) throw new RuntimeException("Unable to find Security Domain");
      return new RunAsSecurityInterceptor(manager, mapping);
   }

   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();
   }
}

