/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.S.
 * 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: JavaVm.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.jmbeans;

import java.util.Vector;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.lib.management.javaee.J2EEManagedObject;
import org.ow2.jonas.lib.util.Log;
import org.ow2.jonas.properties.ServerProperties;

/**
 * The Java Virtual Machine used by the JOnAS server.
 * @author Adriana Danes
 */
public class JavaVm extends J2EEManagedObject {

    // ------------------------------------------------------------- Private
    // Constants
    /** JRE version property name. */
    private static final String JAVA_VERSION = "java.version";

    /** JRE vendor property name. */
    private static final String JAVA_VENDOR = "java.vendor";

    /** JRE VM name property name. */
    private static final String JAVA_VM_NAME = "java.vm.name";

    /** JRE VM name property name. */
    private static final String JAVA_VM_VERSION = "java.vm.version";

    /** default host name. */
    private static final String NODE_LOCAL = "localhost";

    private static final String JAVA_HOME = "java.home";
    // ------------------------------------------------------------- Privates
    // Variables
    /** private logger */
    private static Logger sLogger = null;

    // ------------------------------------------------------------- Properties

    /**
     * JVM version.
     */
    private String javaVersion = null;

    /**
     * JVM vendor.
     */
    private String javaVendor = null;

    /**
     * Node (machine) the JVM is running on.
     */
    private String node = null;

    /**
     * java.home environment property.
     */
    private String javaHome = null;

    // ------------------------------------------------------------- Contructors
    /**
     * Construct JavaVM MBean.
     * @param pObjectName The MBean's OBJECT_NAME
     * @param props the JOnAS server's configuration properties.
     */
    public JavaVm(final String pObjectName, final ServerProperties props) {
        super(pObjectName);
        javaVersion = props.getValue(JAVA_VERSION);
        javaVendor = props.getValue(JAVA_VM_NAME) + "-" +  props.getValue(JAVA_VM_VERSION)
                     + " / " + props.getValue(JAVA_VENDOR);
        javaHome = props.getValue(JAVA_HOME);
        try {
            java.net.InetAddress oInet = java.net.InetAddress.getLocalHost();
            node = oInet.getCanonicalHostName();
        } catch (java.net.UnknownHostException e) {
            node = NODE_LOCAL;
        }
        // get a logger for server traces
        sLogger = Log.getLogger(Log.JONAS_SERVER_PREFIX);
    }

    // ------------------------------------------------------------- Properties
    // Methods
    /**
     * @return The JVM version.
     */
    public String getJavaVersion() {
        return javaVersion;
    }

    /**
     * @return The JVM vendor.
     */
    public String getJavaVendor() {
        return javaVendor;
    }

    /**
     * @return The node (machine) the JVM is running on.
     */
    public String getNode() {
        return node;
    }

    /**
     * @return The java.home environment property.
     */
    public String getJavaHome() {
        return javaHome;
    }
    //  ------------------------------------------------------------- Operations
    /**
     * @return the system threadGroup
     */
    protected ThreadGroup getTopLevelThreadGroup() {
        // Get the topLevel ThreadGroup
        ThreadGroup parentg = null;
        ThreadGroup tg = Thread.currentThread().getThreadGroup();

        while ((parentg = tg.getParent()) != null) {
            tg = parentg;

        }
        return tg;
    }

    /**
     * @return the number of threads in the JOnAS server
     */
    public int getAllThreadsCount() {

        ThreadGroup tg = getTopLevelThreadGroup();
        int realnbthread = 0;
        synchronized (this) {
            // Get the number of active threads
            int count = tg.activeCount();
            sLogger.log(BasicLevel.DEBUG, "number of active threads = " + count);
            Thread[] array = new Thread[count];
            tg.enumerate(array, true);
            for (int j = 0; j < count; j++) {
                if (array[j] != null) {
                    realnbthread++;
                }
            }
        }
        return realnbthread;
    }

    /**
     * @return the list of threadgroups name
     */
    public String[] getThreadGroups() {
        ThreadGroup tg = getTopLevelThreadGroup();
        Vector<String> v = new Vector<String>();
        synchronized (this) {
            // Get the number of active threadGroups
            int counttg = tg.activeGroupCount();
            ThreadGroup[] array = new ThreadGroup[counttg];
            v.addElement(tg.getName());
            tg.enumerate(array, true);
            for (int i = 0; i < counttg; i++) {
                if (array[i] != null) {
                    v.addElement(array[i].getName());
                }
            }
        }
        String[] ret = new String[v.size()];
        v.copyInto(ret);
        return ret;
    }

    /**
     * @param name name of the thread group
     * @return the name of thread names
     */
    public String[] listThreads(String name) {
        ThreadGroup tg = getTopLevelThreadGroup();
        Vector<String> v = new Vector<String>();
        String[] ret = null;
        synchronized (this) {
            // Get the number of active threadGroups
            int counttg = tg.activeGroupCount();
            ThreadGroup[] array = new ThreadGroup[counttg];
            tg.enumerate(array, true);

            for (int i = 0; i < counttg; i++) {
                if (array[i].getName().equals(name)) {
                    // Get the number of active threads
                    int counth = tg.activeCount();
                    Thread[] tharray = new Thread[counth];
                    array[i].enumerate(tharray);
                    for (int j = 0; j < counth; j++) {
                        if (tharray[j] != null) {
                            v.addElement(tharray[j].getName());
                        }
                    }
                    ret = new String[v.size()];
                    v.copyInto(ret);
                    break;
                }
            }
        }
        return ret;
    }
}
