/**
 * 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 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.jmx;

import java.util.List;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.NamingException;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.service.AbsServiceImpl;
import org.objectweb.jonas.service.ServiceException;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * JMX Service implementation. This singleton class must exist in each jonas
 * server that is to be administered via JMX. Its main role is to initialize the
 * service (the singleton object).
 * @author Guillaume Riviere
 * @author Michel Bruno
 * @author Adriana Danes
 */

public abstract class AbsJmxServiceImpl extends AbsServiceImpl implements JmxService {

    /**
     * Trace logger
     */
    private static Logger logger = null;

    /**
     * @return Logger logger object
     */
    protected static Logger getLogger() {
        return logger;
    }

    /**
     * JMX server (MBean server) instance
     */
    private MBeanServer jmxServer = null;

    /**
     * Init the Service. Create the MBeanServer. Configuration information is
     * passed through a Context object.
     * @param ctx context containing service initilaisation parameters
     * @exception ServiceException the service could not be initialized
     */
    public void doInit(Context ctx) throws ServiceException {
        logger = Log.getLogger(Log.JONAS_JMX_PREFIX);
        super.initLogger(Log.getLogger(Log.JONAS_MANAGEMENT_PREFIX));

        // Create the MBeanServer

        // get Id
        String idMBeanServer = null;
        try {
            idMBeanServer = (String) ctx.lookup("idMBeanServer");
        } catch (NamingException ne) {
            throw new ServiceException("Cannot found the id of the MBean Server", ne);
        }

        // ----------------------
        List mbeanServers = MBeanServerFactory.findMBeanServer(idMBeanServer);
        if (mbeanServers.size() == 0) {
            throw new ServiceException("No MBean server found for id '" + idMBeanServer + "'.");
        }
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Use first MBean server ID found");
        }
        jmxServer = (MBeanServer) mbeanServers.get(0);

        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "JMX Service initialized");
        }
    }

    /**
     * Start the Service Initialization of the service is already done.
     * @exception ServiceException the service could not be started
     */
    public abstract void doStart() throws ServiceException;

    /**
     * Stop this service
     * @exception ServiceException the service could not be stopped
     */
    public abstract void doStop() throws ServiceException;

    public abstract JMXServiceURL[] getConnectorServerURLs();

    /**
     * @return The local reference of the MBean server
     */
    public MBeanServer getJmxServer() {
        return this.jmxServer;
    }

    /**
     * Register an MBean on the JOnAS mbeanServer
     * @param mbean
     * @param objectName
     */
    public void registerMBean(Object mbean, String objectName) {
        if (jmxServer == null) {
            logger.log(BasicLevel.ERROR, "JMX Server not initialized yet");
            return;
        }
        try {
            ObjectName on = ObjectName.getInstance(objectName);
            jmxServer.registerMBean(mbean, on);
        } catch (MalformedObjectNameException e) {
            logger.log(BasicLevel.ERROR, objectName + ":" + e);
        } catch (InstanceAlreadyExistsException e) {
            logger.log(BasicLevel.WARN, objectName + ":" + e);
        } catch (MBeanRegistrationException e) {
            logger.log(BasicLevel.ERROR, objectName + ":" + e);
        } catch (NotCompliantMBeanException e) {
            logger.log(BasicLevel.ERROR, objectName + ":" + e);
        }
    }

    /**
     * Remove internal references to the MBeanServer.
     */
    protected void releaseJmxServer() {
        try {
            MBeanServerFactory.releaseMBeanServer(jmxServer);
        } catch (java.lang.IllegalArgumentException ex) {
            // The mbeanServer is not found.
            logger.log(BasicLevel.ERROR, "Cannot find the MBeanServer" + ex);
        }
    }

}