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

// Java imports

import java.util.Vector;

import org.objectweb.jonas.common.JProp;
import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.management.j2eemanagement.J2EEManagedObject;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * The Java Virtual Machine used by the JOnAS server.
 * @author Michel-Ange Anton
 */
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";

    // ------------------------------------------------------------- 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;

    // ------------------------------------------------------------- Contructors
    /**
     * Construct JavaVM MBean
     * @param pObjectName The MBean's OBJECT_NAME
     * @param pProps JProp object containing current JVM's properties
     */
    public JavaVm(String pObjectName, JProp pProps) {
        super(pObjectName);
        javaVersion = pProps.getValue(JAVA_VERSION);
        javaVendor = pProps.getValue(JAVA_VM_NAME) + "-" +  pProps.getValue(JAVA_VM_VERSION)
                     + " / " + pProps.getValue(JAVA_VENDOR);
        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;
    }

    //  ------------------------------------------------------------- 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 v = new Vector();
        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 v = new Vector();
        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() == 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;
    }
}