/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * 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.webapp.jonasadmin;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeOperationsException;

import org.ow2.jonas.lib.management.domain.DomainMonitor;


/**
 * Wrapper class allowing to apply a management operations (getAttribute, setAttribute, invoke, etc.)
 * on the corresponding to managed server's connection.
 * The managed server is identified by a name (serverName parameter).
 * The corresponding connection is kept in the serverConnections table.
 * @author Adriana Danes
 * @author S. Ali Tokmen
 */
public class JonasManagementRepr {

    /**
     * Ref on the DomainMonitor.
     */
    private static DomainMonitor dm = DomainMonitor.getInstance();

    /**
     * Cache of managed server MBeanServerConnection's.
     */
    private static Hashtable<String, MBeanServerConnection> serverConnections =
        new Hashtable<String, MBeanServerConnection>();

    /**
     * Return the connection corresponding to a given server.
     * @param serverName The managed server name
     * @return The MBeanServerConnection corresponding to the managed server
     * @throws ManagementException Couldn't get the connection
     */
    private static MBeanServerConnection getServerConnection(final String serverName) throws ManagementException {
        MBeanServerConnection conn = serverConnections.get(serverName);
        if (conn == null) {
            conn = dm.getConnection(serverName);
            if (conn == null) {
                throw new ManagementException("Can't manage server " + serverName + " as couldn't get connection");
            }
            serverConnections.put(serverName, conn);
        }
        return conn;
    }

    /**
     * @return True if the MBean is already registered in the MBean server, false otherwise or if an exception is catched.
     * @param on ObjectName of the MBean we are looking for
     * @param serverName The server name
     * @throws ManagementException management operation failed
     */
    public static boolean isRegistered(final ObjectName on, final String serverName) throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.isRegistered(on);
        } catch (IOException e) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error calling isRegistered", e);
        }
    }

    /**
     * Gets the value of a specific attribute of a named MBean.
     * @param on The ObjectName of the MBean.
     * @param attribute A String specifying the name of the attribute to be retrieved.
     * @param serverName The server name
     * @return The value of the attribute.
     * @throws ManagementException management operation failed
     */
    public static Object getAttribute(final ObjectName on, final String attribute, final String serverName)
    throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.getAttribute(on, attribute);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error getting attribute: " + attribute, ioe);
        } catch (Exception e) {
            throw new ManagementException("Error getting attribute: " + attribute, e);
        }
    }

    /**
     * Gets the values of several attributes of a named MBean.
     * @param on The ObjectName of the MBean.
     * @param attributes Array of attribute names to be retrieved.
     * @param serverName The server name
     * @return The value of the attribute.
     * @throws ManagementException management operation failed
     */
    public static AttributeList getAttributes(final ObjectName on, final String[] attributes, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.getAttributes(on, attributes);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error getting attributes, first attribute is " + attributes[0], ioe);
        } catch (Exception e) {
            throw new ManagementException("Error getting attributes, first attribute is " + attributes[0], e);
        }
    }

    /**
     * Sets the value of a specific attribute of a named MBean.
     * @param on The ObjectName of the MBean.
     * @param serverName The server name
     * @param attribute A String specifying the name of the attribute to be set.
     * @param value The value to set to the attribute.
     * @throws ManagementException management operation failed
     */
    public static void setAttribute(final ObjectName on, final String attribute, final Object value, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            repr.setAttribute(on, new Attribute(attribute, value));
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error setting attribute: " + attribute, ioe);
        } catch (Exception e) {
            throw new ManagementException("Error setting attribute: " + attribute, e);
        }
    }

    /**
     * @param on The ObjectName of the MBean within which the attribute is to be set.
     * @param serverName The server name
     * @param attributes A list of attributes: The identification of the attribute to be set and the value it is to be set to
     * @throws ManagementException management operation failed
     */
    public static void setAttributes(final ObjectName on, final AttributeList attributes, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            repr.setAttributes(on, attributes);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error setting attributes, first attribute is " + attributes.get(0), ioe);
        } catch (Exception e) {
            throw new ManagementException("Error setting attributes, first attribute is " + attributes.get(0), e);
        }
    }

    /**
     * Invokes an operation on an MBean.
     * @param on MBean name
     * @param operation operation to invoke
     * @param param invoke parameters
     * @param signature invoke parameters signature
     * @param serverName The server name
     * @return The object returned by the operation
     * @throws ManagementException management operation failed
     */
    public static Object invoke(final ObjectName on, final String operation, final Object[] param, final String[] signature, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.invoke(on, operation, param, signature);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error while invoking opeartion: ", ioe);
        } catch (Exception e) {
            String message = e.getMessage();
            message = message + " - " + e.getCause().getMessage();
            Throwable exc = null;
            if (e instanceof MBeanException
                    || e instanceof ReflectionException
                    || e instanceof RuntimeMBeanException
                    || e instanceof RuntimeOperationsException
                    || e instanceof RuntimeErrorException) {

                Exception targetExc = null;
                if (e instanceof MBeanException)                {
                    targetExc = ((MBeanException) e).getTargetException();
                } else if (e instanceof ReflectionException) {
                    targetExc = ((ReflectionException) e).getTargetException();
                } else if (e instanceof RuntimeMBeanException) {
                    targetExc = ((RuntimeMBeanException) e).getTargetException();
                } else if (e instanceof RuntimeOperationsException) {
                    targetExc = ((RuntimeOperationsException) e).getTargetException();
                } else if (e instanceof RuntimeErrorException) {
                    Error atargetExc = ((RuntimeErrorException) e).getTargetError();
                    targetExc = new Exception(atargetExc.getMessage());
                }
                exc = targetExc;
            } else {
                exc = e;
            }
            throw new ManagementException(message, exc);
        }
    }

    /**
     * @return A set containing the ObjectNames for the MBeans selected.
     * @param on MBean name
     * @param serverName The server name
     * @throws ManagementException management operation failed
     */
    public static Set queryNames(final ObjectName on, final String serverName)
     throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.queryNames(on, null);
        } catch (IOException e) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error while getting MBeans names: ", e);
        }
    }


    /**
     * @return An instance of MBeanInfo allowing the retrieval of all
     * attributes and operations of this MBean.
     * @param name MBean's ObjectName
     * @param serverName The server name
     * @throws ManagementException management operation failed
     */
    public static MBeanInfo getMBeanInfo(final ObjectName on, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            return repr.getMBeanInfo(on);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error while getting MBean info: ", ioe);
        } catch (Exception e) {
            throw new ManagementException("Error while getting MBean info: ", e);
        }
    }

    /**
     * Unregisters an MBean from the managed server's MBean server.
     * @param on The object name of the MBean.
     * @param serverName The server name
     * @throws ManagementException wraps exception thrown by the called management operation
     */
    public static void unregisterMBean(final ObjectName on, final String serverName)
        throws ManagementException {
        MBeanServerConnection repr = getServerConnection(serverName);
        try {
            repr.unregisterMBean(on);
        } catch (IOException ioe) {
            // Connection has become obsolete.
            serverConnections.remove(serverName);
            throw new ManagementException("Error while unregistering MBean: ", ioe);
        } catch (Exception e) {
            throw new ManagementException("Error while unregistering MBean: ", e);
        }
    }

}
