/**
 * 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("[MEJB] Cannot find the default MBeanServer for the platform, create a new one.");
            mbeanServer = MBeanServerFactory.createMBeanServer();
        }
    }

    public Object getAttribute(final ObjectName name,
                               final String attribute) throws MBeanException,
                                                              AttributeNotFoundException,
                                                              InstanceNotFoundException,
                                                              ReflectionException {
        return mbeanServer.getAttribute(name, attribute);
    }

    public AttributeList getAttributes(final ObjectName name,
                                       final String[] attributes) throws InstanceNotFoundException,
                                                                         ReflectionException {
        return mbeanServer.getAttributes(name, attributes);
    }

    public String getDefaultDomain() {
        return mbeanServer.getDefaultDomain();
    }

    public Integer getMBeanCount() {
        return mbeanServer.getMBeanCount();
    }

    public MBeanInfo getMBeanInfo(final ObjectName name) throws IntrospectionException,
                                                                InstanceNotFoundException,
                                                                ReflectionException {
        return mbeanServer.getMBeanInfo(name);
    }

    @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);
    }

    public boolean isRegistered(final ObjectName name) {
        return mbeanServer.isRegistered(name);
    }

    public Set queryNames(final ObjectName name, final QueryExp query) {
        return mbeanServer.queryNames(name, query);
    }

    @RolesAllowed("mejb-admin")
    public void setAttribute(final ObjectName name,
                             final Attribute attribute) throws MBeanException,
                                                               AttributeNotFoundException,
                                                               InstanceNotFoundException,
                                                               InvalidAttributeValueException,
                                                               ReflectionException {
        mbeanServer.setAttribute(name, attribute);
    }

    @RolesAllowed("mejb-admin")
    public AttributeList setAttributes(final ObjectName name,
                                       final AttributeList attributes) throws InstanceNotFoundException,
                                                                              ReflectionException {
        return mbeanServer.setAttributes(name, attributes);
    }

    /**
     * Returns the ListenerRegistration implementation object which allows the client to register
     * a event notification listener.
     * This method also creates a MBean
     * @return An instance of the class implementing the ListenerRegistration interface.
     * <code>null</code> is returned if
     */
    public ListenerRegistration getListenerRegistry() {
        // TODO I suspect that the MBeanServer will not support ser/deser process ...
        return new ListenerRegistrationImpl(mbeanServer);
    }

}
