/*
* JBoss, the OpenSource J2EE webOS
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jboss.security.ssl;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.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 javax.net.ssl.KeyManagerFactory
 * @see javax.net.ssl.SSLContext
 * @see javax.net.ssl.TrustManager
 * @see javax.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.2.6.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");
      }
   }
}