package org.jboss.resource.adapter.jms;
import java.util.Set;
import java.util.Iterator;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.security.auth.Subject;
import javax.resource.spi.ManagedConnectionFactory;
import javax.resource.spi.SecurityException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.security.PasswordCredential;
public class JmsCred
{
    public String name;
    public String pwd;
    public JmsCred()
    {
            }
    
    public static JmsCred getJmsCred(ManagedConnectionFactory mcf, Subject subject, ConnectionRequestInfo info)
            throws SecurityException
    {
        JmsCred jc = new JmsCred();
        if (subject == null && info != null)
        {
                        jc.name = ((JmsConnectionRequestInfo) info).getUserName();
            jc.pwd = ((JmsConnectionRequestInfo) info).getPassword();
        }
        else if (subject != null)
        {
                        PasswordCredential pwdc = GetCredentialAction.getCredential(subject, mcf);
            if (pwdc == null)
            {
                                throw new SecurityException("No Passwdord credentials found");
            }
            jc.name = pwdc.getUserName();
            jc.pwd = new String(pwdc.getPassword());
        }
        else
        {
            throw new SecurityException("No Subject or ConnectionRequestInfo set, could not get credentials");
        }
        return jc;
    }
    public String toString()
    {
        return super.toString() + "{ username=" + name + ", password=**** }";
    }
   private static class GetCredentialAction implements PrivilegedAction
   {
      Subject subject;
      ManagedConnectionFactory mcf;
      GetCredentialAction(Subject subject, ManagedConnectionFactory mcf)
      {
         this.subject = subject;
         this.mcf = mcf;
      }
      public Object run()
      {
         Set creds = subject.getPrivateCredentials(PasswordCredential.class);
         PasswordCredential pwdc = null;
         Iterator credentials = creds.iterator();
         while (credentials.hasNext())
         {
            PasswordCredential curCred = (PasswordCredential) credentials.next();
            if (curCred.getManagedConnectionFactory().equals(mcf))
            {
               pwdc = curCred;
               break;
            }
         }
         return pwdc;
      }
      static PasswordCredential getCredential(Subject subject, ManagedConnectionFactory mcf)
      {
         GetCredentialAction action = new GetCredentialAction(subject, mcf);
         PasswordCredential pc = (PasswordCredential) AccessController.doPrivileged(action);
         return pc;
      }
    }
}