/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2005 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 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.objectweb.jonas.mejb;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.j2ee.ListenerRegistration;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jmx.J2eeObjectName;
import org.objectweb.jonas.jmx.JmxService;
import org.objectweb.jonas.management.j2eemanagement.J2EEDomain;
import org.objectweb.jonas.management.j2eemanagement.ManagementListener;
import org.objectweb.jonas.management.j2eemanagement.ManagementListenerMBean;
import org.objectweb.jonas.service.ServiceManager;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * 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.
 *
 * It also allows access to managed resources registered in remote MBean servers
 * which belong to the current management domain, via management methods exposed as a
 * WebService endpoint (defined in the ManagementEndpoint interface).
 *
 * @author Adriana Danes
 * @author Vivek Lakshmanan
 * @author Matt Wringe
 */
public class ManagementBean implements SessionBean, ManagementEndpoint {

    /**
     * Logger
     */
    private static Logger logger = Log.getLogger(Log.JONAS_MEJB);
    /**
     * reference to the context object
     */
    private SessionContext sessionContext = null;
    /**
     * The current JOnAS server's jmx service.
     * The jmx service is used to get connections to remote MBean servers
     */
    private JmxService jmxService = null;
    /**
     * Connection to the current JOnAS server's MBean server
     */
    private MBeanServerConnection jmxServerConnection = null;
    /**
     * The current server name
     */
    private String serverName = null;
    /**
     * The current domain name
     */
    private String domainName = null;
    /**
     * The remote NotificationListener proxy name
     */
    private String proxyName = "MEJB_listener";

    /**
     * ejbCreate method
     *
     * Get the MBeanServer reference to allow local access
     */
    public void ejbCreate() throws CreateException {
        try {
            jmxService = (JmxService) ServiceManager.getInstance().getJmxService();
            serverName = jmxService.getJonasServerName();
            domainName = jmxService.getDomainName();
            jmxServerConnection = (MBeanServerConnection) jmxService.getJmxServer();
        } catch (Exception e) {
            throw new CreateException("Could not create Management bean: " + e.getMessage());
        }
    }

    /*====================== javax.ejb.SessionBean implementation =================*/

    public void ejbActivate() {
        // Nothing to do when the MEJB is activated
    }
    public void ejbPassivate() {
        // Nothing to do when the MEJB is passivated
    }
    public void ejbRemove() {
        // Nothing to do when the MEJB is removed
    }
    /**
     * Sets the associated session context.
     * @param sessionContext - A SessionContext interface for the instance.
     */
    public void setSessionContext(SessionContext sessionContext) {
        this.sessionContext = sessionContext;
    }

    /*========================= Management interface implementation ============================*/
    /*=============== The management methods are invoked on the local MBeanServer ========*/


    public Object getAttribute(ObjectName name, String attribute) throws
    MBeanException,
    AttributeNotFoundException,
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        try {
            return jmxServerConnection.getAttribute(name, attribute);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("Object getAttribute(ObjectName, String) failed", ioe);
        }
    }

    public AttributeList getAttributes(ObjectName name, String[] attributes) throws
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        try {
            return jmxServerConnection.getAttributes(name, attributes);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("AttributeList getAttributes(ObjectName, String[]) failed", ioe);
        }
    }

    public String getDefaultDomain() throws RemoteException {

        try {
            return jmxServerConnection.getDefaultDomain();
        } catch (java.io.IOException ioe) {
            throw new RemoteException("String getDefaultDomain() failed", ioe);
        }
    }

    public Integer getMBeanCount() throws RemoteException {

        try {
            return jmxServerConnection.getMBeanCount();
        } catch (java.io.IOException ioe) {
            throw new RemoteException("Integer getMBeanCount() failed", ioe);
        }
    }

    public MBeanInfo getMBeanInfo(ObjectName name) throws
    IntrospectionException,
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        try {
            return jmxServerConnection.getMBeanInfo(name);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("MBeanInfo getMBeanInfo(ObjectName) failed", ioe);
        }
    }

    public Object invoke(ObjectName name, String operationName, Object[] params, String[] signature) throws
    MBeanException,
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        try {
            return jmxServerConnection.invoke(name, operationName, params, signature);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("Object invoke(ObjectName, String, Object[], String[]) failed", ioe);
        }
    }

    public boolean isRegistered(ObjectName name) throws RemoteException {

        try {
            return jmxServerConnection.isRegistered(name);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("boolean isRegistered(ObjectName) failed", ioe);
        }
    }

    public Set queryNames(ObjectName name, QueryExp query) throws RemoteException {
        try {
            return jmxServerConnection.queryNames(name, query);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("Set queryNames(ObjectName, QueryExp)  failed", ioe);
        }
    }

    public void setAttribute(ObjectName name, Attribute attribute) throws
    MBeanException,
    AttributeNotFoundException,
    InstanceNotFoundException,
    InvalidAttributeValueException,
    ReflectionException,
    RemoteException {

        try {
            jmxServerConnection.setAttribute(name, attribute);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("void setAttribute(ObjectName, Attribute) failed", ioe);
        }
    }

    public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        try {
            return jmxServerConnection.setAttributes(name, attributes);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("AttributeList setAttributes(ObjectName, AttributeList) failed", ioe);
        }
    }

    /**
     * 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() throws RemoteException {
        // Create and register the ManagemenentListener MBean if this is not already done
        ObjectName listenerOn = J2eeObjectName.ManagementListener(domainName, serverName);
        boolean isRegisteredListener;
        isRegisteredListener = jmxService.getJmxServer().isRegistered(listenerOn);
        if (!isRegisteredListener) {
            ManagementListenerMBean listenerMBean = new ManagementListener(proxyName);
            try {
                jmxService.getJmxServer().registerMBean(listenerMBean, listenerOn);
            } catch (InstanceAlreadyExistsException ae) {
                // Not possible as tested before
            } catch (Exception e) {
                // Could not register MBean -> the management bean can't handle notifications
                throw new RemoteException("Can not return ListenerRegistration implementation", e);
            }
        }
        // Create ListenerRegistration object
        return new ListenerRegistrationImpl(listenerOn, proxyName);
    }

    /*=============== The management methods are invoked on Remote MBeanServers ==========*/

    /**
     * Returns a connection for a server in the domain. Any error messages in getting
     * the server connection is thrown as a remote exception.
     * @param domainServerName    The server name.
     * @return                    A connection to the server.
     */
    private MBeanServerConnection getServerConnection (String domainServerName) {
        //if the domainServerName is null, return the connection to the current server
        if (domainServerName == null || domainServerName.equals(serverName)) {
            return jmxServerConnection;
        }
        return J2EEDomain.getInstance().getConnection(domainServerName);
    }

    public Object getAttribute (String domainServerName, ObjectName name, String attribute) throws
    AttributeNotFoundException,
    InstanceNotFoundException,
    MBeanException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.getAttribute(name, attribute);
        } catch (IOException ioe) {
            throw new RemoteException ("Object getAttribute(String, ObjectName, String) failed", ioe);
        }
    }


    public AttributeList getAttributes(String domainServerName, ObjectName name, String[] attributes) throws
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.getAttributes(name, attributes);
        } catch (IOException ioe) {
            throw new RemoteException("AttributeList getAttributes(String, ObjectName, String[]) failed", ioe);
        }
    }



    public Integer getMBeanCount(String domainServerName) throws RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
                throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.getMBeanCount();
        } catch (IOException ioe) {
            throw new RemoteException("Integer getMBeanCount(String) failed", ioe);
        }
    }


    public MBeanInfo getMBeanInfo(String domainServerName, ObjectName name) throws
    IntrospectionException,
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection (domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.getMBeanInfo(name);
        } catch (IOException ioe) {
            throw new RemoteException("MBeanInfo getMbeanInfo(String, ObjectName) failed", ioe);
        }
    }

    public Object invoke(String domainServerName, ObjectName name, String operationName, Object[] params, String[] signature) throws
    MBeanException,
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection (domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.invoke (name, operationName, params, signature);
        } catch (IOException ioe) {
            throw new RemoteException("Object invoke(String, ObjectName, String, Object[], String[]) failed", ioe);
        }
    }

    public boolean isRegistered(String domainServerName, ObjectName name) throws RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.isRegistered(name);
        } catch (java.io.IOException ioe) {
            throw new RemoteException ("boolean isRegistered(String, ObjectName) failed", ioe);
        }
    }

    public Set queryNames(String domainServerName, ObjectName name, QueryExp query) throws RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            return connection.queryNames (name, query);
        } catch (java.io.IOException ioe) {
            throw new RemoteException ("Set queryNames(String, ObjectName, QueryExp) failed", ioe);
        }
    }

    public void setAttribute(String domainServerName, ObjectName name, Attribute attribute) throws
    MBeanException,
    AttributeNotFoundException,
    InstanceNotFoundException,
    InvalidAttributeValueException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException ("Could not connect to server " + domainServerName);
        }
        try {
            connection.setAttribute (name, attribute);
        } catch (java.io.IOException ioe) {
            throw new RemoteException ("void setAttribute(String, ObjectName, Attribute) failed", ioe);
        }
    }

    public AttributeList setAttributes(String domainServerName, ObjectName name, AttributeList attributes) throws
    InstanceNotFoundException,
    ReflectionException,
    RemoteException {

        MBeanServerConnection connection = getServerConnection(domainServerName);
        if (connection == null) {
            throw new RemoteException("Could not connect to server " + domainServerName);
        }
        try {
            return connection.setAttributes(name, attributes);
        } catch (java.io.IOException ioe) {
            throw new RemoteException("AttributeList setAttributes(String, ObjectName, AttributeList) failed", ioe);
        }
    }


    /*================== ManagementBean Monitoring Endpoint implementation ===============*/
    /*=============== The management methods are invoked on Remote MBeanServers ==========*/

    /*
     * Implementation for the ManagementEndpoint interface begins here
     *
     * -the ManagementEndpoint allows monitoring of the server remotely using its web
     *  service.
     * -many of these methods look the same as the ones above but their
     *  data types have been changed to make them easier for a web service to use
     *  them.
     * -The only method used in the ManagementEndpoint interface that is
     *  not listed below is getMBeanCount which was already web service friendly
     * -Special expections are thrown when errors occur. These persist to the
     *  web service client. Exception Class:
     *  org.objectweb.jonas.mejb.ManagementEndpointException.
     */

    /**
     * Returns the names of the servers in the domain.
     * @return The names of the servers in the domain.
     * @throws ManagementEndpointException    If any errors occur.
     * @throws RemoteException                If a connection error occurs.
     */
    public String[] getServers() throws ManagementEndpointException, RemoteException {
        String j2eeDomainName = domainName + ":j2eeType=J2EEDomain,name=" + this.domainName;
        return getAttribute(serverName, j2eeDomainName, "serverNames");
    }


    /**
     * @see ManagementEndpoint#getAttribute(String, String, String)
     */
    public String[] getAttribute(String domainServerName, String objectName, String attribute)
            throws ManagementEndpointException {
        try {
            return getObjectValue(getAttribute(domainServerName, new ObjectName(objectName), attribute));
        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in getAttribute service call for objectname: " + objectName
                    + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /**
     * @see ManagementEndpoint#isRegistered(String, String)
     */
    public boolean isRegistered(String domainServerName, String objectName) throws ManagementEndpointException {
        try {
            return isRegistered(domainServerName, new ObjectName(objectName));
        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in isRegistered service call for objectname: " + objectName
                    + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /**
     * @see ManagementEndpoint#queryNames(String, String, String)
     */
    public String[] queryNames(String domainServerName, String objectName, String query) throws ManagementEndpointException {
        try {

            // TODO Determine how to use QueryExp. ATM query support disabled.
            return getObjectValue(queryNames(domainServerName, new ObjectName(objectName), null));

        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in queryNames service call for objectname: " + objectName
                    + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /**
     * @see ManagementEndpoint#getAttributesList(String, String)
     */
    public String[] getAttributesList(String domainServerName, String objectName) throws ManagementEndpointException {
        try {
            MBeanInfo info = getMBeanInfo(domainServerName, new ObjectName(objectName));
            MBeanAttributeInfo[] attrInfo = info.getAttributes();
            String[] attrs = new String[attrInfo.length];
            for (int i = 0; i < attrs.length; i++) {
                attrs[i] = attrInfo[i].getName();
            }
            return attrs;

        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in getAttributeList service call for objectname: " + objectName
                + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /**
     * @see ManagementEndpoint#getDescription(String, String)
     */
    public String getDescription(String domainServerName, String objectName)
        throws ManagementEndpointException {
        try {
            MBeanInfo info = getMBeanInfo(domainServerName, new ObjectName(objectName));
            return info.getDescription();
        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in getDescription service call for objectname: " + objectName
                + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }

    }

    /**
     * @see ManagementEndpoint#getOperations(String, String)
     */
    public String[] getOperations(String domainServerName, String objectName)
        throws ManagementEndpointException {
        try {
            MBeanInfo info = getMBeanInfo(domainServerName, new ObjectName(objectName));
            MBeanOperationInfo[] operationInfo = info.getOperations();
            String[] operations = new String[operationInfo.length];
            for (int i = 0; i < operationInfo.length; i++) {
                operations[i] = operationInfo[i].getName();
            }
            return operations;

        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in getOperations service call for objectname: " + objectName
                + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /**
     * @see ManagementEndpoint#invoke(String, String, String[])
     */
    public String[] invoke(String domainServerName, String objectName, String operationName, String[] params)
    throws ManagementEndpointException, RemoteException {
        try {
            String[] signature = new String[params.length];
            for (int i = 0; i < signature.length; i++) {
                signature[i] = "String";
            }
            return getObjectValue(invoke(domainServerName
                , new ObjectName(objectName)
                , operationName
                , (Object[]) params
                , signature));
        } catch (Exception e) {
            ManagementEndpointException mex = new ManagementEndpointException();
            mex.setExceptionType(e.getClass().toString());
            mex.setMessage("Problem in invoke service call for objectname: " + objectName
                    + " - the request was not completed: " + e.getMessage());
            logger.log(BasicLevel.ERROR, mex.getMessage(), e);
            throw (ManagementEndpointException) mex.initCause(e);
        }
    }

    /*
     *  Listed below are helper methods for the ManagementEndpoint
     *
     *  These methods are used to convert complex data types into more simpler
     *  types so that they work easier with web services. Most complex data types
     *  are converted into a string array
     */

    /**
     * Takes an arbitrary object and returns a string array representation
     * of the object. This methods is used to make passing values from a
     * web service endpoint to a client easier to handle.
     * @param objectValue   An object.
     * @return              A string array representation of the object.
     */
    private String[] getObjectValue(Object objectValue) {
        String[] value = null;

        if (objectValue == null) {
            value = new String[1];
            value[0] = "null";
        } else {
            // Detect Array or Collection
            if (objectValue.getClass().isArray()) {
                // Array
                value = arrayToString((Object[]) objectValue);
            } else {
                try {
                    // Collection
                    value = collectionToString((Collection) objectValue);
                } catch (Exception e) {
                    // Default
                    value = new String[1];
                    value[0] = objectValue.toString();
                }
            }
        }
        return value;
    }

    /**
     * Takes an array of objects and returns the string array representation.
     * @param pArray    An array of objects.
     * @return          A string array representation of the object array.
     */
    private String[] arrayToString(Object[] pArray) {
        String[] retStringArr = new String[pArray.length];
        for (int i = 0; i < pArray.length; i++) {
            if (pArray[i] == null) {
                retStringArr[i] = "null";
        } else {
                retStringArr[i] = pArray[i].toString();
            }

        }
        return retStringArr;
    }

    /**
     * Takes a collection and returns the string array representation of the object.
     * @param pCollection    A collection of objects.
     * @return               A string array representation of the object.
     */
    private String[] collectionToString(Collection pCollection) {
        String[] retStringArr = new String[pCollection.size()];
        Iterator it = pCollection.iterator();
        int i = 0;
        while (it.hasNext()) {
            retStringArr[i++] = it.next().toString();
        }
        return retStringArr;
    }

}