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:com.tc.stats.DSO.java

private ObjectName makeRootObjectName(String name, ObjectID id) {
    try {//from  ww w. j ava 2  s . co m
        return new ObjectName(DSO_OBJECT_NAME_PREFIX + "rootID=" + id.toLong());
    } catch (MalformedObjectNameException e) {
        // this shouldn't happen
        throw new RuntimeException(e);
    }
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Try to find a nonssl connector to retrieve shared resources like stylesheets, images etc. Fallback: Use request
 * url.//from  w w w  . j  a  va 2  s.  c om
 *
 * @param request
 * @return
 */
private String getLocalURL(final HttpServletRequest request) {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    String requestURL = request.getRequestURL().toString();
    log.warn("No mbeans of type '*:type=Connector,*' configured, using request url (assuming non-ssl): "
            + requestURL);
    return requestURL;
}

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

/**
  * Returns the Server's global naming context
  *// ww  w. j  av a  2 s  .  c  o  m
  * @return the global JNDI context
  */
protected javax.naming.Context getGlobalNamingContext() {

    javax.naming.Context globalContext = null;
    MBeanServer mBeanServer = getMBeanServer();
    if (mBeanServer != null) {
        try {
            ObjectName name = new ObjectName("Catalina:type=Server");
            Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
            //getGlobalNamingContext() was added to Server interface in Tomcat 7.0.11
            if (server instanceof StandardServer) {
                globalContext = ((StandardServer) server).getGlobalNamingContext();
            }
        } catch (Exception e) {
            logger.error("There was an error getting globalContext through JMX server:", e);
        }
    }

    return globalContext;
}

From source file:com.ngdata.hbaseindexer.impl.IndexerModelImplTest.java

public int terminateZooKeeperConnections() throws Exception {
    MBeanServerConnection connection = java.lang.management.ManagementFactory.getPlatformMBeanServer();
    ObjectName replicationSources = new ObjectName(
            "org.apache.ZooKeeperService:name0=*,name1=Connections,name2=*,name3=*");
    Set<ObjectName> mbeans = connection.queryNames(replicationSources, null);
    int connectionCount = mbeans.size();

    for (ObjectName name : mbeans) {
        connection.invoke(name, "terminateConnection", new Object[] {}, new String[] {});
    }/*from  w w w. jav a 2s.c o  m*/

    return connectionCount;
}

From source file:com.ngdata.sep.tools.monitoring.ReplicationStatusRetriever.java

public void addStatusFromJmx(ReplicationStatus replicationStatus) throws Exception {
    JmxConnections jmxConnections = new JmxConnections();

    for (String peerId : replicationStatus.getPeersAndRecoveredQueues()) {
        for (String server : replicationStatus.getServers(peerId)) {
            Status status = replicationStatus.getStatus(peerId, server);
            String hostName = ServerName.parseHostname(server);

            MBeanServerConnection connection = jmxConnections.getConnector(hostName, HBASE_JMX_PORT)
                    .getMBeanServerConnection();

            ObjectName replSourceBean = new ObjectName("hadoop:service=Replication,name=ReplicationSource for "
                    + URLEncoder.encode(peerId, "UTF8"));
            try {
                status.ageOfLastShippedOp = (Long) connection.getAttribute(replSourceBean,
                        "ageOfLastShippedOp");
            } catch (AttributeNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            } catch (InstanceNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            }/* w  ww  .  j  a v  a2  s . c o m*/

            // The following mbean is only available when using NGDATA's ForkedReplicationSource
            ObjectName replSourceInfoBean = new ObjectName(
                    "hadoop:service=Replication,name=ReplicationSourceInfo for "
                            + URLEncoder.encode(peerId, "UTF8"));
            try {
                status.selectedPeerCount = (Integer) connection.getAttribute(replSourceInfoBean,
                        "SelectedPeerCount");
                status.timestampOfLastShippedOp = (Long) connection.getAttribute(replSourceInfoBean,
                        "TimestampLastShippedOp");
                status.sleepReason = (String) connection.getAttribute(replSourceInfoBean, "SleepReason");
                status.sleepMultiplier = (Integer) connection.getAttribute(replSourceInfoBean,
                        "SleepMultiplier");
                status.timestampLastSleep = (Long) connection.getAttribute(replSourceInfoBean,
                        "TimestampLastSleep");
            } catch (AttributeNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
            } catch (InstanceNotFoundException e) {
                // could be the case if the queue disappeared since we read info from ZK
                // or the ForkedReplicationSource isn't used
            }
        }
    }

    jmxConnections.close();
}

From source file:com.espertech.esper.metrics.codahale_metrics.metrics.reporting.JmxReporter.java

@Override
public void onMetricAdded(MetricName name, Metric metric) {
    if (metric != null) {
        try {/*from   ww  w  .  j a  v  a2s  .  c o  m*/
            metric.processWith(this, name, new Context(name, new ObjectName(name.getMBeanName())));
        } catch (Exception e) {
            log.warn("Error processing '" + name + "': " + e.getMessage(), e);
        }
    }
}

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 {//  w ww .j  a  v a2  s . c  o m
        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.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

/**
 * Set the Configuration property via REST interface and check whether the JMX interface returns the same value
 *
 * @throws Exception//from  ww  w.  ja v a 2s .co  m
 */
//TODO: Use the web target JAXRS API to execute these request possibly ?
@Ignore
@Test
public void testSetRESTGetMBeanLocal() throws Exception {
    LOGGER.debug("testSetRESTGetMBeanLocal");
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    ServletTester tester = new ServletTester();
    tester.addServlet(LaxConfigServlet.class, "/config");
    tester.start();

    for (Triple<String, String, String> triple : mbeanAttributes) {
        String attrName = triple.getLeft();
        String attrType = triple.getRight();

        String attrValueStr;
        if (attrType.equals("int"))
            attrValueStr = Integer.toString(RandomUtils.nextInt(30000, 65535));
        else if (attrType.equals("long"))
            attrValueStr = Long.toString(RandomUtils.nextLong(10, 1000));
        else
            attrValueStr = RandomStringUtils.randomAlphabetic(10);

        String str = constructGson(triple.getMiddle(), attrValueStr);

        HttpTester request = new HttpTester();
        request.setMethod("POST");
        request.setHeader("Host", "tester");
        request.setContent(str);
        request.setHeader("Content-Type", "application/json");

        request.setURI("/config");
        HttpTester response = new HttpTester();
        //response = response.parse(tester.getResponses(request.generate()));
        response.parse(tester.getResponses(request.generate()));
        assertEquals("Values do not match", server.getAttribute(name, triple.getLeft()).toString(),
                attrValueStr);

    }
}

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

public void stop() throws IOException {
    MBeanServer server = getMBeanServer();
    IOException error = null;/*from   w w w . jav  a  2  s  .c  o m*/
    if (exposeMBeansAsUPNP.booleanValue()) {
        try {
            ObjectName delegate = new ObjectName("JMImplementation:type=MBeanServerDelegate");
            NotificationEmitter emmiter = (NotificationEmitter) MBeanServerInvocationHandler
                    .newProxyInstance(server, delegate, NotificationEmitter.class, false);
            emmiter.removeNotificationListener(this, null, this);
        } catch (Exception ex) {
            // MX4J throws an unexpected ListenerNotFoundException with jre 1.5.06.. works nice with sun JMX impl
            if (!(ex instanceof ListenerNotFoundException)) {
                IOException ioEx = new IOException("UPNPConnector stop error");
                ioEx.initCause(ex);
                error = ioEx;
            }
        }
        synchronized (STOP_PROCESS) {
            // now stop all the remaining Devices
            for (Iterator i = registeredMBeans.values().iterator(); i.hasNext();) {
                UPNPMBeanDevice dv = (UPNPMBeanDevice) i.next();
                try {
                    dv.stop();
                } catch (IOException ex) {
                    log.error("Error during UPNPMBean device stop", ex);
                }
            }
            registeredMBeans.clear();
        }
    }
    if (exposeUPNPAsMBeans.booleanValue()) {
        try {
            server.unregisterMBean(discoveryBeanName);
        } catch (Exception ex) {
            IOException ioEx = new IOException("Error occured during MBeans discovery");
            ioEx.initCause(ex);
            throw ioEx;
        }
    }
    if (error != null) {
        throw error;
    }
}

From source file:org.jolokia.client.request.J4pReadIntegrationTest.java

@Test
public void mbeanPatternWithAttributes() throws MalformedObjectNameException, J4pException {
    for (J4pReadRequest req : readRequests("*:type=attribute", "LongSeconds", "List")) {
        assertNull(req.getPath());/*from  www.  ja va  2  s.c o m*/
        J4pReadResponse resp = j4pClient.execute(req);
        assertEquals(1, resp.getObjectNames().size());
        Map respVal = resp.getValue();
        Map attrs = (Map) respVal.get(itSetup.getAttributeMBean());
        assertEquals(2, attrs.size());
        assertTrue(attrs.containsKey("LongSeconds"));
        assertTrue(attrs.containsKey("List"));

        Double longVal = resp.getValue(new ObjectName(itSetup.getAttributeMBean()), "LongSeconds");
        assertNotNull(longVal);

        try {
            resp.getValue(new ObjectName(itSetup.getAttributeMBean()), "FCN");
            fail();
        } catch (IllegalArgumentException exp) {
            assertTrue(exp.getMessage().contains("FCN"));
        }
    }
}