Example usage for javax.management MBeanServerConnection queryNames

List of usage examples for javax.management MBeanServerConnection queryNames

Introduction

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

Prototype

public Set<ObjectName> queryNames(ObjectName name, QueryExp query) throws IOException;

Source Link

Document

Gets the names of MBeans controlled by the MBean server.

Usage

From source file:io.mapzone.arena.ArenaPlugin.java

protected void testMBeanConnection() throws Exception {
    // test connection
    String port = System.getProperty("com.sun.management.jmxremote.port");
    if (port != null) {
        String url = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi";
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        try (JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);) {
            MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();
            Set<ObjectName> beanSet = conn.queryNames(null, null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            beanSet = conn.queryNames(ArenaConfigMBean.NAME.get(), null);
            beanSet.forEach(n -> log.debug("    MBean: " + n));

            ArenaConfigMBean arenaConfig = JMX.newMBeanProxy(conn, ArenaConfigMBean.NAME.get(),
                    ArenaConfigMBean.class);
            arenaConfig.setAppTitle("Arena");
        }// w  ww . j a v a  2  s. c  o  m
    } else {
        log.info("No jmxremote.port specified.");
    }
}

From source file:org.jumpmind.symmetric.JmxCommand.java

@Override
protected boolean executeWithOptions(final CommandLine line) throws Exception {
    if (line.hasOption(OPTION_LISTBEANS)) {
        execute(new IJmxTemplate<Object>() {
            @Override/*w  w  w  .  j  av a2  s.  c o  m*/
            public Object execute(String engineName, MBeanServerConnection mbeanConn) throws Exception {
                Set<ObjectName> beanSet = mbeanConn.queryNames(null, null);
                for (ObjectName objectName : beanSet) {
                    if (objectName.getDomain().startsWith("org.jumpmind.symmetric." + engineName)) {
                        System.out.println(objectName.toString());
                    }
                }
                return null;
            }
        });
    } else if (line.hasOption(OPTION_LISTMETHODS) || line.hasOption(OPTION_METHOD)) {
        if (line.hasOption(OPTION_BEAN)) {

            execute(new IJmxTemplate<Object>() {
                @Override
                public Object execute(String engineName, MBeanServerConnection mbeanConn) throws Exception {
                    String beanName = line.getOptionValue(OPTION_BEAN);
                    MBeanInfo info = mbeanConn.getMBeanInfo(new ObjectName(beanName));
                    if (info != null) {
                        if (line.hasOption(OPTION_LISTMETHODS)) {
                            MBeanOperationInfo[] operations = info.getOperations();
                            Map<String, MBeanOperationInfo> orderedMap = new TreeMap<String, MBeanOperationInfo>();
                            for (MBeanOperationInfo methodInfo : operations) {
                                orderedMap.put(methodInfo.getName(), methodInfo);
                            }
                            for (MBeanOperationInfo methodInfo : orderedMap.values()) {
                                System.out.print(methodInfo.getName() + "(");
                                MBeanParameterInfo[] params = methodInfo.getSignature();
                                int index = 0;
                                for (MBeanParameterInfo p : params) {
                                    if (index > 0) {
                                        System.out.print(", ");
                                    }
                                    System.out.print(p.getType() + " " + p.getName());
                                    index++;
                                }
                                System.out.print(")");
                                if (methodInfo.getReturnType() != null
                                        && !methodInfo.getReturnType().equals("void")) {
                                    System.out.print(" : " + methodInfo.getReturnType());
                                }
                                System.out.println();
                            }
                        } else if (line.hasOption(OPTION_METHOD)) {
                            String argsDelimiter = line.getOptionValue(OPTION_ARGS_DELIM);
                            if (isBlank(argsDelimiter)) {
                                argsDelimiter = ",";
                            } else {
                                argsDelimiter = argsDelimiter.trim();
                            }
                            String methodName = line.getOptionValue(OPTION_METHOD);
                            String[] args = null;
                            if (line.hasOption(OPTION_ARGS)) {
                                String argLine = line.getOptionValue(OPTION_ARGS);
                                args = argsDelimiter == "," ? CsvUtils.tokenizeCsvData(argLine)
                                        : argLine.split(argsDelimiter);
                                ;
                            } else {
                                args = new String[0];
                            }

                            MBeanOperationInfo[] operations = info.getOperations();
                            for (MBeanOperationInfo methodInfo : operations) {
                                MBeanParameterInfo[] paramInfos = methodInfo.getSignature();
                                if (methodInfo.getName().equals(methodName)
                                        && paramInfos.length == args.length) {
                                    String[] signature = new String[args.length];
                                    Object[] objArgs = new Object[args.length];
                                    int index = 0;
                                    for (MBeanParameterInfo paramInfo : paramInfos) {
                                        signature[index] = paramInfo.getType();
                                        if (!paramInfo.getType().equals(String.class.getName())) {
                                            Class<?> clazz = Class.forName(paramInfo.getType());
                                            Constructor<?> constructor = clazz.getConstructor(String.class);
                                            objArgs[index] = constructor.newInstance(args[index]);
                                        } else {
                                            objArgs[index] = args[index];
                                        }
                                        index++;
                                    }
                                    Object returnValue = mbeanConn.invoke(new ObjectName(beanName), methodName,
                                            objArgs, signature);
                                    if (methodInfo.getReturnType() != null
                                            && !methodInfo.getReturnType().equals("void")) {
                                        System.out.println(returnValue);
                                    }
                                    System.exit(0);
                                }
                            }

                            System.out.println("ERROR: Could not locate a JMX method named: " + methodName
                                    + " with " + args.length + " arguments on bean: " + beanName);
                            System.exit(1);

                            return null;

                        }
                    } else {
                        System.out.println("ERROR: Could not locate a JMX bean with the name of: " + beanName);
                        System.exit(1);
                    }
                    return null;
                }
            });
        } else {
            System.out.println("ERROR: Must specifiy the --bean option.");
            System.exit(1);
        }
    } else {
        return false;
    }

    return true;
}

From source file:com.googlecode.jmxtrans.model.Query.java

public Iterable<ObjectName> queryNames(MBeanServerConnection mbeanServer) throws IOException {
    return mbeanServer.queryNames(objectName, null);
}

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);
    }/*from   w w  w . j  av  a 2 s.com*/

    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:net.sf.ehcache.management.ManagementServiceTest.java

private void traverseMBeanAttributes(MBeanServerConnection connection, String type)
        throws JMException, IOException {
    Set objectNames = connection.queryNames(new ObjectName("net.sf.ehcache:type=" + type + ",*"), null);
    for (Iterator iterator = objectNames.iterator(); iterator.hasNext();) {
        ObjectName objectName = (ObjectName) iterator.next();
        MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
        MBeanAttributeInfo[] attributes = mBeanInfo.getAttributes();
        for (int i = 0; i < attributes.length; i++) {
            MBeanAttributeInfo attribute = attributes[i];
            LOG.info(attribute.getName() + " " + connection.getAttribute(objectName, attribute.getName()));
        }// w w w  . j  ava 2  s  .  c om
    }
}

From source file:org.helios.jzab.agent.commands.impl.jmx.JMXDiscoveryCommandProcessor.java

/**
 * Var parameters:<ol>/*w ww. ja  v  a 2s.  com*/
 *  <li><b>JMX Object Name</b>: The ObjectName pattern query.</li>
 *  <li><b>Domain</b>: (Optional) Defines the MBeanServer domain in which the target MBeans are registered. Can also be interpreted as a {@link JMXServiceURL} in which case a remote connection will be used to retrieve the attribute values.</li>
 * </ol>
 * {@inheritDoc}
 * @see org.helios.jzab.agent.commands.AbstractCommandProcessor#doExecute(java.lang.String, java.lang.String[])
 */
@Override
protected Object doExecute(String commandName, String... args) throws Exception {
    if (commandName == null || commandName.trim().isEmpty())
        throw new IllegalArgumentException("Null or empty command name", new Throwable());
    if (args == null || args.length < 1)
        throw new IllegalArgumentException("Invalid argument count for command [" + commandName
                + "] with args [" + (args == null ? 0 : args.length) + "]", new Throwable());
    commandName = commandName.trim();
    Map<String, String> tokens = new HashMap<String, String>();
    ObjectName objectName = null;
    try {
        objectName = extractTokens(args[0].trim(), tokens);
    } catch (Exception e) {
        log.error("Invalid ObjectName Requested [{}], Error:[{}]", args[0], e.getMessage());
        throw new RuntimeException(e);
    }
    String domain = null;
    if (args.length > 3) {
        domain = args[3];
    }
    MBeanServerConnection server = null;
    Set<JSONObject> results = new HashSet<JSONObject>();
    try {
        server = getServerForDomain(domain);
        //return JMXHelper.getAttribute(server, compoundDelimiter, on, attrName);

        for (ObjectName on : server.queryNames(objectName, null)) {
            for (Map.Entry<String, String> entry : tokens.entrySet()) {
                String resolvedValue = resolveValue(on.toString(), entry.getKey(), args[0].trim());
                log.debug("Resolved Value [{}] for Token [{}]", resolvedValue, entry.getKey());
                //result.append("\n").append(entry.getValue()).append("--->").append(resolvedValue);
                results.add(new JSONObject(Collections.singletonMap(entry.getKey(), resolvedValue)));
            }
        }
        return results.toArray(new JSONObject[results.size()]);
    } catch (Exception e) {
        log.debug("Failed to get MBeanServerConnection for domain [{}]", domain, e);
        log.error("Failed to get MBeanServerConnection for domain [{}]", domain);
        throw new RuntimeException(e);
    }
}

From source file:org.hyperic.hq.plugin.activemq.EmbeddedActiveMQServerDetector.java

@Override
public List getServerResources(ConfigResponse platformConfig) throws PluginException {
    log.debug("[getServerResources] platformConfig=" + platformConfig);
    List<ServerResource> servers = super.getServerResources(platformConfig);
    List<ServerResource> serversOK = new ArrayList();

    for (ServerResource server : servers) {
        JMXConnector connector = null;
        MBeanServerConnection mServer;
        try {//from   w ww .jav a  2 s .  c o m
            connector = MxUtil.getMBeanConnector(server.getProductConfig().toProperties());
            mServer = connector.getMBeanServerConnection();
            Set<ObjectName> objs = mServer.queryNames(new ObjectName("org.apache.activemq:*"), null);
            log.debug("[getServerResources] objs.size=" + objs.size());
            if (objs.size() > 0) { // Only discover servers with jmx obects on activeMQ domain.
                serversOK.add(server);
            }
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
        } finally {
            try {
                if (connector != null) {
                    connector.close();
                }
            } catch (IOException e) {
                throw new PluginException(e.getMessage(), e);
            }
        }

    }
    return serversOK;
}

From source file:org.zenoss.jmxnl.NotificationListener.java

@SuppressWarnings("unchecked")
private void connect() throws IOException {
    log.info(url + ": Attempting connection (timeout in 180 seconds)");
    JMXConnector connector = JMXConnectorFactory.connect(url, environment);
    connector.addConnectionNotificationListener(this, null, "placeholder");
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    log.info(url + ": Connected.");
    sendConnectionEvent("0", "JMX connection has been restored");

    Set<ObjectName> results = connection.queryNames(scope, null);
    java.util.Iterator<ObjectName> iter = results.iterator();
    while (iter.hasNext()) {
        ObjectName objName = (ObjectName) iter.next();
        String type = objName.getKeyProperty("type");
        if (type == null || !type.equals("alias")) {
            try {
                connection.addNotificationListener(objName, this, attributeFilter, zenossDevice);
                log.debug("Added notification listener: " + objName);
            } catch (IllegalArgumentException e) {
                log.debug("Can't listen to " + objName + " because it is not a notification broadcaster.");
            } catch (InstanceNotFoundException e) {
                log.debug("Can't listen to " + objName + " because it was not found on the server.");
            }//from  www .  ja  va2  s  . c  om
        }

        // There can be a lot of listeners to add. Give other threads a
        // chance to get work done while this happens.
        Thread.yield();
    }
}

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

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all.//w  w w  .ja v  a 2  s.com
 *
 * Note that this test creates a Registry which will keep running until the JVM Exists. There
 * is no way to stop it but it should do no harm.
 *
 *
 */
public void testJMXConnectorServer() throws Exception {

    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);

    LocateRegistry.createRegistry(55000);
    String serverUrl = "service:jmx:rmi:///jndi/rmi://localhost:55000/server";
    JMXServiceURL url = new JMXServiceURL(serverUrl);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
    cs.start();
    JMXConnector connector = cs.toJMXConnector(null);
    connector.connect(null);
    MBeanServerConnection connection = connector.getMBeanServerConnection();
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            connection.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

    Ehcache ehcache = manager.getCache("sampleCache1");

    ehcache.put(new Element("key1", "value1"));
    ehcache.put(new Element("key2", "value1"));
    assertNotNull(ehcache.get("key1"));
    assertNotNull(ehcache.get("key2"));

    //Test CacheManager
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "CacheManager");

    //Test Cache
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "Cache");

    //Test CacheStatistics
    traverseMBeanAttributes(connection, "CacheStatistics");

    //Test CacheConfiguration
    traverseMBeanAttributes(connection, "CacheConfiguration");

    cs.stop();
}

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[] {});
    }/*  ww  w .ja  v  a 2  s .  c o  m*/

    return connectionCount;
}