/*
 * Created on February 12, 2004
 *
 * Utility.java uses Sun logging
 * 
 */

package ersatz.resourceadapter;


import javax.resource.ResourceException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.SecurityException;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import java.util.Set;
import java.util.Iterator;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * 
 *
**/
public class Utility
{
  private static Logger logger = null;
  /**
   * Write a JOnAS log record
   *
   * @param msg  display this message in log
   *
   */
  public static synchronized void log(String msg) {
    if (logger == null) {
        logger = Log.getLogger("ersatz.resourceadapter");
    }
    logger.log(BasicLevel.DEBUG, msg);
  }  


  /** Returns the Password credential
  *
  * @param mcf      ManagedConnectionFactory currently being used
  * @param subject  Subject associated with this call
  * @param info     ConnectionRequestInfo
  *
  * @return         PasswordCredential for this user
  */
  static synchronized PasswordCredential getPasswordCredential
         (ManagedConnectionFactoryImpl mcf, Subject subject, 
            ConnectionRequestInfo info)
         throws ResourceException 
  {
    String mName = "Utility.getPasswordCredential";
  	if (subject == null) 
    {
      if (info == null) return null;
      ConnectionRequestInfoImpl crii = (ConnectionRequestInfoImpl) info;
      PasswordCredential pc = 
           new PasswordCredential(crii.getUserName(),
                                  crii.getPassword().toCharArray());
      pc.setManagedConnectionFactory(mcf);
      return pc;
    } 
    Set cred = subject.getPrivateCredentials(PasswordCredential.class);
    PasswordCredential pc = null;
    for (Iterator iter = cred.iterator();  iter.hasNext();)
    {
      PasswordCredential tmpPc = (PasswordCredential) iter.next();
      if (mcf.equals(tmpPc.getManagedConnectionFactory())) 
      {
        log(mName+" PasswordCredential found mcf="+mcf);
        pc = tmpPc;
        break;
      }
    }
    if (pc == null) 
    {
      SecurityException se = new SecurityException("No PasswordCredential found");
      log(mName+" No PasswordCredential found.");
      throw se;
    } 
    return pc;
  }
 

}
