Example usage for javax.management MBeanServerConnection getAttribute

List of usage examples for javax.management MBeanServerConnection getAttribute

Introduction

In this page you can find the example usage for javax.management MBeanServerConnection getAttribute.

Prototype

public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException,
        InstanceNotFoundException, ReflectionException, IOException;

Source Link

Document

Gets the value of a specific attribute of a named MBean.

Usage

From source file:gr.cslab.Metric_test.java

static void reportMetric(Metric ms, String host) {
    try {/* w  w  w .  j  a v  a  2 s.  c  o m*/
        //construct the service URL
        JMXConnector jmxc = hostConnections.get(host);
        if (jmxc == null) {
            System.out.println("Host " + host + " unavailable, attempting to connect");
            if (!connectHost(host))
                return;
        }
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        Object rv = mbsc.getAttribute(ms.mbeanName, ms.attribute);
        if (verbose)
            System.out.println(host + ": " + ms.label + "=" + rv + " " + ms.units);
    } catch (IOException ex) {
        System.err.println("ERROR: problem in connection with" + host);
    } catch (MBeanException | ReflectionException ex) {
    } catch (AttributeNotFoundException ex) {
        System.err.println("ERROR: could not find attribute: " + ms.attribute + "in host: " + host);
    } catch (InstanceNotFoundException ex) {
        System.err.println("ERROR: instance was not found");
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.jmx.MutationMxClient.java

public static boolean connect(int i) {
    JMXConnector jmxc = null;//from w  w  w  .  j  a va2 s. c o m
    JMXServiceURL url = null;

    try {
        url = new JMXServiceURL(MXBeanRegisterer.ADDRESS + i);
        jmxc = JMXConnectorFactory.connect(url, null);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        return false;
        // System.out.println("Could not connect to address: " + url);
        // e.printStackTrace();
    }
    if (jmxc != null) {
        try {
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
            ObjectName objectName = new ObjectName(MXBeanRegisterer.OBJECT_NAME);
            Object numberOfMutations = mbsc.getAttribute(objectName, "NumberOfMutations");
            Object currentTest = mbsc.getAttribute(objectName, "CurrentTest");
            Object currentMutation = mbsc.getAttribute(objectName, "CurrentMutation");
            Object allMutations = mbsc.getAttribute(objectName, "Mutations");
            Object mutationsDuration = mbsc.getAttribute(objectName, "MutationDuration");
            Object testDuration = mbsc.getAttribute(objectName, "TestDuration");
            //            Object mutationSummary = mbsc.getAttribute(objectName,
            //                  "MutationSummary");

            final RuntimeMXBean remoteRuntime = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);

            final MemoryMXBean remoteMemory = ManagementFactory.newPlatformMXBeanProxy(mbsc,
                    ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
            System.out.print("Connection: " + i + "  ");
            System.out.println("Target VM: " + remoteRuntime.getName() + " - " + remoteRuntime.getVmVendor()
                    + " - " + remoteRuntime.getSpecVersion() + " - " + remoteRuntime.getVmVersion());
            System.out.println(
                    "Running for: " + DurationFormatUtils.formatDurationHMS(remoteRuntime.getUptime()));
            System.out
                    .println("Memory usage: Heap - " + formatMemory(remoteMemory.getHeapMemoryUsage().getUsed())
                            + "  Non Heap - " + formatMemory(remoteMemory.getNonHeapMemoryUsage().getUsed()));

            String mutationDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(mutationsDuration.toString()));
            String testDurationFormatted = DurationFormatUtils
                    .formatDurationHMS(Long.parseLong(testDuration.toString()));
            if (DEBUG_ADD) {
                System.out.println("Classpath: " + remoteRuntime.getClassPath());
                System.out.println("Args: " + remoteRuntime.getInputArguments());
                System.out.println("All Mutations: " + allMutations);
            }
            //            System.out.println(mutationSummary);
            System.out.println(
                    "Current mutation (Running for: " + mutationDurationFormatted + "): " + currentMutation);
            System.out.println("Mutations tested: " + numberOfMutations);
            System.out.println("Current test:   (Running for: " + testDurationFormatted + "): " + currentTest);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (AttributeNotFoundException e) {
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            e.printStackTrace();
        } catch (MBeanException e) {
            e.printStackTrace();
        } catch (ReflectionException e) {
            e.printStackTrace();
        } finally {
            try {
                jmxc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}

From source file:org.cipango.console.ApplicationManager.java

public static ObjectName[] getWebAppContexts(MBeanServerConnection mbsc) throws Exception {
    return (ObjectName[]) mbsc.getAttribute(JettyManager.SERVER, "contexts");
}

From source file:com.athena.dolly.console.module.jmx.JmxClientManager.java

public static MemoryVo getMemoryUsage(String nodeName) {
    JmxClient jmxClient = jmxClientMap.get(nodeName);

    MemoryVo memory = null;//w w  w  .j a  v  a2 s. c om
    try {
        ObjectName objectName = new ObjectName("java.lang:type=Memory");

        MBeanServerConnection connection = jmxClient.getJmxConnector().getMBeanServerConnection();
        CompositeDataSupport heapMemoryUsage = (CompositeDataSupport) connection.getAttribute(objectName,
                "HeapMemoryUsage");

        memory = new MemoryVo();
        memory.setCommitted((Long) heapMemoryUsage.get("committed"));
        memory.setInit((Long) heapMemoryUsage.get("init"));
        memory.setMax((Long) heapMemoryUsage.get("max"));
        memory.setUsed((Long) heapMemoryUsage.get("used"));

        logger.debug("nodeName: [{}], memoryUsage: [committed: {}, init:{}, max:{}, used:{}]", new Object[] {
                nodeName, memory.getCommitted(), memory.getInit(), memory.getMax(), memory.getUsed() });
    } catch (Exception e) {
        logger.error("unhandled exception has errored : ", e);
    }

    return memory;
}

From source file:com.athena.dolly.console.module.jmx.JmxClientManager.java

public static OperationgSystemVo getOperatingSystemUsage(String nodeName) {
    JmxClient jmxClient = jmxClientMap.get(nodeName);

    OperationgSystemVo osVo = null;/*from   ww w .  j  a  va 2 s . c o  m*/
    try {
        ObjectName objectName = new ObjectName("java.lang:type=OperatingSystem");

        MBeanServerConnection connection = jmxClient.getJmxConnector().getMBeanServerConnection();

        osVo = new OperationgSystemVo();

        osVo.setName((String) connection.getAttribute(objectName, "Name"));
        osVo.setVersion((String) connection.getAttribute(objectName, "Version"));
        osVo.setArch((String) connection.getAttribute(objectName, "Arch"));
        osVo.setSystemLoadAverage((Double) connection.getAttribute(objectName, "SystemLoadAverage"));
        osVo.setAvailableProcessors((Integer) connection.getAttribute(objectName, "AvailableProcessors"));

        osVo.setFreePhysicalMemory((Long) connection.getAttribute(objectName, "FreePhysicalMemorySize"));
        osVo.setFreeSwapSpaceSize((Long) connection.getAttribute(objectName, "FreeSwapSpaceSize"));
        osVo.setProcessCpuTime((Long) connection.getAttribute(objectName, "ProcessCpuTime"));
        osVo.setCommittedVirtualMemorySize(
                (Long) connection.getAttribute(objectName, "CommittedVirtualMemorySize"));
        osVo.setTotalPhysicalMemorySize((Long) connection.getAttribute(objectName, "TotalPhysicalMemorySize"));
        osVo.setTotalSwapSpaceSize((Long) connection.getAttribute(objectName, "TotalSwapSpaceSize"));

    } catch (Exception e) {
        logger.error("unhandled exception has errored : ", e);
    }

    return osVo;
}

From source file:org.hyperic.hq.plugin.jboss.JBossUtil.java

static void determineJSR77Case(String url, MBeanServerConnection mServer) {
    try {/* w w w . j  a v a 2s .c  o m*/
        ObjectName server = new ObjectName(ServerQuery.SERVER_NAME);
        String version = (String) mServer.getAttribute(server, ServerQuery.ATTR_VERSION);
        if (version.length() < 5) {
            return;
        }
        boolean lc;
        int majorVersion = Character.getNumericValue(version.charAt(0));
        if (majorVersion >= 4) {
            //4.x, 5.x
            lc = true;
        } else if (Character.getNumericValue(version.charAt(4)) >= 8) {
            //3.2.8
            lc = true;
        } else {
            //<= 3.2.7
            lc = false;
        }

        synchronized (lowerCaseURLMappings) {
            lowerCaseURLMappings.put(url, lc ? Boolean.TRUE : Boolean.FALSE);
        }

        if (log.isDebugEnabled()) {
            log.debug(url + " " + version + " jsr77LowerCase=" + lc);
        }
    } catch (Exception e) {
        //unlikely, but in this case, leave it to the server type to determine the case
    }
}

From source file:com.athena.dolly.console.module.jmx.JmxClientManager.java

public static String getCpuUsage(String nodeName) {
    String cpuUsageStr = null;/*from w w  w.j a  va2s .  co  m*/
    JmxClient jmxClient = jmxClientMap.get(nodeName);

    try {
        MBeanServerConnection connection = jmxClient.getJmxConnector().getMBeanServerConnection();

        ObjectName osObjectName = new ObjectName("java.lang:type=OperatingSystem");
        ObjectName runTimeObjectName = new ObjectName("java.lang:type=Runtime");

        //before Cpu
        int availableProcessors = (Integer) connection.getAttribute(osObjectName, "AvailableProcessors");
        long prevUpTime = (Long) connection.getAttribute(runTimeObjectName, "Uptime");
        long prevProcessCpuTime = (Long) connection.getAttribute(osObjectName, "ProcessCpuTime");

        try {
            Thread.sleep(1000);
        } catch (Exception ignored) {
            // ignore
        }

        //after Cpu
        long upTime = (Long) connection.getAttribute(runTimeObjectName, "Uptime");
        long processCpuTime = (Long) connection.getAttribute(osObjectName, "ProcessCpuTime");

        long elapsedCpu = processCpuTime - prevProcessCpuTime;
        long elapsedTime = upTime - prevUpTime;

        double cpuUsage = Math.min(99F, elapsedCpu / (elapsedTime * 10000F * availableProcessors));
        cpuUsageStr = String.format("%.2f", cpuUsage);
        logger.debug("nodeName: [{}], cpuUsage: [{}]", nodeName, cpuUsageStr);
    } catch (Exception e) {
        logger.error("unhandled exception has errored : ", e);
    }

    return cpuUsageStr;
}

From source file:de.jgoldhammer.alfresco.jscript.jmx.JmxDumpUtil.java

/**
 * Dumps the details of a single MBean./*  w w  w  .j a v  a  2s .  c om*/
 * 
 * @param connection
 *            the server connection (or server itself)
 * @param objectName
 *            the object name
 * @param out
 *            PrintWriter to write the output to
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws JMException
 *             Signals a JMX error
 */
public static void printMBeanInfo(MBeanServerConnection connection, ObjectName objectName, PrintWriter out,
        String attributeName) throws IOException, JMException {
    Map<String, Object> attributes = new TreeMap<String, Object>();
    MBeanInfo info = connection.getMBeanInfo(objectName);
    attributes.put("** Object Name", objectName.toString());
    attributes.put("** Object Type", info.getClassName());

    if (StringUtils.isNotBlank(attributeName)) {
        Object value;
        try {
            value = connection.getAttribute(objectName, attributeName);
        } catch (Exception e) {
            value = JmxDumpUtil.UNREADABLE_VALUE;
        }
        outputValue(out, value, 10);
    } else {

        for (MBeanAttributeInfo element : info.getAttributes()) {
            Object value;
            if (element.isReadable()) {
                try {
                    value = connection.getAttribute(objectName, element.getName());
                } catch (Exception e) {
                    value = JmxDumpUtil.UNREADABLE_VALUE;
                }
            } else {
                value = JmxDumpUtil.UNREADABLE_VALUE;
            }
            attributes.put(element.getName(), value);
        }
        tabulate(JmxDumpUtil.NAME_HEADER, JmxDumpUtil.VALUE_HEADER, attributes, out, 0);
    }
}

From source file:de.jgoldhammer.alfresco.jscript.jmx.JmxDumpUtil.java

/**
 * Dumps the details of a single MBean./*from   ww w.ja va2s .  c om*/
 * 
 * @param connection
 *            the server connection (or server itself)
 * @param objectName
 *            the object name
 * @param out
 *            PrintWriter to write the output to
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws JMException
 *             Signals a JMX error
 */
public static Map<Object, Object> getSimpleMBeanInfo(MBeanServerConnection connection, ObjectName objectName)
        throws IOException, JMException {
    Map<Object, Object> attributes = new TreeMap<Object, Object>();
    MBeanInfo info = connection.getMBeanInfo(objectName);
    attributes.put("** Object Name", objectName.toString());
    attributes.put("** Object Type", info.getClassName());

    for (MBeanAttributeInfo element : info.getAttributes()) {
        Object value;
        if (element.isReadable()) {
            try {
                value = connection.getAttribute(objectName, element.getName());
            } catch (Exception e) {
                value = JmxDumpUtil.UNREADABLE_VALUE;
            }
        } else {
            value = JmxDumpUtil.UNREADABLE_VALUE;
        }
        attributes.put(element.getName(), value);
    }
    return attributes;
}

From source file:org.hyperic.hq.plugin.jboss.JBossUtil.java

static Double getJSR77Statistic(MBeanServerConnection mServer, ObjectName objName, Metric metric, boolean lc)
        throws MetricNotFoundException, MetricInvalidException, MetricUnreachableException, PluginException {

    //jboss changed attribute case in version 4.0
    String[] attrs;//from  ww w .  j  av  a 2 s  . c om
    if (lc) {
        attrs = STAT_PROVIDER_4;
    } else {
        attrs = STAT_PROVIDER;
    }

    Stats stats;
    try {
        Boolean provider = (Boolean) mServer.getAttribute(objName, attrs[0]);
        if ((provider == null) || !provider.booleanValue()) {
            String msg = "MBeanServerConnection does not provide statistics";
            throw new PluginException(msg);
        }

        stats = (Stats) mServer.getAttribute(objName, attrs[1]);
    } catch (RemoteException e) {
        throw unreachable(metric, e);
    } catch (InstanceNotFoundException e) {
        throw notfound(metric, e);
    } catch (AttributeNotFoundException e) {
        throw notfound(metric, e);
    } catch (ReflectionException e) {
        throw error(metric, e);
    } catch (MBeanException e) {
        throw error(metric, e);
    } catch (IOException e) {
        throw error(metric, e);
    }

    if (stats == null) {
        throw new PluginException("MBeanServerConnection has no stats");
    }

    String statName = metric.getAttributeName().substring(9);
    Statistic stat = stats.getStatistic(statName);
    if (stat == null) {
        String msg = "Statistic '" + statName + "' not found [" + metric + "]";
        throw new MetricNotFoundException(msg);
    }

    long value;
    if (stat instanceof CountStatistic) {
        value = ((CountStatistic) stat).getCount();
    } else if (stat instanceof RangeStatistic) {
        value = ((RangeStatistic) stat).getCurrent();
    } else {
        String msg = "Unsupported statistic type [" + statName.getClass().getName() + " for [" + metric + "]";
        throw new MetricInvalidException(msg);
    }

    return new Double(value);
}