/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2009 Bull S.A.S.
 * Contact: jonas-team@ow2.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 any 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
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ee.mejb;

import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.ejb.RemoteHome;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.MBeanServer;
import javax.management.j2ee.ListenerRegistration;
import javax.management.j2ee.ManagementHome;
import javax.annotation.PostConstruct;
import javax.annotation.security.RolesAllowed;

import org.ow2.util.log.LogFactory;
import org.ow2.util.log.Log;

/**
 * This is the Management EJB implementation for JOnAS.
 * A MEJB instance is created and deployed at JOnAS start time.
 * It is registered in the ejb/mgmt naming subcontext.
 *
 * The current implementation allows access to managed resources registered in
 * the current (local) MBean server via the standard management methods defined in the
 * javax.management.j2ee.Management interface.
 *
 * @author Adriana Danes
 * @author Vivek Lakshmanan
 * @author Matt Wringe
 */
@Stateless(name="MEJB",
           mappedName = "ejb/mgmt/MEJB")
@RemoteHome(ManagementHome.class)
@RolesAllowed({"mejb-admin", "mejb-user"})
public class ManagementBean {

    /**
     * Logger.
     */
    private static final Log logger = LogFactory.getLog(ManagementBean.class);

    /**
     * Connection to the current JOnAS server's MBean server.
     */
    private MBeanServer mbeanServer = null;

    /**
     * Get the MBeanServer local reference.
     */
    @PostConstruct
    public void init() {
        // TODO : find a 'very better' way to retrieve the MBeanServer used by JOnAS
        // Look if there is already a MBeanServer for JOnAS.
        List<?> mbeanServers = MBeanServerFactory.findMBeanServer(null);
        if (mbeanServers.size() > 0) {
            mbeanServer = (MBeanServer) mbeanServers.get(0);
        } else {
            // Should not be the case, but anyway ...
            logger.debug("Cannot find the default MBeanServer for the platform, create a new one.");
            mbeanServer = MBeanServerFactory.createMBeanServer();
        }
    }

    /**
     * Gets the value of a specific attribute of a named managed object.
     * The managed object is identified by its object name.
     * @param name The object name of the managed object from which the
     *        attribute is to be retrieved.
     * @param attribute A String specifying the name of the attribute
     *        to be retrieved.
     * @return The value of the retrieved attribute.
     * @throws MBeanException Wraps an exception thrown by the managed
     *         object's getter.
     * @throws AttributeNotFoundException The attribute specified is
     *         not accessible in the managed object.
     * @throws InstanceNotFoundException The managed object specified is
     *         not registered in the MEJB.
     * @throws ReflectionException An exception occurred when trying to
     *         invoke the getAttribute method of a Dynamic MBean
     */
    public Object getAttribute(final ObjectName name,
                               final String attribute) throws MBeanException,
                                                              AttributeNotFoundException,
                                                              InstanceNotFoundException,
                                                              ReflectionException {
        return mbeanServer.getAttribute(name, attribute);
    }

    /**
     * Enables the values of several attributes of a named managed object.
     * The managed object is identified by its object name.
     * @param name The object name of the managed object from which
     *        the attributes are retrieved.
     * @param attributes A list of the attributes to be retrieved.
     * @return The list of the retrieved attributes.
     * @throws InstanceNotFoundException The managed object specified is
     *         not registered in the MEJB.
     * @throws ReflectionException An exception occurred when trying to
     *         invoke the getAttributes method of a Dynamic MBean.
     */
    public AttributeList getAttributes(final ObjectName name,
                                       final String[] attributes) throws InstanceNotFoundException,
                                                                         ReflectionException {
        return mbeanServer.getAttributes(name, attributes);
    }

    /**
     * Returns the default domain name of this MEJB.
     * @return the default domain name of this MEJB.
     */
    public String getDefaultDomain() {
        return mbeanServer.getDefaultDomain();
    }

    /**
     * Returns the number of managed objects registered in the MEJB.
     * @return the number of managed objects registered in the MEJB.
     */
    public Integer getMBeanCount() {
        return mbeanServer.getMBeanCount();
    }

    /**
     * This method discovers the attributes and operations that a managed
     * object exposes for management.
     * @param name The name of the managed object to analyze
     * @return An instance of {@link MBeanInfo} allowing the retrieval of
     *         all attributes and operations of this managed object.
     * @throws IntrospectionException An exception occurs during introspection.
     * @throws InstanceNotFoundException The managed object specified is
     *         not found.
     * @throws ReflectionException An exception occurred when trying to
     *         perform reflection on a managed object
     */
    public MBeanInfo getMBeanInfo(final ObjectName name) throws IntrospectionException,
                                                                InstanceNotFoundException,
                                                                ReflectionException {
        return mbeanServer.getMBeanInfo(name);
    }

    /**
     * Invokes an operation on a managed object.
     * @param name The object name of the managed object on which the
     *        method is to be invoked.
     * @param operationName The name of the operation to be invoked.
     * @param params An array containing the parameters to be set
     *        when the operation is invoked
     * @param signature An array containing the signature of the operation.
     *        The class objects will be loaded using the same class loader
     *        as the one used for loading the managed object on which the
     *        operation was invoked.
     * @return The object returned by the operation, which represents the
     *         result of invoking the operation on the managed object specified.
     * @throws InstanceNotFoundException The managed object specified is not
     *         registered in the MEJB.
     * @throws MBeanException Wraps an exception thrown by the managed
     *         object's invoked method.
     * @throws ReflectionException Wraps a {@link Exception} thrown while
     *         trying to invoke the method.
     */
    @RolesAllowed("mejb-admin")
    public Object invoke(final ObjectName name,
                         final String operationName,
                         final Object[] params,
                         final String[] signature) throws MBeanException,
                                                          InstanceNotFoundException,
                                                          ReflectionException {
        return mbeanServer.invoke(name, operationName, params, signature);
    }

    /**
     * Checks whether a managed object, identified by its object name, is
     * already registered with the MEJB.
     * @param name The object name of the managed object to be checked.
     * @return True if the managed object is already registered in the MEJB,
     *         false otherwise.
     */
    public boolean isRegistered(final ObjectName name) {
        return mbeanServer.isRegistered(name);
    }

    /**
     * Gets the names of managed objects controlled by the MEJB. This method
     * enables any of the following to be obtained: The names of all managed
     * objects, the names of a set of managed objects specified by pattern
     * matching on the {@link ObjectName}, a specific managed object name
     * (equivalent to testing whether a managed object is registered). When
     * the object name is null or no domain and key properties are specified,
     * all objects are selected. It returns the set of J2EEObjectNames for
     * the managed objects selected.
     * @param name The object name pattern identifying the managed objects to
     *        be retrieved. If null or no domain and key properties are
     *        specified, all the managed objects registered will be retrieved.
     * @param query a relational constraints for results filtering
     * @return A set containing the ObjectNames for the managed objects selected.
     *         If no managed object satisfies the query, an empty set is returned.
     */
    public Set queryNames(final ObjectName name, final QueryExp query) {
        return mbeanServer.queryNames(name, query);
    }

    /**
     * Sets the value of a specific attribute of a named managed object.
     * The managed object is identified by its object name.
     * @param name The name of the managed object within which the
     *        attribute is to be set.
     * @param attribute The identification of the attribute to be set
     *        and the value it is to be set to.
     * @throws InstanceNotFoundException The managed object specified
     *         is not registered in the MEJB.
     * @throws AttributeNotFoundException The attribute specified is
     *         not accessible in the managed object.
     * @throws InvalidAttributeValueException The value specified for
     *         the attribute is not valid.
     * @throws MBeanException Wraps an exception thrown by the managed
     *         object's setter.
     * @throws ReflectionException An exception occurred when trying
     *         to invoke the setAttribute method of a Dynamic MBean.
     */
    @RolesAllowed("mejb-admin")
    public void setAttribute(final ObjectName name,
                             final Attribute attribute) throws MBeanException,
                                                               AttributeNotFoundException,
                                                               InstanceNotFoundException,
                                                               InvalidAttributeValueException,
                                                               ReflectionException {
        mbeanServer.setAttribute(name, attribute);
    }

    /**
     * Sets the values of several attributes of a named managed
     * object. The managed object is identified by its object name.
     * @param name The object name of the managed object within
     *        which the attributes are to be set.
     * @param attributes A list of attributes: The identification
     *        of the attributes to be set and the values they are
     *        to be set to.
     * @return The list of attributes that were set, with their new values.
     * @throws InstanceNotFoundException The managed object specified
     *         is not registered in the MEJB.
     * @throws ReflectionException An exception occurred when trying
     *         to invoke the setAttributes method of a Dynamic MBean.
     */
    @RolesAllowed("mejb-admin")
    public AttributeList setAttributes(final ObjectName name,
                                       final AttributeList attributes) throws InstanceNotFoundException,
                                                                              ReflectionException {
        return mbeanServer.setAttributes(name, attributes);
    }

    /**
     * Returns the listener registry implementation for this
     * MEJB. The listener registry implements the methods that
     * enable clients to add and remove event notification
     * listeners managed objects
     * @return An implementation of {@link ListenerRegistration}
     */
    public ListenerRegistration getListenerRegistry() {
        // TODO I suspect that the MBeanServer will not support ser/deser process ...
        return new ListenerRegistrationImpl(mbeanServer);
    }

}
