Example usage for javax.management ObjectName toString

List of usage examples for javax.management ObjectName toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a string representation of the object name.

Usage

From source file:org.ops4j.gaderian.management.TestMBeanRegistry.java

/**
 * Tests the handling of registrations errors during processing of the contributed mbeans
 */// w  w w.ja v a2  s .co m
public void testRegistrationException() throws Exception {
    Registry registry = buildFrameworkRegistry("testMBeanRegistry.xml", false);
    List mBeanList = registry.getConfiguration("gaderian.management.MBeans");

    ServicePoint sp1 = ((MBeanRegistrationContribution) mBeanList.get(0)).getServicePoint();
    ObjectName on1 = objectNameBuilder.createServiceObjectName(sp1);

    // Training
    expect(server.registerMBean(isA(MBeanTestService.class), eq(on1)))
            .andThrow(new MBeanRegistrationException(new Exception("Registration failed")));
    expect(server.registerMBean(isA(MBeanTestService.class), isA(ObjectName.class)))
            .andThrow(new MBeanRegistrationException(new Exception("Registration failed")));
    expect(server.registerMBean(isA(MBeanNonInterfaceTestService.class), isA(ObjectName.class)))
            .andThrow(new MBeanRegistrationException(new Exception("Registration failed")));

    replayAllRegisteredMocks();

    interceptLogging(MBeanRegistry.class.getName());

    new MBeanRegistryImpl(errorHandler, log, server, objectNameBuilder, mBeanList);

    assertLoggedMessage("Registering MBean " + on1.toString() + " failed");

    verifyAllRegisteredMocks();
}

From source file:org.infinispan.server.test.configs.ExampleConfigsTest.java

@Test
public void testHotRodRollingUpgrades() throws Exception {
    // Target node
    final int managementPortServer1 = 9999;
    MBeanServerConnectionProvider provider1;
    // Source node
    final int managementPortServer2 = 10099;
    MBeanServerConnectionProvider provider2;

    controller.start("hotrod-rolling-upgrade-2");
    try {//from  w  w  w  .j  av a2  s. c om
        RemoteInfinispanMBeans s2 = createRemotes("hotrod-rolling-upgrade-2", "local", DEFAULT_CACHE_NAME);
        final RemoteCache<Object, Object> c2 = createCache(s2);

        c2.put("key1", "value1");
        assertEquals("value1", c2.get("key1"));

        for (int i = 0; i < 50; i++) {
            c2.put("keyLoad" + i, "valueLoad" + i);
        }

        controller.start("hotrod-rolling-upgrade-1");

        RemoteInfinispanMBeans s1 = createRemotes("hotrod-rolling-upgrade-1", "local", DEFAULT_CACHE_NAME);
        final RemoteCache<Object, Object> c1 = createCache(s1);

        assertEquals("Can't access etries stored in source node (target's RemoteCacheStore).", "value1",
                c1.get("key1"));

        provider1 = new MBeanServerConnectionProvider(
                s1.server.getHotrodEndpoint().getInetAddress().getHostName(), managementPortServer1);
        provider2 = new MBeanServerConnectionProvider(
                s2.server.getHotrodEndpoint().getInetAddress().getHostName(), managementPortServer2);

        final ObjectName rollMan = new ObjectName("jboss.infinispan:type=Cache," + "name=\"default(local)\","
                + "manager=\"local\"," + "component=RollingUpgradeManager");

        invokeOperation(provider2, rollMan.toString(), "recordKnownGlobalKeyset", new Object[] {},
                new String[] {});

        invokeOperation(provider1, rollMan.toString(), "synchronizeData", new Object[] { "hotrod" },
                new String[] { "java.lang.String" });

        invokeOperation(provider1, rollMan.toString(), "disconnectSource", new Object[] { "hotrod" },
                new String[] { "java.lang.String" });

        // is source (RemoteCacheStore) really disconnected?
        c2.put("disconnected", "source");
        assertEquals("Can't obtain value from cache1 (source node).", "source", c2.get("disconnected"));
        assertNull("Source node entries should NOT be accessible from target node (after RCS disconnection)",
                c1.get("disconnected"));

        // all entries migrated?
        assertEquals("Entry was not successfully migrated.", "value1", c1.get("key1"));
        for (int i = 0; i < 50; i++) {
            assertEquals("Entry was not successfully migrated.", "valueLoad" + i, c1.get("keyLoad" + i));
        }
    } finally {
        if (controller.isStarted("hotrod-rolling-upgrade-1")) {
            controller.stop("hotrod-rolling-upgrade-1");
        }
        if (controller.isStarted("hotrod-rolling-upgrade-2")) {
            controller.stop("hotrod-rolling-upgrade-2");
        }
    }
}

From source file:org.infinispan.server.test.configs.ExampleConfigsTest.java

@Test
public void testRestRollingUpgrades() throws Exception {
    // target node
    final int managementPortServer1 = 9999;
    MBeanServerConnectionProvider provider1;
    // Source node
    final int managementPortServer2 = 10099;
    MBeanServerConnectionProvider provider2;

    controller.start("rest-rolling-upgrade-2");
    try {//from  w w w .j a va  2 s .  c om
        RemoteInfinispanMBeans s2 = createRemotes("rest-rolling-upgrade-2", "local", DEFAULT_CACHE_NAME);
        final RemoteCache<Object, Object> c2 = createCache(s2);

        c2.put("key1", "value1");
        assertEquals("value1", c2.get("key1"));

        for (int i = 0; i < 50; i++) {
            c2.put("keyLoad" + i, "valueLoad" + i);
        }

        controller.start("rest-rolling-upgrade-1");

        RemoteInfinispanMBeans s1 = createRemotes("rest-rolling-upgrade-1", "local", DEFAULT_CACHE_NAME);
        final RemoteCache<Object, Object> c1 = createCache(s1);

        assertEquals("Can't access etries stored in source node (target's RestCacheStore).", "value1",
                c1.get("key1"));

        provider1 = new MBeanServerConnectionProvider(
                s1.server.getRESTEndpoint().getInetAddress().getHostName(), managementPortServer1);
        provider2 = new MBeanServerConnectionProvider(
                s2.server.getRESTEndpoint().getInetAddress().getHostName(), managementPortServer2);

        final ObjectName rollMan = new ObjectName("jboss.infinispan:type=Cache," + "name=\"default(local)\","
                + "manager=\"local\"," + "component=RollingUpgradeManager");

        invokeOperation(provider2, rollMan.toString(), "recordKnownGlobalKeyset", new Object[] {},
                new String[] {});

        invokeOperation(provider1, rollMan.toString(), "synchronizeData", new Object[] { "rest" },
                new String[] { "java.lang.String" });

        invokeOperation(provider1, rollMan.toString(), "disconnectSource", new Object[] { "rest" },
                new String[] { "java.lang.String" });

        // is source (RemoteCacheStore) really disconnected?
        c2.put("disconnected", "source");
        assertEquals("Can't obtain value from cache1 (source node).", "source", c2.get("disconnected"));
        assertNull("Source node entries should NOT be accessible from target node (after RCS disconnection)",
                c1.get("disconnected"));

        // all entries migrated?
        assertEquals("Entry was not successfully migrated.", "value1", c1.get("key1"));
        for (int i = 0; i < 50; i++) {
            assertEquals("Entry was not successfully migrated.", "valueLoad" + i, c1.get("keyLoad" + i));
        }
    } finally {
        if (controller.isStarted("rest-rolling-upgrade-1")) {
            controller.stop("rest-rolling-upgrade-1");
        }
        if (controller.isStarted("rest-rolling-upgrade-2")) {
            controller.stop("rest-rolling-upgrade-2");
        }
    }
}

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

public List getPools() throws Exception {

    List memoryPools = new LinkedList();
    MBeanServer mBeanServer = new Registry().getMBeanServer();
    Set memoryOPools = mBeanServer.queryMBeans(new ObjectName("java.lang:type=MemoryPool,*"), null);

    ///*www  . java2 s.  c  o  m*/
    // totals
    //
    long totalInit = 0;
    long totalMax = 0;
    long totalUsed = 0;
    long totalCommitted = 0;

    for (Iterator it = memoryOPools.iterator(); it.hasNext();) {
        ObjectInstance oi = (ObjectInstance) it.next();
        ObjectName oName = oi.getObjectName();
        MemoryPool memoryPool = new MemoryPool();
        memoryPool.setName(JmxTools.getStringAttr(mBeanServer, oName, "Name"));
        memoryPool.setType(JmxTools.getStringAttr(mBeanServer, oName, "Type"));

        CompositeDataSupport cd = (CompositeDataSupport) mBeanServer.getAttribute(oName, "Usage");
        //
        // It seems that "Usage" attribute of one of the pools may turn into null intermittently. We better have a
        // dip in the graph then an NPE though.
        //
        if (cd != null) {
            memoryPool.setMax(JmxTools.getLongAttr(cd, "max"));
            memoryPool.setUsed(JmxTools.getLongAttr(cd, "used"));
            memoryPool.setInit(JmxTools.getLongAttr(cd, "init"));
            memoryPool.setCommitted(JmxTools.getLongAttr(cd, "committed"));
        } else {
            logger.error("Oops, JVM problem? " + oName.toString() + " \"Usage\" attribute is NULL!");
        }

        totalInit += memoryPool.getInit();
        totalMax += memoryPool.getMax();
        totalUsed += memoryPool.getUsed();
        totalCommitted += memoryPool.getCommitted();

        memoryPools.add(memoryPool);
    }

    if (!memoryPools.isEmpty()) {
        MemoryPool pool = new MemoryPool();
        pool.setName("Total");
        pool.setType("TOTAL");
        pool.setInit(totalInit);
        pool.setUsed(totalUsed);
        pool.setMax(totalMax);
        pool.setCommitted(totalCommitted);
        memoryPools.add(pool);
    }

    return memoryPools;

}

From source file:net.sbbi.upnp.jmx.upnp.UPNPConnectorServer.java

public void handleNotification(Notification notification, Object handBack) {

    if (notification.getType().equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
        MBeanServerNotification regNot = (MBeanServerNotification) notification;
        MBeanServer srv = getMBeanServer();
        ObjectName name = regNot.getMBeanName();
        try {/*from www.  j  a  va  2s. c o m*/
            ObjectInstance objIn = srv.getObjectInstance(name);
            String className = objIn.getClassName();
            // do not expose as UPN, UPNP devices exposed as MBeans ( class UPNPServiceMBean purpose )
            if (className.equals(UPNPServiceMBean.class.getName()))
                return;
            if (builder.select(name, className)) {
                MBeanInfo info = srv.getMBeanInfo(name);
                UPNPMBeanDevice dv = builder.buildUPNPMBean(getMBeanServer(), objIn, info);
                if (dv != null) {
                    dv.setBindAddress(sktAddress);
                    dv.start();
                    registeredMBeans.put(name.toString(), dv);
                }
            }
        } catch (Exception ex) {
            log.error("Error during UPNP Mbean device " + name.toString() + " creation", ex);
        }
    } else if (notification.getType().equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
        MBeanServerNotification regNot = (MBeanServerNotification) notification;
        String beanName = regNot.getMBeanName().toString();
        synchronized (STOP_PROCESS) {
            UPNPMBeanDevice dv = (UPNPMBeanDevice) registeredMBeans.get(beanName);
            if (dv != null) {
                try {
                    dv.stop();
                } catch (Exception ex) {
                    log.error("Error during UPNPMBean device stop", ex);
                }
                registeredMBeans.remove(beanName);
            }
        }
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private void registerMbean() {
    ObjectName objectName = null;
    MBeanServer mBeanServer = null;
    try {/*  w  w w .  j av a2 s  .co m*/
        objectName = new ObjectName(KeystoreEditor.class.getName() + ":service=keystore");
        mBeanServer = ManagementFactory.getPlatformMBeanServer();
    } catch (MalformedObjectNameException e) {
        LOGGER.error("Unable to create Keystore Editor MBean.", e);
    }
    if (mBeanServer != null) {
        try {
            try {
                mBeanServer.registerMBean(this, objectName);
                LOGGER.info("Registered Keystore Editor MBean under object name: {}", objectName.toString());
            } catch (InstanceAlreadyExistsException e) {
                // Try to remove and re-register
                mBeanServer.unregisterMBean(objectName);
                mBeanServer.registerMBean(this, objectName);
                LOGGER.info("Re-registered Keystore Editor MBean");
            }
        } catch (Exception e) {
            LOGGER.error("Could not register MBean [{}].", objectName.toString(), e);
        }
    }
}

From source file:org.apache.hadoop.hdfs.server.common.MetricsLoggerTask.java

/**
 * Write metrics to the metrics appender when invoked.
 *//*from w  w  w. j av a2  s .  c o m*/
@Override
public void run() {
    // Skip querying metrics if there are no known appenders.
    if (!metricsLog.isInfoEnabled() || !hasAppenders(metricsLog) || objectName == null) {
        return;
    }

    metricsLog.info(" >> Begin " + nodeName + " metrics dump");
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    // Iterate over each MBean.
    for (final ObjectName mbeanName : server.queryNames(objectName, null)) {
        try {
            MBeanInfo mBeanInfo = server.getMBeanInfo(mbeanName);
            final String mBeanNameName = MBeans.getMbeanNameName(mbeanName);
            final Set<String> attributeNames = getFilteredAttributes(mBeanInfo);

            final AttributeList attributes = server.getAttributes(mbeanName,
                    attributeNames.toArray(new String[attributeNames.size()]));

            for (Object o : attributes) {
                final Attribute attribute = (Attribute) o;
                final Object value = attribute.getValue();
                final String valueStr = (value != null) ? value.toString() : "null";
                // Truncate the value if it is too long
                metricsLog.info(mBeanNameName + ":" + attribute.getName() + "=" + trimLine(valueStr));
            }
        } catch (Exception e) {
            metricsLog.error("Failed to get " + nodeName + " metrics for mbean " + mbeanName.toString(), e);
        }
    }
    metricsLog.info(" << End " + nodeName + " metrics dump");
}

From source file:org.apache.webapp.admin.context.SaveContextAction.java

/**
 * Append nodes for any define resources for the specified Context.
 *
 * @param containerNode Container node for the tree control
 * @param containerName Object name of the parent container
 * @param resources The MessageResources for our localized messages
 *  messages/*from   ww w . ja v a 2 s.  c o m*/
 */
public void addToTreeControlNode(ObjectName oname, String containerName, String parentName,
        MessageResources resources, HttpSession session) throws Exception {

    String domain = oname.getDomain();
    TreeControl control = (TreeControl) session.getAttribute("treeControlTest");
    if (control != null) {
        TreeControlNode parentNode = control.findNode(parentName);
        if (parentNode != null) {
            String type = "Context";
            String path = "";
            String host = "";
            String name = oname.getKeyProperty("name");
            if ((name != null) && (name.length() > 0)) {
                name = name.substring(2);
                int i = name.indexOf("/");
                host = name.substring(0, i);
                path = name.substring(i);
            }
            String nodeLabel = "Context (" + path + ")";
            String encodedName = URLEncoder.encode(oname.toString());
            TreeControlNode childNode = new TreeControlNode(oname.toString(), "Context.gif", nodeLabel,
                    "EditContext.do?select=" + encodedName, "content", true, domain);
            parentNode.addChild(childNode);

            // FIXME - force a redisplay
            TreeControlNode subtree = new TreeControlNode("Context Resource Administration " + containerName,
                    "folder_16_pad.gif", resources.getMessage("resources.treeBuilder.subtreeNode"), null,
                    "content", true, domain);
            childNode.addChild(subtree);
            TreeControlNode datasources = new TreeControlNode("Context Data Sources " + containerName,
                    "Datasource.gif", resources.getMessage("resources.treeBuilder.datasources"),
                    "resources/listDataSources.do?resourcetype=" + URLEncoder.encode(type) + "&path="
                            + URLEncoder.encode(path) + "&host=" + URLEncoder.encode(host) + "&forward="
                            + URLEncoder.encode("DataSources List Setup"),
                    "content", false, domain);
            TreeControlNode mailsessions = new TreeControlNode("Context Mail Sessions " + containerName,
                    "Mailsession.gif", resources.getMessage("resources.treeBuilder.mailsessions"),
                    "resources/listMailSessions.do?resourcetype=" + URLEncoder.encode(type) + "&path="
                            + URLEncoder.encode(path) + "&host=" + URLEncoder.encode(host) + "&forward="
                            + URLEncoder.encode("MailSessions List Setup"),
                    "content", false, domain);
            TreeControlNode resourcelinks = new TreeControlNode("Resource Links " + containerName,
                    "ResourceLink.gif", resources.getMessage("resources.treeBuilder.resourcelinks"),
                    "resources/listResourceLinks.do?resourcetype=" + URLEncoder.encode(type) + "&path="
                            + URLEncoder.encode(path) + "&host=" + URLEncoder.encode(host) + "&forward="
                            + URLEncoder.encode("ResourceLinks List Setup"),
                    "content", false, domain);
            TreeControlNode envs = new TreeControlNode("Context Environment Entries " + containerName,
                    "EnvironmentEntries.gif", resources.getMessage("resources.env.entries"),
                    "resources/listEnvEntries.do?resourcetype=" + URLEncoder.encode(type) + "&path="
                            + URLEncoder.encode(path) + "&host=" + URLEncoder.encode(host) + "&forward="
                            + URLEncoder.encode("EnvEntries List Setup"),
                    "content", false, domain);
            subtree.addChild(datasources);
            subtree.addChild(mailsessions);
            subtree.addChild(resourcelinks);
            subtree.addChild(envs);
        } else {
            getServlet().log("Cannot find parent node '" + parentName + "'");
        }
    } else {
        getServlet().log("Cannot find TreeControlNode!");
    }
}

From source file:org.hyperic.hq.product.jmx.MxServerQuery.java

private void findServices(MBeanServerConnection mServer, MxServiceQuery query) throws PluginException {

    boolean isDebug = log.isDebugEnabled();

    query.initialize();//  w  ww.  j a  v a  2  s  .  c  om

    Set services;
    ObjectName name;
    String mbeanClass = query.getMBeanClass();

    String filter = query.getObjectNameFilter();
    StringMatcher matcher = null;
    if (filter != null) {
        matcher = new StringMatcher();
        if (filter.charAt(0) == '!') {
            matcher.setExcludes(filter.substring(1));
        } else {
            matcher.setIncludes(filter);
        }
    }

    try {
        name = new ObjectName(query.getQueryName());
        log.debug("[findServices] name=" + name);
        services = mServer.queryNames(name, null);
        log.debug("[findServices] services=(" + services.size() + ")" + services);
    } catch (MalformedObjectNameException e) {
        String msg = query.getQueryName() + ": " + e.getMessage();
        throw new IllegalArgumentException(msg);
    } catch (RemoteException e) {
        throw new PluginException("Cannot connect to server", e);
    } catch (IOException e) {
        throw new PluginException("Cannot connect to server", e);
    }

    for (Iterator it = services.iterator(); it.hasNext();) {
        name = (ObjectName) it.next();

        if ((matcher != null) && !matcher.matches(name.toString())) {
            if (isDebug) {
                log.debug("[" + name + "] !matches(" + matcher + ")");
            }
            continue;
        }

        if (!query.apply(name)) {
            continue;
        }

        if (mbeanClass != null) {
            try {
                MBeanInfo info = mServer.getMBeanInfo(name);
                if (!info.getClassName().matches(mbeanClass)) {
                    if (isDebug) {
                        log.debug("[" + name + "] " + info.getClassName() + " !instanceof " + mbeanClass);
                    }
                    continue;
                }
            } catch (Exception e) {
                log.error("mServer.getMBeanInfo(" + name + "): " + e);
                continue;
            }
        }

        MxServiceQuery service = query.cloneInstance();
        service.setObjectName(name);

        this.services.add(service);
        service.setParent(this);
        service.setServerQuery(this);
        service.getAttributes(mServer);
    }
}

From source file:org.mc4j.ems.impl.jmx.connection.DConnection.java

private DMBean mapBean(ObjectName objectName, boolean loadSynchronous) {
    DMBean bean = null;/* ww  w. j  a  v  a 2  s . c  o m*/
    DObjectName dObjectName = new DObjectName(objectName);

    // If the bean is unknown to the internal map, create our local representation and add it
    synchronized (this) {
        if (!this.beanMap.keySet().contains(dObjectName)) {
            if (isJMX12) {
                bean = new DAdvancedBean(connectionProvider, objectName);
            } else {
                bean = new DMBean(connectionProvider, objectName);
            }
            beanMap.put(dObjectName, bean);
        }
    }

    // If the bean was just created then optional load its metadata synchronously
    // Do this outside the synchronized block
    if (bean != null && loadSynchronous) {
        try {
            bean.loadSynchronous();
        } catch (EmsUnsupportedTypeException e) {
            // Keep loading other beans even if one has an unsupported type
            log.info("Bean metadata not loaded, unsupported type on [" + objectName.toString() + "]", e);
        }
    }

    if (bean == null) {
        return (DMBean) this.beanMap.get(dObjectName);
    } else {
        return bean;
    }
}