package org.jboss.security.ssl;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import com.sun.net.ssl.KeyManagerFactory;
import com.sun.net.ssl.SSLContext;
import com.sun.net.ssl.TrustManager;
import com.sun.net.ssl.TrustManagerFactory;

import org.jboss.logging.Logger;
import org.jboss.security.SecurityDomain;

/** 
 * Utility class with a static method that returns an initialized JSSE 
 * SSLContext for a given JBossSX SecurityDomain.
 *
 * @see com.sun.net.ssl.SSLContext
 * @see com.sun.net.ssl.KeyManagerFactory
 * @see com.sun.net.ssl.TrustManagerFactory
 * @see org.jboss.security.SecurityDomain
 * 
 * @author  Scott.Stark@jboss.org
 * @author <a href="mailto:reverbel@ime.usp.br">Francisco Reverbel</a>
 *
 * @version $Revision: 1.1.2.1 $
 */
class Context
{
   private static Logger log = Logger.getLogger(Context.class);

   /*
    * Returns an initialized JSSE SSLContext that uses the KeyManagerFactory
    * and TrustManagerFactory objects encapsulated by a given JBossSX 
    * SecurityDomain.
    */
   static SSLContext forDomain(SecurityDomain securityDomain)
      throws IOException
   {
      SSLContext sslCtx = null;
      try
      {
         sslCtx = SSLContext.getInstance("TLS");
         KeyManagerFactory keyMgr = securityDomain.getKeyManagerFactory();
         if( keyMgr == null )
            throw new IOException("KeyManagerFactory is null for security domain: "+securityDomain.getSecurityDomain());
         TrustManagerFactory trustMgr = securityDomain.getTrustManagerFactory();
         TrustManager[] trustMgrs = null;
         if( trustMgr != null )
            trustMgrs = trustMgr.getTrustManagers();
         sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
         return sslCtx;
      }
      catch(NoSuchAlgorithmException e)
      {
         log.error("Failed to get SSLContext for TLS algorithm", e);
         throw new IOException("Failed to get SSLContext for TLS algorithm");
      }
      catch(KeyManagementException e)
      {
         log.error("Failed to init SSLContext", e);
         throw new IOException("Failed to init SSLContext");
      }
      catch(SecurityException e)
      {
         log.error("Failed to init SSLContext", e);
         throw new IOException("Failed to init SSLContext");
      }
   }
}
