/**
 * 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: EJBModule.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.ejb2.internal.mbean;

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

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

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

import org.ow2.jonas.lib.ejb21.JContainer;
import org.ow2.jonas.lib.management.javaee.J2EEModule;
import org.ow2.jonas.lib.management.javaee.J2eeObjectName;
import org.ow2.jonas.lib.util.Log;


/**
 * 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 {

    protected JContainer cont;

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

    /** server logger. */
    private static Logger logger = Log.getLogger(Log.JONAS_EJB_PREFIX);

    // 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(final MBeanServer mBeanServer, final ObjectName objectName, final JContainer cont, final String fileName, final String containerName, final String j2eeAppName, final URL earUrl) {

        super(objectName.toString());
        //logger = 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()]));
    }

    public void addEjb(final 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 URL getUrl() {
        //TODO: URL should be given instead of fileName in the constructor.
        try {
            return new File(fileName).toURI().toURL();
        } catch (MalformedURLException e) {
            throw new RuntimeException("Cannot get URL for fileName '" + fileName + "'.", e);
        }
    }


    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
     */
    @SuppressWarnings("unchecked")
    public long getNumberOfCalls() {
        long numberOfCalls = 0;
        try {
            Iterator<ObjectName> statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = statefulBeans.next();
                numberOfCalls += ((Long) mBeanServer.getAttribute(on, "numberOfCalls")).intValue();
            }
            Iterator<ObjectName> statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = statelessBeans.next();
                numberOfCalls += ((Long) mBeanServer.getAttribute(on, "numberOfCalls")).intValue();
            }
        } catch (Exception e) {
            logger.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
     */
    @SuppressWarnings("unchecked")
    public long getTotalProcessingTime() {
        long totalProcessingTime = 0;
        try {
            Iterator<ObjectName> statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = statefulBeans.next();
                totalProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalProcessingTime")).longValue();
            }
            Iterator<ObjectName> statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = statelessBeans.next();
                totalProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalProcessingTime")).longValue();
            }
        } catch (Exception e) {
            logger.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
     */
    @SuppressWarnings("unchecked")
    public long getTotalBusinessProcessingTime() {
        long totalBusinessProcessingTime = 0;
        try {
            Iterator<ObjectName> statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = statefulBeans.next();
                totalBusinessProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalBusinessProcessingTime"))
                        .longValue();
            }

            Iterator<ObjectName> statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = statelessBeans.next();
                totalBusinessProcessingTime += ((Long) mBeanServer.getAttribute(on, "totalBusinessProcessingTime"))
                        .longValue();
            }
        } catch (Exception e) {
            logger.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?
     */
    @SuppressWarnings("unchecked")
    public boolean getMonitoringEnabled() {
        try {
            Iterator<ObjectName> statefulBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatefulSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statefulBeans.hasNext()) {
                ObjectName on = statefulBeans.next();
                if (!((Boolean) mBeanServer.getAttribute(on, "monitoringEnabled")).booleanValue()) {
                    return false;
                }

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

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

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

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

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

            Iterator<ObjectName> statelessBeans = mBeanServer.queryNames(
                    new ObjectName(this.objectName.getDomain() + ":j2eeType=StatelessSessionBean,EJBModule="
                            + containerName + ",*"), null).iterator();
            while (statelessBeans.hasNext()) {
                ObjectName on = statelessBeans.next();
                int currentWarningThreshold = ((Integer) mBeanServer.getAttribute(on, "warningThreshold")).intValue();
                if (warningThreshold == -1) {
                    warningThreshold = currentWarningThreshold;
                } else if (warningThreshold != currentWarningThreshold) {
                    return -1;
                }
            }
        } catch (Exception e) {
            logger.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.
     */
    @SuppressWarnings("unchecked")
    public void setWarningThreshold(final int warningThreshold) {

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

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

}
