/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 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.ws.mbean;

import java.util.Iterator;
import java.util.List;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBean;

import org.apache.commons.modeler.ManagedBean;
import org.apache.commons.modeler.Registry;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jmx.JmxService;
import org.objectweb.jonas.management.JonasMBeanTools;
import org.objectweb.jonas.management.j2eemanagement.J2EEManagedObject;
import org.objectweb.jonas.service.ServiceManager;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Base Class for WebServices MBeans. It makes registration/unregistration
 * of hierarchical MBeans very easy. Needs to be subclassed for each WebService MBean.
 *
 * @author Guillaume Sauthier
 */
public abstract class AbstractWebServiceMBean extends J2EEManagedObject {

    /**
     * logger
     */
    private static Logger log = Log.getLogger(Log.JONAS_WS_PREFIX);

    /**
     * ObjectName instance : avoid recreating an ObjectName each time we want one
     */
    private ObjectName realObjectName = null;

    /**
     * Constructor for default J2eeManagedObject
     * @param objectName the MBean's ObjectName
     */
    public AbstractWebServiceMBean(String objectName) {
        super(objectName);
        try {
            realObjectName = ObjectName.getInstance(objectName);
        } catch (MalformedObjectNameException e) {
            // Cannot go here
            realObjectName = null;
        }
    }

    /**
     * Registers the MBean (and its childs) in the default MBeanServer
     */
    public void register() {
        register(getMBeanServer());
    }

    /**
     * Registers the MBean (and its childs) in the specified MBeanServer
     * @param server the MBeanServer where ON will be registered
     */
    public void register(MBeanServer server) {

        // get common-modeler Registry
        Registry registry = JonasMBeanTools.getRegistry();
        // get the ManagedBean given the MBean type (WebServices, PortComponent, ...)
        ManagedBean managed = registry.findManagedBean(getMBeanType());
        try {
            // instantiate and register the Model
            ModelMBean model = managed.createMBean(this);
            server.registerMBean(model, realObjectName);
        } catch (Exception e) {
            // should never goes here
            log.log(BasicLevel.DEBUG, "Should never goes here", e);
        }

        // register "childs"
        List childs = getChildsMBeans();
        if (childs != null) {
            for (Iterator i = childs.iterator(); i.hasNext();) {
                AbstractWebServiceMBean child = (AbstractWebServiceMBean) i.next();
                child.register(server);
            }
        }
    }

    /**
     * @return Returns the MBean type (as used in mbean-descriptor.xml)
     */
    protected abstract String getMBeanType();

    /**
     * Unregisters the MBean (and its childs) from the default MBeanServer
     */
    public void unregister() {
        unregister(getMBeanServer());
    }

    /**
     * Unregisters the MBean (and its childs) from the specified MBeanServer
     * @param server the MBeanServer where ON will be unregistered
     */
    public void unregister(MBeanServer server) {
        // unregister MBean
        try {
            server.unregisterMBean(ObjectName.getInstance(getObjectName()));
        } catch (Exception e) {
            // nothing to do, we simply continue the unregistering process
            log.log(BasicLevel.DEBUG, "Should never goes here", e);
        }

        // unregister "childs"
        List childs = getChildsMBeans();
        if (childs != null) {
            for (Iterator i = childs.iterator(); i.hasNext();) {
                AbstractWebServiceMBean child = (AbstractWebServiceMBean) i.next();
                child.unregister(server);
            }
        }
    }

    /**
     * @return Returns the Child List
     */
    protected abstract List getChildsMBeans();

    /**
     * @return Returns the MBeanServer
     */
    private MBeanServer getMBeanServer() {
        ServiceManager sm;
        try {
            sm = ServiceManager.getInstance();
        } catch (Exception e) {
            // we should never goes here
            throw new IllegalStateException(
                    "Cannot get ServiceManager inside JOnAS !");
        }
        MBeanServer server = ((JmxService) sm.getJmxService()).getJmxServer();
        return server;
    }

    /**
     * @return Returns the ObjectName instance
     */
    public ObjectName getRealObjectName() {
        return this.realObjectName;
    }
}
