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:org.jolokia.client.request.J4pReadIntegrationTest.java

@Test
public void allAttributes() throws MalformedObjectNameException, J4pException {
    for (J4pReadRequest req : readRequests(itSetup.getAttributeMBean())) {
        J4pReadResponse resp = j4pClient.execute(req);
        assertFalse(req.hasSingleAttribute());
        assertTrue(req.hasAllAttributes());
        assertEquals(0, req.getAttributes().size());
        Map respVal = resp.getValue();
        assertTrue(respVal.containsKey("LongSeconds"));
        assertTrue(respVal.containsKey("SmallMinutes"));
        assertTrue(respVal.size() > 20);

        Collection<String> attrs = resp.getAttributes(new ObjectName(itSetup.getAttributeMBean()));
        Set<String> attrSet = new HashSet<String>(attrs);
        assertTrue(attrSet.contains("LongSeconds"));
        assertTrue(attrSet.contains("SmallMinutes"));

        try {// ww w  . ja v a 2s.  co  m
            resp.getAttributes(new ObjectName("blub:type=bla"));
            fail();
        } catch (IllegalArgumentException exp) {
            assertTrue(exp.getMessage().contains(itSetup.getAttributeMBean()));
        }

        Set<String> allAttrs = new HashSet<String>(resp.getAttributes());
        assertTrue(allAttrs.size() > 20);
        assertTrue(allAttrs.contains("Name"));
        assertTrue(allAttrs.contains("Bytes"));

        Long val = resp.getValue(new ObjectName(itSetup.getAttributeMBean()), "MemoryUsed");
        assertNotNull(val);

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

        Long bytes = resp.getValue("Bytes");
        assertNotNull(bytes);

        try {
            req.getAttribute();
            fail();
        } catch (IllegalArgumentException exp) {
            assertTrue(exp.getMessage().contains("than one"));
        }
    }
}

From source file:de.tudarmstadt.lt.lm.app.StartLM.java

@SuppressWarnings("static-access")
public StartLM(String[] args) {
    Options opts = new Options();
    opts.addOption(new Option("?", "help", false, "display this message"));
    opts.addOption(OptionBuilder.withLongOpt("host").withArgName("hostname").hasArg()
            .withDescription("specifies the hostname on which the rmi registry listens (default: localhost)")
            .create("h"));
    opts.addOption(OptionBuilder.withLongOpt("rmiport").withArgName("port-number").hasArg()
            .withDescription(String.format("specifies the port on which rmi registry listens (default: %d)",
                    Registry.REGISTRY_PORT))
            .create("rp"));
    opts.addOption(OptionBuilder.withLongOpt("port").withArgName("port-number").hasArg().withDescription(
            "specifies the port on which this service should populate (default: 0, which means a random port will be assigned)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("lmtype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model that you want to use: {BerkeleyLM, CountingLM, LaplaceSmoothedLM, CountingStringLM, KneserNeyLM, (experimental: KneserNeyLMRecursive, PoptKneserNeyLMRecursive, ModifiedKNeserNeyLMRecursive)} (default: BerkeleyLM)")
            .create("t"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("pt"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(//from w w  w  . j  av  a  2  s .c o  m
                    "specify the directory that contains '.txt' files that are used as source for this language model")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("order").withArgName("ngram-order").hasArg()
            .withDescription("specify the order for this language model").create("n"));
    opts.addOption(OptionBuilder.withLongOpt("identifier").withArgName("name").hasArg().withDescription(
            "specify a name/identifier for the language model. If no name is given, a random name will be generated.")
            .create("i"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite")
            .withDescription("Overwrite existing saved or temporary files.").create("w"));
    opts.addOption(OptionBuilder.withLongOpt("discount").withArgName("Discount value in [0,1]").hasArg()
            .withDescription("Uniform discount value for Lucene based Kneser-Ney LM.").create());
    opts.addOption(OptionBuilder.withLongOpt("mincount").withArgName("int").hasArg().withDescription(
            "(Only applicable for Lucene Based LMs) - Specify the number of times an ngram must occur to be considered in further calculations. Ngrams with counts below mincount are filtered. (default: 1).")
            .create("m"));

    try {
        CommandLine cmd = new ExtendedGnuParser(true).parse(opts, args);
        if (cmd.hasOption("help"))
            CliUtils.print_usage_quit(System.err, StartLM.class.getSimpleName(), opts, USAGE_HEADER, null, 0);

        _rmiRegistryPort = Integer
                .parseInt(cmd.getOptionValue("rmiport", String.valueOf(Registry.REGISTRY_PORT)));
        _port = Integer.parseInt(cmd.getOptionValue("port", "0"));
        _srcdir = cmd.getOptionValue("dir");
        _n = Integer.parseInt(cmd.getOptionValue("order", "5"));
        _type_lm = cmd.getOptionValue("lmtype", BerkeleyLM.class.getSimpleName());
        _type_provider = cmd.getOptionValue("ptype", LtSegProvider.class.getSimpleName());
        _name = cmd.getOptionValue("identifier", String.valueOf(System.currentTimeMillis()));
        _host = cmd.getOptionValue("host", "localhost");
        _overwrite = cmd.hasOption("overwrite");
        _discount = Double.parseDouble(cmd.getOptionValue("discount", "-1"));
        _mincount = Integer.parseInt(cmd.getOptionValue("mincount", "1"));
        // String[] non_named_args = cmd.getArgs();
        _providerJmxBeanName = new ObjectName("de.tudarmstadt.lt.lm:type=ProviderService");

    } catch (Exception e) {
        LOG.error("{}: {}", e.getClass().getSimpleName(), e.getMessage());
        CliUtils.print_usage_quit(System.err, StartLM.class.getSimpleName(), opts, USAGE_HEADER,
                String.format("%s: %s%n", e.getClass().getSimpleName(), e.getMessage()), 1);
    }
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public int getThreadCount() throws Exception {
    ObjectName mbeanName;//from w  w  w  . j  a v a2 s  .  c  om
    mbeanName = new ObjectName("java.lang:type=Threading");
    Integer ut;
    ut = (Integer) mbsc.getAttribute(mbeanName, "ThreadCount");
    return ut.intValue();
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java

/**
 * Set the MBean attribute value using the local platform MBean server and check whether the
 * returned value matches the set value/*from  www.  j ava 2s.  c  o  m*/
 *
 * @throws Exception
 */
@Test
public void testSetGetMBeanLocal() throws Exception {
    ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME);
    testSetGetAttribute(server, name);
}

From source file:FullThreadDump.java

/**
 * Constructs a ThreadMonitor object to get thread information in a remote
 * JVM./*ww  w  .  ja  v  a2s .  c  o  m*/
 */
public ThreadMonitor(MBeanServerConnection server) throws IOException {
    this.server = server;
    this.tmbean = newPlatformMXBeanProxy(server, THREAD_MXBEAN_NAME, ThreadMXBean.class);
    try {
        objname = new ObjectName(THREAD_MXBEAN_NAME);
    } catch (MalformedObjectNameException e) {
        // should not reach here
        InternalError ie = new InternalError(e.getMessage());
        ie.initCause(e);
        throw ie;
    }
    parseMBeanInfo();
}

From source file:org.xmatthew.spy2servers.component.spy.jmx.JmxSpySupportComponent.java

public Map<String, Object> getAttributesAsMap(String mbeanName, MBeanServerConnection mbsc) throws Exception {
    ObjectName mbean = new ObjectName(mbeanName);
    MBeanInfo info = null;// w  w w.  j  a  v a 2s.c  o  m
    try {
        info = mbsc.getMBeanInfo(mbean);
    } catch (Exception e) {
        //ignore the exception
    }

    if (info != null) {
        MBeanAttributeInfo[] attributes;
        attributes = info.getAttributes();
        if (attributes == null) {
            return null;
        }

        int size = attributes.length;
        if (size == 0) {
            return null;
        }

        Map<String, Object> beansMap = new HashMap<String, Object>(size);
        for (int i = 0; i < size; i++) {
            try {
                beansMap.put(attributes[i].getName(), mbsc.getAttribute(mbean, attributes[i].getName()));
            } catch (Exception e) {
                //ignore the exception
            }
        }
        return beansMap;
    }
    return null;
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Integration test for the registration service
 *//*from w  ww.jav  a  2 s.  c om*/
public void testRegistrationServiceNoneTrue() throws Exception {
    ManagementService.registerMBeans(manager, mBeanServer, false, false, false, false);
    assertEquals(0, mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

}

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 {/* www .  j av  a 2 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:com.enioka.jqm.tools.JndiContext.java

@Override
public Object lookup(String name) throws NamingException {
    if (name == null) {
        throw new IllegalArgumentException("name cannot be null");
    }//from   w ww .  j  a va 2 s.c o m
    jqmlogger.trace("Looking up a JNDI element named " + name);

    // Special delegated cases
    if (name.startsWith("rmi:")) {
        try {
            return this.r.lookup(name.split("/")[3]);
        } catch (Exception e) {
            NamingException e1 = new NamingException();
            e1.setRootCause(e);
            throw e1;
        }
    }
    if (name.endsWith("serverName")) {
        return JqmEngine.latestNodeStartedName;
    }

    // If in cache...
    if (singletons.containsKey(name)) {
        jqmlogger.trace("JNDI element named " + name + " found in cache.");
        return singletons.get(name);
    }

    // Retrieve the resource description from the database or the XML file
    JndiResourceDescriptor d = ResourceParser.getDescriptor(name);
    jqmlogger.trace("JNDI element named " + name + " not found in cache. Will be created. Singleton status: "
            + d.isSingleton());

    // Singleton handling is synchronized to avoid double creation
    if (d.isSingleton()) {
        synchronized (singletons) {
            if (singletons.containsKey(name)) {
                return singletons.get(name);
            }

            // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
            // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
            Object res = null;
            try {
                ResourceFactory rf = new ResourceFactory(Thread.currentThread()
                        .getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                                ? Thread.currentThread().getContextClassLoader()
                                : extResources);
                res = rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
            } catch (Exception e) {
                jqmlogger.warn("Could not instanciate singleton JNDI object resource " + name, e);
                NamingException ex = new NamingException(e.getMessage());
                ex.initCause(e);
                throw ex;
            }

            // Cache result
            if (res.getClass().getClassLoader() instanceof JarClassLoader) {
                jqmlogger.warn(
                        "A JNDI resource was defined as singleton but was loaded by a payload class loader - it won't be cached to avoid class loader leaks");
            } else {
                singletons.put(name, res);

                // Pool JMX registration (only if cached - avoids leaks)
                if ("org.apache.tomcat.jdbc.pool.DataSourceFactory".equals(d.getFactoryClassName())
                        && (d.get("jmxEnabled") == null ? true
                                : Boolean.parseBoolean((String) d.get("jmxEnabled").getContent()))) {
                    try {
                        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                        ObjectName jmxname = new ObjectName("com.enioka.jqm:type=JdbcPool,name=" + name);
                        mbs.registerMBean(res.getClass().getMethod("getPool").invoke(res).getClass()
                                .getMethod("getJmxPool")
                                .invoke(res.getClass().getMethod("getPool").invoke(res)), jmxname);
                        jmxNames.add(jmxname);
                    } catch (Exception e) {
                        jqmlogger.warn("Could not register JMX MBean for resource.", e);
                    }
                }
            }

            // Done
            return res;
        }
    }

    // Non singleton
    try {
        // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
        // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
        ResourceFactory rf = new ResourceFactory(
                Thread.currentThread().getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                        ? Thread.currentThread().getContextClassLoader()
                        : extResources);
        return rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
    } catch (Exception e) {
        jqmlogger.warn("Could not instanciate JNDI object resource " + name, e);
        NamingException ex = new NamingException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:io.github.albertopires.mjc.JConsoleM.java

public int getLoadedClassCount() throws Exception {
    ObjectName mbeanName;//from  w ww  .  j  a v a2  s  . c o  m
    mbeanName = new ObjectName("java.lang:type=ClassLoading");
    Integer ut;
    ut = (Integer) mbsc.getAttribute(mbeanName, "LoadedClassCount");
    return ut.intValue();
}