package org.jboss.resource.security;

import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.Iterator;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;

/**
 * @author Scott.Stark@jboss.org
 * @version $Revison:$
 */
class SubjectActions
{
   static class AddCredentialsAction implements PrivilegedAction
   {
      Subject subject;
      PasswordCredential cred;
      AddCredentialsAction(Subject subject, PasswordCredential cred)
      {
         this.subject = subject;
         this.cred = cred;
      }
      public Object run()
      {
         subject.getPrivateCredentials().add(cred);
         return null;
      }
   }
   static class AddPrincipalsAction implements PrivilegedAction
   {
      Subject subject;
      Principal p;
      AddPrincipalsAction(Subject subject, Principal p)
      {
         this.subject = subject;
         this.p = p;
      }
      public Object run()
      {
         subject.getPrincipals().add(p);
         return null;
      }
   }
   static class RemoveCredentialsAction implements PrivilegedAction
   {
      Subject subject;
      ManagedConnectionFactory mcf;
      RemoveCredentialsAction(Subject subject, ManagedConnectionFactory mcf)
      {
         this.subject = subject;
         this.mcf = mcf;
      }
      public Object run()
      {
         Iterator i = subject.getPrivateCredentials().iterator();
         while( i.hasNext() )
         {
            Object o = i.next();
            if ( o instanceof PasswordCredential )
            {
               PasswordCredential pc = (PasswordCredential) o;
               if( pc.getManagedConnectionFactory() == mcf )
                  i.remove();
            }
         }
         return null;
      }
   }

   static void addCredentials(Subject subject, PasswordCredential cred)
   {
      AddCredentialsAction action = new AddCredentialsAction(subject, cred);
      AccessController.doPrivileged(action);
   }
   static void addPrincipals(Subject subject, Principal p)
   {
      AddPrincipalsAction action = new AddPrincipalsAction(subject, p);
      AccessController.doPrivileged(action);
   }
   static void removeCredentials(Subject subject, ManagedConnectionFactory mcf)
   {
      RemoveCredentialsAction action = new RemoveCredentialsAction(subject, mcf);
      AccessController.doPrivileged(action);
   }

}
