/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Created on Jan 20, 2004
 */
package org.jboss.net.axis.security;

import java.lang.reflect.Constructor;
import java.security.KeyStore;

import org.apache.log4j.Logger;
import org.apache.ws.security.components.crypto.CryptoFactory;

/**
 * <dl>
 * <dt><b>Title: </b><dd>Crypto Factory for use within JBoss.Net</dd>
 * <p>
 * <dt><b>Description: </b><dd>Crypto factory that returns JBossCrypto implementations rather than Crypto 
 * implementations</dd>
 * <p>
 * </dl>
 * @author <a href="mailto:jasone@greenrivercomputing.com">Jason Essington</a>
 * @version $Revision: 1.2 $
 */
public class JBossCryptoFactory extends CryptoFactory
{
   private static Logger log = Logger.getLogger(JBossCryptoFactory.class);

   /**
    * Gets an instance of the given Crypto class 
    * @param cryptoClassName name of the crypto class to load. This class should have a constructor that takes a 
    * keystore as a parameter
    * @param keystore this is the keystore that will be used by the crypto class.
    * @return
    */
   public static JBossCrypto getInstance(String cryptoClassName, KeyStore keystore)
   {
      if (log.isDebugEnabled())
         log.debug("Attempting to get a Crypto instance of type " + cryptoClassName);
      return loadClass(cryptoClassName, keystore);
   }

   /**
    * This is prety much the way a new crypto instance is created via the super class, only this one doesn't depend
    * upon properties, it just has the keystore fed in directly.
    * @param cryptoClassName
    * @param keystore
    * @return
    */
   private static JBossCrypto loadClass(String cryptoClassName, KeyStore keystore)
   {
      Class cryptogenClass = null;
      JBossCrypto crypto = null;
      try
      {
         // instruct the class loader to load the crypto implementation
         cryptogenClass = java.lang.Class.forName(cryptoClassName);
      }
      catch (ClassNotFoundException e)
      {
         throw new RuntimeException(cryptoClassName + " Not Found");
      }

      log.info("Using Crypto Engine [" + cryptoClassName + "]");

      try
      {
         Class[] classes = new Class[]{KeyStore.class};
         Constructor c = cryptogenClass.getConstructor(classes);
         crypto = (JBossCrypto) c.newInstance(new Object[]{keystore});
         return crypto;
      }
      catch (java.lang.Exception e)
      {
         log.debug(e);
         log.debug(cryptoClassName + " cannot create instance with KeyStore constructor");
      }

      try
      {
         // try to instantiate the Crypto subclass
         crypto = (JBossCrypto) cryptogenClass.newInstance();
         return crypto;
      }
      catch (java.lang.Exception e)
      {
         throw new RuntimeException(cryptoClassName + " cannot create instance");
      }

   }
}