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

import java.net.URL;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.jboss.system.ServiceMBeanSupport;
import org.jboss.deployment.DeploymentException;

/** A security config mbean that loads an xml login configuration using the
 XMLLoginConfig.loadConfig(URL config) operation on start, and unloads
 the contained login module configurations on stop.

 <server>
   <mbean code="org.jboss.security.auth.login.DynamicLoginConfig"
      name="...">
      <attribute name="AuthConfig">login-config.xml</attribute>
      <!-- The service which supports dynamic processing of login-config.xml
         configurations.
      -->
      <depends optional-attribute-name="LoginConfigService">
         jboss.security:service=XMLLoginConfig
      </depends>
      <!-- Optionally specify the security mgr service to use when
         this service is stopped to flush the auth caches of the domains
         registered by this service.
      -->
      <depends optional-attribute-name="SecurityManagerService">
         jboss.security:service=JaasSecurityManager
      </depends>
   </mbean>
 </server>
 
 @see org.jboss.security.auth.login.XMLLoginConfig

 @author Scott.Stark@jboss.org
 @version $Revision: 1.4 $
 */
public class DynamicLoginConfig extends ServiceMBeanSupport
   implements DynamicLoginConfigMBean
{
   /** The JAAS login config file resource to load */
   private String authConf = "login-config.xml";
   /** The name of the XMLLoginConfig to use to load the login configs */
   private ObjectName loginConfigService;
   /** The name of the SecurityMgrService to use for cache flushes */
   private ObjectName securityMgrService;
   /** The names of the login module configs loaded during start */
   private String[] configNames;

   public DynamicLoginConfig()
   {
   }

   public String getName()
   {
      return "Dynamic JAAS Login Config";
   }

   public ObjectName getLoginConfigService()
   {
      return loginConfigService;
   }
   /** Get the XMLLoginConfig service to use for loading. This service must
    * support a String[] loadConfig(URL) operation to load the configurations. 
    * 
    * @param serviceName - the XMLLoginConfig service name.
    */ 
   public void setLoginConfigService(ObjectName serviceName)
   {
      this.loginConfigService = serviceName;
   }

   public ObjectName getSecurityManagerService()
   {
      return securityMgrService;
   }
   /** Set the SecurityManagerService used to flush the registered security
    * domains. This service must support an flushAuthenticationCache(String)
    * operation to flush the case for the argument security domain. Setting
    * this triggers the flush of the authentication caches when the service
    * is stopped.
    * @param serviceName - the SecurityManagerService service name.
    */
   public void setSecurityManagerService(ObjectName serviceName)
   {
      this.securityMgrService = serviceName;
   }

   /** Get the resource path to the JAAS login configuration file to use.
    */
   public String getAuthConfig()
   {
      return authConf;
   }

   /** Set the resource path to the JAAS login configuration file to use.
    The default is "login-config.xml".
    */
   public void setAuthConfig(String authConf)
   {
      this.authConf = authConf;
   }

   /** Go through the registered login config names and flush the auth
    * caches if there is a registered SecurityManagerService.
    * 
    * @throws Exception
    */ 
   public void flushAuthenticationCaches() throws Exception
   {
      if( this.securityMgrService != null && server.isRegistered(securityMgrService))
      {
         int count = configNames == null ? 0 : configNames.length;
         String[] sig = {String.class.getName()};
         for(int n = 0; n < count; n ++)
         {
            Object[] args = {configNames[n]};
            server.invoke(securityMgrService, "flushAuthenticationCache", args, sig);         
            log.debug("Flushed domain: "+configNames[n]);
         }
      }
   }

   /** Start the service. This entails loading the AuthConf file contents
    * using the LoginConfigService.
    */
   protected void startService() throws Exception
   {
      // Look for the authConf as resource
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      URL loginConfig = loader.getResource(authConf);
      if( loginConfig != null )
      {
         log.debug("Using JAAS AuthConfig: "+loginConfig.toExternalForm());
         MBeanServer server = super.getServer();
         Object[] args = {loginConfig};
         String[] sig = {URL.class.getName()};
         configNames = (String[]) server.invoke(loginConfigService,
            "loadConfig", args, sig);
         int count = configNames == null ? 0 : configNames.length;
         for(int n = 0; n < count; n ++)
         {
            log.debug("Loaded config: "+configNames[n]);
         }
      }
      else
      {
         throw new DeploymentException("Failed to find authConf as resource: "+authConf); 
      }
   }

   /** Start the service. This entails unloading the AuthConf file contents
    * using the LoginConfigService.
    */
   protected void stopService() throws Exception
   {
      MBeanServer server = super.getServer();
      flushAuthenticationCaches();
      if( configNames != null && configNames.length > 0 )
      {
         Object[] args = {configNames};
         String[] sig = {configNames.getClass().getName()};
         server.invoke(loginConfigService, "removeConfigs", args, sig);
      }
   }
}