Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

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

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

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

public static boolean connect(int i) {
    JMXConnector jmxc = null;// w w  w .ja va  2s  .co 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:com.ngdata.hbaseindexer.supervisor.IndexerRegistry.java

private void registerMBean() {
    try {/* www . j a v a  2  s .c o m*/
        jmxObjectName = new ObjectName("HBaseIndexer:name=Indexer");
        ManagementFactory.getPlatformMBeanServer().registerMBean(this, jmxObjectName);
    } catch (Exception e) {
        log.warn("Error registering mbean '" + jmxObjectName, e);
    }
}

From source file:dk.au.cs.karibu.backend.standard.StandardDaemon.java

/** Create a daemon with the given name to handle the
 * provided message receiver endpoint. The daemon is
 * NOT run, use 'startAndJoin' for that, or start it manually
 * using the accessor method for the underlying thread.
 * /*from   w w  w . j a v a  2 s . co m*/
 * @param nameOfDaemon name of daemon used in the log files.
 * @param the message receiver endpoint
 */

public StandardDaemon(String nameOfDaemon, MessageReceiverEndpoint mre) {
    log = LoggerFactory.getLogger(StandardDaemon.class);
    daemonName = nameOfDaemon;

    receiverThread = new Thread(mre, daemonName + "-ReceiverThread");

    MBeanServer mbs = null;
    MonitoringMBean monitor;

    mbs = ManagementFactory.getPlatformMBeanServer();
    monitor = new Monitoring(mre);
    try {
        String theName2 = "EcoSense:name=" + daemonName + "Monitor";
        ObjectName monitorBeanName = new ObjectName(theName2);
        mbs.registerMBean(monitor, monitorBeanName);
        log.info("Registered JMX bean: " + nameOfDaemon);
    } catch (Exception e) {
        String theTrace = ExceptionUtils.getStackTrace(e);
        log.error("JMX bean exception: " + theTrace);
    }

}

From source file:com.googlecode.jmxtrans.monitoring.ManagedGenericKeyedObjectPool.java

@Override
public ObjectName getObjectName() throws MalformedObjectNameException {
    if (objectName == null) {
        objectName = new ObjectName("com.googlecode.jmxtrans:Type=GenericKeyedObjectPool,PoolName="
                + this.poolName + ",Name=" + this.getClass().getSimpleName() + "@" + this.hashCode());
    }//from   w w w.  j  ava  2 s  . co m
    return objectName;
}

From source file:com.vmware.springsource.hyperic.plugin.gemfire.AlertsPlugin.java

@Override
public void configure(ConfigResponse config) throws PluginException {
    log.debug("[configure] config=" + config);
    super.configure(config);
    MBeanServerConnection mServer;

    try {//from  w  w w.jav  a  2  s.c o  m
        mServer = MxUtil.getMBeanServer(config.toProperties());
        ObjectName obj = new ObjectName("GemFire:type=MemberInfoWithStatsMBean");
        mServer.addNotificationListener(obj, this, null, null);
        log.debug("[configure] listener OK");
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    }
}

From source file:net.sfr.tv.mom.mgt.handlers.InvocationHandler.java

@Override
public Object execute(MBeanServerConnection connection, Object[] args) {
    if (this.expression.indexOf("{") != -1) {
        this.expression = renderExpression(new Object[] { "\"".concat(args[0].toString()).concat("\"") });
        args = Arrays.copyOfRange(args, 1, args.length);
    }//ww  w  .  j ava 2  s.  co m

    try {
        final Set<ObjectName> oNames = connection.queryNames(new ObjectName(expression), null);
        if (oNames == null || oNames.isEmpty()) {
            LOGGER.severe("No object names returns for expression '" + expression + "'");
            return null;
        } else {
            final Object result = connection.invoke(oNames.iterator().next(), operation.getName(), args,
                    operation.getSignature());
            if (result == null) {
                LOGGER.warning("Result of operation '" + operation.getName() + "'is null");
                return result;
            }
            return formatter.format(result);
        }
        //result = connection.invoke(new ObjectName(expression), operation.getName(), new Object[operation.getSignature().length], operation.getSignature());
    } catch (MBeanException | IllegalArgumentException | InstanceNotFoundException
            | MalformedObjectNameException | ReflectionException | IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.netflix.config.jmx.ConfigJMXManager.java

private static ObjectName getJMXObjectName(AbstractConfiguration config, ConfigMBean bean) throws Exception {
    try {//from   w ww .  j a v a2  s  . c o m
        Class<? extends ConfigMBean> c = bean.getClass();
        String className = c.getName();
        int lastDot = className.lastIndexOf('.');
        ObjectName name = new ObjectName(
                "Config-" + className.substring(0, lastDot) + ":class=" + className.substring(lastDot + 1));
        return name;
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException("MalformedObjectNameException", e);
    } catch (NullPointerException e) {
        throw new RuntimeException("NullPointerException", e);
    }
}

From source file:com.riotgames.mondev.JMXDiscovery.java

protected String discoverMBeans(String key) throws Exception {
    try {// ww w .  j  a  v  a  2s.co m
        HashMap<String, String[]> env = null;
        if (null != username && null != password) {
            env = new HashMap<String, String[]>();
            env.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        }

        jmxc = JMXConnectorFactory.connect(jmxServerUrl, env);
        mbsc = jmxc.getMBeanServerConnection();

        ObjectName filter = new ObjectName(key);
        JSONArray beanList = new JSONArray();
        JSONObject mapping = new JSONObject();

        Set beans = mbsc.queryMBeans(filter, null);
        for (Object obj : beans) {
            JSONObject bean = new JSONObject();
            ObjectName beanName;

            // Return the ObjectName instance correctly for both Objects and Instances
            if (obj instanceof ObjectName)
                beanName = (ObjectName) obj;
            else if (obj instanceof ObjectInstance)
                beanName = ((ObjectInstance) obj).getObjectName();
            else
                throw new RuntimeException("Unexpected object type: " + obj);

            // Build the standing info, description and object path
            MBeanInfo mbi = mbsc.getMBeanInfo(beanName);
            bean.put("{#JMXDESC}", mbi.getDescription());
            bean.put("{#JMXOBJ}", beanName.getCanonicalName());

            // Build a list of all the MBean properties as {#PROP<NAME>}
            Hashtable<String, String> pt = beanName.getKeyPropertyList();
            for (Map.Entry<String, String> prop : pt.entrySet())
                bean.put(String.format("{#PROP%s}", prop.getKey().toUpperCase()), prop.getValue());

            beanList.put(bean);
        }

        mapping.put("data", beanList);
        return mapping.toString();
    } catch (Exception e) {
        JSONArray data = new JSONArray();
        JSONObject out = new JSONObject();
        out.put("data", data);

        return out.toString();
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }
}

From source file:com.googlecode.psiprobe.beans.ResourceResolverBean.java

public List getApplicationResources() throws NamingException {
    logger.info("Reading GLOBAL resources");
    List resources = new ArrayList();

    MBeanServer server = getMBeanServer();
    if (server != null) {
        try {/*  w ww .  j a v a2 s.  com*/
            Set dsNames = server.queryNames(new ObjectName("Catalina:type=Resource,resourcetype=Global,*"),
                    null);
            for (Iterator it = dsNames.iterator(); it.hasNext();) {
                ObjectName objectName = (ObjectName) it.next();
                ApplicationResource resource = new ApplicationResource();

                logger.info("reading resource: " + objectName);
                resource.setName(getStringAttribute(server, objectName, "name"));
                resource.setType(getStringAttribute(server, objectName, "type"));
                resource.setScope(getStringAttribute(server, objectName, "scope"));
                resource.setAuth(getStringAttribute(server, objectName, "auth"));
                resource.setDescription(getStringAttribute(server, objectName, "description"));

                lookupResource(resource, true, true);

                resources.add(resource);
            }
        } catch (Exception e) {
            logger.error("There was an error querying JMX server:", e);
        }
    }
    return resources;
}

From source file:com.googlecode.psiprobe.beans.JBossResourceResolverBean.java

public List getApplicationResources() throws NamingException {

    List resources = new ArrayList();

    MBeanServer server = getMBeanServer();
    if (server != null) {
        try {/*from   ww  w .  j a  va 2s. c  o  m*/
            Set dsNames = server.queryNames(new ObjectName("jboss.jca:service=ManagedConnectionPool,*"), null);
            for (Iterator it = dsNames.iterator(); it.hasNext();) {
                ObjectName managedConnectionPoolOName = (ObjectName) it.next();

                ApplicationResource resource = new ApplicationResource();
                resource.setName(managedConnectionPoolOName.getKeyProperty("name"));
                resource.setType("jboss");
                String criteria = (String) server.getAttribute(managedConnectionPoolOName, "Criteria");
                if ("ByApplication".equals(criteria)) {
                    resource.setAuth("Application");
                } else if ("ByContainerAndApplication".equals(criteria)) {
                    resource.setAuth("Both");
                } else {
                    resource.setAuth("Container");
                }
                DataSourceInfo dsInfo = new DataSourceInfo();
                dsInfo.setMaxConnections(
                        ((Integer) server.getAttribute(managedConnectionPoolOName, "MaxSize")).intValue());
                dsInfo.setEstablishedConnections(
                        ((Integer) server.getAttribute(managedConnectionPoolOName, "ConnectionCount"))
                                .intValue());
                dsInfo.setBusyConnections(
                        ((Long) server.getAttribute(managedConnectionPoolOName, "InUseConnectionCount"))
                                .intValue());

                ObjectName connectionFactoryOName = new ObjectName(
                        "jboss.jca:service=ManagedConnectionFactory,name=" + resource.getName());
                Element elm = (Element) server.getAttribute(connectionFactoryOName,
                        "ManagedConnectionFactoryProperties");

                if (elm != null) {
                    NodeList nl = elm.getChildNodes();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        Node na = n.getAttributes().getNamedItem("name");
                        if (na != null) {
                            if ("ConnectionURL".equals(na.getNodeValue())) {
                                dsInfo.setJdbcURL(n.getFirstChild().getNodeValue());
                            }

                            if ("UserName".equals(na.getNodeValue())) {
                                dsInfo.setUsername(n.getFirstChild().getNodeValue());
                            }

                            //
                            // JMS datasource
                            //
                            if ("JmsProviderAdapterJNDI".equals(na.getNodeValue())) {
                                dsInfo.setJdbcURL(n.getFirstChild().getNodeValue());
                                resource.setType("jms");
                            }
                        }
                    }
                }

                dsInfo.setResettable(true);

                resource.setDataSourceInfo(dsInfo);
                resources.add(resource);
            }
        } catch (Exception e) {
            //
            logger.fatal("There was an error querying JBoss JMX server:", e);
        }
    }
    return resources;
}