/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or 1any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer: Florent BENOIT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.security.realm.factory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.management.MBeanServer;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.Referenceable;

import org.objectweb.jonas.security.SecurityService;
import org.objectweb.jonas.service.ServiceManager;
import org.objectweb.jonas.management.ReconfigDispatcher;
import org.objectweb.jonas.management.ReconfiguredXml;

//import objectweb.util
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jmx.JmxService;
import org.objectweb.jonas.security.realm.principals.User;

/**
 * This class implements JOnAS realm factory objects. It is build from an xml
 * file by the security service of JOnAS.
 * @author Florent Benoit
 */
public abstract class JResource extends ReconfigDispatcher implements Serializable, Referenceable, JResourceMBean {

    /**
     * Name of this resource
     */
    private String name = null;

    /**
     * The logger used in JOnAS
     */
    private static Logger logger = Log.getLogger(Log.JONAS_SECURITY_PREFIX);

    /**
     * Hashtable used to cache the users (speed up search)
     */
    private Hashtable users = null;

    /**
     * Value used as sequence number by reconfiguration notifications
     */
    private long sequenceNumber;

    /**
     * Reference to the security service
     */
    private SecurityService securityService = null;

    /**
     * Reference to a MBean server.
     */
    private MBeanServer mbeanServer = null;

    /**
     * Constructor
     * @throws Exception if a service can't be retrieved
     */
    public JResource() throws Exception {
        users = new Hashtable();
        sequenceNumber = 0;
        try {
            ServiceManager sm = ServiceManager.getInstance();
            securityService = (SecurityService) sm.getSecurityService();
            mbeanServer = ((JmxService) sm.getJmxService()).getJmxServer();
        } catch (Exception e) {
            // no save available
            // no MBeans
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "Cannot get MBean server, client mode ? no jmx registration");
            }
        } catch (Error err) {
            // ServiceManager with JProp class not found
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "No services can be retrieved, client mode ?");
            }
        }

    }

    /**
     * Set the name of this resource
     * @param name Name of the resource
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Get the name of this resource
     * @return the name of this resource
     */
    public String getName() {
        return name;
    }

    /**
     * Get the MBean server
     * @return the MBean server
     */
    protected MBeanServer getMBeanServer() {
        return mbeanServer;
    }

    /**
     * Retrieves the Reference of the object. The Reference contains the factory
     * used to create this object and the optional parameters used to configure
     * the factory.
     * @return the non-null Reference of the object.
     * @throws NamingException if a naming exception was encountered while
     *         retrieving the reference.
     */
    public abstract Reference getReference() throws NamingException;

    /**
     * Remove all the Mbeans used by this resource
     * @throws JResourceException if the MBeans can not be removed
     */
    public abstract void removeMBeans() throws JResourceException;

    /**
     * Check if a user is found and return it
     * @param name the wanted user name
     * @return the user found or null
     * @throws JResourceException if there is an error during the search
     */
    public abstract User findUser(String name) throws JResourceException;

    /**
     * Check if the given credential is the right credential for the given user
     * @param user user to check its credentials
     * @param credentials the given credentials
     * @return true if the credential is valid for this user
     */
    public abstract boolean isValidUser(User user, String credentials);

    /**
     * Get all the roles (from the roles and from the groups) of the given user
     * @param user the given user
     * @return the array list of all the roles for a given user
     * @throws JResourceException if it fails
     */
    public abstract ArrayList getArrayListCombinedRoles(User user) throws JResourceException;

    /**
     * Return users
     * @return Return users
     */
    public Hashtable getUsers() {
        return users;
    }

    /**
     * Return a sequence number and increase this number
     * @return a sequence number
     */
    protected long getSequenceNumber() {
        return ++sequenceNumber;
    }

    /**
     * Update and save configuration
     */
    public void saveConfig() {

        if (securityService != null) {
            // Retrieve the xml value by the Security service
            String xml = securityService.toXML();
            ReconfiguredXml reconfiguredXml = new ReconfiguredXml(xml);

            // Send a reconfiguration notification to the listener MBean
            sendReconfigNotification(getSequenceNumber(), name, reconfiguredXml);
            sendSaveNotification(getSequenceNumber(), name);

            // rebind this resource into the jndi
            try {
                Context ictx = new InitialContext();
                ictx.rebind(getName(), this);
                if (logger.isLoggable(BasicLevel.DEBUG)) {
                    logger.log(BasicLevel.DEBUG, "jResource " + getName() + " is rebind into the registry.");
                }
            } catch (NamingException e) {
                logger.log(BasicLevel.ERROR, "Cannot rebind factory to the jndi : '" + e.getMessage() + "'");
            }

        }
    }

    /**
     * @return Returns the logger.
     */
    public static Logger getLogger() {
        return logger;
    }
    /**
     * @param logger The logger to set.
     */
    public static void setLogger(Logger logger) {
        JResource.logger = logger;
    }
    /**
     * @param users The users to set.
     */
    public void setUsers(Hashtable users) {
        this.users = users;
    }

    /**
     * Clear the cache
     */
    public void clearCache() {
        setUsers(new Hashtable());
    }
}