/* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
 * This file is part of SIGAR.
 * 
 * SIGAR is free software; you can redistribute it and/or modify
 * it under the terms version 2 of the GNU General Public License as
 * published by the Free Software Foundation. This program 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 General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA.
 */

package org.hyperic.sigar.cmd;

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

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.jmx.SigarProcess;

public class Mx extends SigarCommandBase {

    private boolean isRegistered;

    public Mx(Shell shell) {
        super(shell);
    }

    public Mx() {
        super();
    }
    //java -Dcom.sun.management.jmxremote -jar sigar.jar
    public String getUsageShort() {
        return "Register MBeans for use via jconsole, etc.";
    }

    protected boolean validateArgs(String[] args) {
        return args.length <= 1;
    }

    public static MBeanServer getMBeanServer()
        throws SigarException {
        List servers = 
            MBeanServerFactory.findMBeanServer(null);
    
        if (servers.size() == 0) {
            throw new SigarException("No MBeanServers available");
        }
        else {
            return (MBeanServer)servers.get(0);
        }
    }

    private void register(MBeanServer server) throws SigarException {
        if (isRegistered) {
            return;
        }

        try {
            String name = org.hyperic.sigar.jmx.SigarRegistry.class.getName();
            server.createMBean(name, null);
            SigarProcess proc = new SigarProcess(this.sigar);
            server.registerMBean(proc, new ObjectName(proc.getObjectName()));
            isRegistered = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new SigarException(e.getMessage());
        }
    }

    private void jconsole() {
        String pid = String.valueOf(this.sigar.getPid());
        String[] argv = { "jconsole", pid };
        println("exec(jconsole, " + pid + ")");
        try {
            Process p = Runtime.getRuntime().exec(argv);
            p.waitFor();
            println("jconsole exited");
        } catch (Exception e) {
            println(e.getMessage());
        }        
    }

    public void output(String[] args) throws SigarException {
        MBeanServer server = getMBeanServer();
        register(server);
        boolean hasQuery = false;
        boolean launchJconsole = false;
        String query = "sigar:*";

        for (int i=0; i<args.length; i++) {
            String arg = args[i];
            if (arg.equals("-jconsole")) {
                launchJconsole = true;
            }
            else {
                query = arg;
                hasQuery = true;
            }
        }

        try {
            Set beans =
                server.queryNames(new ObjectName(query), null);
            println(beans.size() + " MBeans are registered...");
            for (Iterator it=beans.iterator(); it.hasNext();) {
                ObjectName name = (ObjectName)it.next(); 
                if (hasQuery) {
                    MBeanInfo info = server.getMBeanInfo(name);
                    MBeanAttributeInfo[] attrs = info.getAttributes();
                    for (int i=0; i<attrs.length; i++) {
                        String attr = attrs[i].getName();
                        Object val = server.getAttribute(name, attr);
                        println(name + ":" + attr + "=" + val);
                    }                    
                }
                else {
                    println(name.toString());
                }
            }
        } catch (Exception e) {
            throw new SigarException(e.getMessage());
        }
        if (launchJconsole) {
            jconsole();
        }
    }

    public static void main(String[] args) throws Exception {
        new Mx().processCommand(args);
    }
}

@@ -1171,28 +1171,31 @@
 ate 
-boolean isRegistered
+ObjectName registryName
 ;%0A%0A 
@@ -1981,28 +1981,41 @@
     if (
-isRegistered
+this.registryName != null
 ) %7B%0A    
@@ -2137,32 +2137,52 @@
 e();%0A           
+ this.registryName =
  server.createMB
@@ -2192,24 +2192,40 @@
 (name, null)
+.getObjectName()
 ;%0A          
@@ -2292,34 +2292,26 @@
     
-server.registerMBean(proc,
+ObjectName pname =
  new
@@ -2343,17 +2343,16 @@
 tName())
-)
 ;%0A      
@@ -2362,27 +2362,106 @@
    i
-sRegistered = true;
+f (!server.isRegistered(pname)) %7B%0A                server.registerMBean(proc, pname);%0A            %7D
 %0A   
@@ -4536,19 +4536,269 @@
     
-jconsole();
+flush();%0A            jconsole();%0A            try %7B //test unregisterMBean%0A                server.unregisterMBean(this.registryName);%0A                this.registryName = null;%0A            %7D catch (Exception e) %7B%0A                e.printStackTrace();%0A            %7D
 %0A   

test unregisterMBean