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

import org.jboss.security.SecurityAssociation;

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

/**
 * @author <a href="mailto:alex@jboss.org">Alexey Loubyansky</a>
 * @version <tt>$Revision: 1.1.2.1 $</tt>
 */
public interface PrincipalInfoAction
{
   class UTIL
   {
      static PrincipalInfoAction getPrincipalInfoAction()
      {
         return System.getSecurityManager() == null ? NON_PRIVILEGED : PRIVILEGED;
      }

      static void set(Principal principal, Object credential)
      {
         getPrincipalInfoAction().set(principal, credential);
      }
   }

   PrincipalInfoAction NON_PRIVILEGED = new PrincipalInfoAction()
   {
      public void set(Principal principal, Object credential)
      {
         SecurityAssociation.setPrincipal(principal);
         SecurityAssociation.setCredential(credential);
      }
   };

   PrincipalInfoAction PRIVILEGED = new PrincipalInfoAction()
   {
      public void set(final Principal principal, final Object credential)
      {
         AccessController.doPrivileged(
            new PrivilegedAction()
            {
               public Object run()
               {
                  SecurityAssociation.setPrincipal(principal);
                  SecurityAssociation.setCredential(credential);
                  return null;
               }
            }
         );
      }
   };

   void set(Principal principal, Object credential);
}
