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

// JOnAS Management
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import javax.management.Attribute;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jmx.J2eeObjectName;
import org.objectweb.jonas.management.j2eemanagement.J2EEModule;
import org.objectweb.jonas_ejb.container.JContainer;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * MBean class for EJBModule management
 * 
 * @author Adriana Danes JSR 77 (J2EE Management Standard)
 * @author S. Ali Tokmen, Malek Chahine: EJB statistics
 */
public class EJBModule extends J2EEModule {

    /**
     * Server logger
     */
    private static Logger servlog = null;

    protected JContainer cont;

    // JSR 77
    private ArrayList ejbs = new ArrayList();

    // private attributes
    String containerName = null;
    String fileName = null;
    /**
     * J2EEApplication MBean OBJECT_NAME in ear case
     */
    private String earON = null;
    /**
     * URL of the ear
     */
    private URL earURL = null;

    /**
     * We are in ear case or not ?
     */
    private boolean inEarCase = false;

    /**
     * MBean server.
     */
    private MBeanServer mBeanServer;

    /**
     * Object name.
     */
    private ObjectName objectName;

    public EJBModule(MBeanServer mBeanServer, ObjectName objectName, JContainer cont, String fileName,
            String containerName, String j2eeAppName, URL earUrl) {
        super(objectName.toString());
        servlog = Log.getLogger(Log.JONAS_SERVER_PREFIX);
        this.mBeanServer = mBeanServer;
        this.objectName = objectName;
        this.cont = cont;
        this.fileName = fileName;
        this.containerName = containerName;
        if (j2eeAppName != null && earUrl != null) {
            ObjectName j2eeAppOn = J2eeObjectName.J2EEApplication(objectName.getDomain(), objectName
                    .getKeyProperty("J2EEServer"), j2eeAppName);
            earON = j2eeAppOn.toString();
            this.earURL = earUrl;
            inEarCase = true;
        }
    }

    public String[] getEjbs() {
        return ((String[]) ejbs.toArray(new String[ejbs.size()]));
    }

    protected void addEjb(String ejbObjectName) {
        ejbs.add(ejbObjectName);
    }

    public int getCurrentNumberOfEJB() {
        return ejbs.size();
    }

    public int getCurrentNumberOfBMP() {
        return cont.getEntityBMPNb();
    }

    public int getCurrentNumberOfCMP() {
        return cont.getEntityCMPNb();
    }

    public int getCurrentNumberOfSBF() {
        return cont.getStatefulSessionNb();
    }

    public int getCurrentNumberOfSBL() {
        return cont.getStatelessSessionNb();
    }

    public int getCurrentNumberOfMDB() {
        return cont.getMessageDrivenNb();
    }

    public String getContainerName() {
        return containerName;
    }

    public String getFileName() {
        return fileName;
    }

    public String getEarON() {
        return earON;
    }

    public URL getEarURL() {
        return earURL;
    }

    public boolean isInEarCase() {
        return inEarCase;
    }

    /**
     * get the total number of calls on all beans of this ejb container
     * 
     * @return the total number of calls on all beans of this ejb container
     */
    public int getNumberOfCalls() {
        int numberOfCalls = 0;
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                numberOfCalls += ((Integer) mBeanServer.getAttribute(on, "numberOfCalls")).intValue();
            }
            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                numberOfCalls += ((Integer) mBeanServer.getAttribute(on, "numberOfCalls")).intValue();
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed getting attribute 'numberOfCalls'", e);
        }
        return numberOfCalls;
    }

    /**
     * get the total time spent in container + business execution for all beans
     * of this ejb container
     * 
     * @return the total time spent in container + business execution for all
     *         beans of this ejb container
     */
    public long getTotalProcessingTime() {
        long totalProcessingTime = 0;
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                totalProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalProcessingTime")).longValue();
            }
            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                totalProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalProcessingTime")).longValue();
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed getting attribute 'totalProcessingTime'", e);
        }
        return totalProcessingTime;
    }

    /**
     * get the total time spent in business execution for all beans of this ejb
     * container
     * 
     * @return the total time spent in business execution for all beans of this
     *         ejb container
     */
    public long getTotalBusinessProcessingTime() {
        long totalBusinessProcessingTime = 0;
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                totalBusinessProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalBusinessProcessingTime"))
                        .longValue();
            }

            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                totalBusinessProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalBusinessProcessingTime"))
                        .longValue();
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed getting attribute 'totalBusinessProcessingTime'", e);
        }
        return totalBusinessProcessingTime;
    }

    /**
     * get the average time spent in container + business execution for all
     * beans of this ejb container per request
     * 
     * @return the average time spent in container + business execution for all
     *         beans of this ejb container per request
     */
    public long getAverageProcessingTime() {
        if (getNumberOfCalls() > 0) {
            return getTotalProcessingTime() / getNumberOfCalls();
        } else {
            return 0;
        }
    }

    /**
     * get the average time spent in business execution for all beans of this
     * ejb container per request
     * 
     * @return the average time spent in business execution for all beans of
     *         this ejb container per request
     */
    public long getAverageBusinessProcessingTime() {
        if (getNumberOfCalls() > 0) {
            return getTotalBusinessProcessingTime() / getNumberOfCalls();
        } else {
            return 0;
        }
    }

    /**
     * @return Will EJB monitoring enabled for EJBs deployed in the future?
     */
    public boolean getMonitoringEnabled() {
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                if (!((Boolean) mBeanServer.getAttribute(on, "monitoringEnabled")).booleanValue()) {
                    return false;
                }

            }
            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                if (!((Boolean) mBeanServer.getAttribute(on, "monitoringEnabled")).booleanValue()) {
                    return false;
                }
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed getting attribute 'monitoringEnabled'", e);
        }
        return true;
    }

    /**
     * @param monitoringEnabled
     *            Whether EJB monitoring will enabled for EJBs deployed in the
     *            future.
     */
    public void setMonitoringEnabled(final boolean monitoringEnabled) {

        Attribute monitoringEnabledAttribute = new Attribute("monitoringEnabled", new Boolean(monitoringEnabled));
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                mBeanServer.setAttribute(on, monitoringEnabledAttribute);
            }

            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                mBeanServer.setAttribute(on, monitoringEnabledAttribute);
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed setting attribute 'monitoringEnabled'", e);
        }
    }

    /**
     * @return Number of milliseconds after which methods of EJBs deployed in
     *         the future will start warning.
     */
    public int getWarningThreshold() {
        // -1 means "inconsistent values"
        int warningThreshold = -1;
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                int currentWarningThreshold = ((Integer) mBeanServer.getAttribute(on, "warningThreshold")).intValue();
                if (warningThreshold == -1) {
                    warningThreshold = currentWarningThreshold;
                } else if (warningThreshold != currentWarningThreshold) {
                    return -1;
                }
            }

            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                int currentWarningThreshold = ((Integer) mBeanServer.getAttribute(on, "warningThreshold")).intValue();
                if (warningThreshold == -1) {
                    warningThreshold = currentWarningThreshold;
                } else if (warningThreshold != currentWarningThreshold) {
                    return -1;
                }
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed getting attribute 'warningThreshold'", e);
        }
        return warningThreshold;
    }

    /**
     * @param warningThreshold
     *            Number of milliseconds after which methods of EJBs deployed in
     *            the future will start warning.
     */
    public void setWarningThreshold(final int warningThreshold) {

        Attribute warningThresholdAttribute = new Attribute("warningThreshold", new Integer(warningThreshold));
        try {
            Iterator statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = (ObjectName) statefulBeans.next();
                mBeanServer.setAttribute(on, warningThresholdAttribute);
            }

            Iterator statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = (ObjectName) statelessBeans.next();
                mBeanServer.setAttribute(on, warningThresholdAttribute);
            }
        } catch (Exception e) {
            servlog.log(BasicLevel.INFO, "Failed setting attribute 'warningThreshold'", e);
        }
    }

}
