Example usage for javax.management MBeanServer queryNames

List of usage examples for javax.management MBeanServer queryNames

Introduction

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

Prototype

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

Source Link

Usage

From source file:org.apache.solr.cloud.api.collections.CollectionsAPIDistributedZkTest.java

private void checkNoTwoShardsUseTheSameIndexDir() throws Exception {
    Map<String, Set<String>> indexDirToShardNamesMap = new HashMap<>();

    List<MBeanServer> servers = new LinkedList<>();
    servers.add(ManagementFactory.getPlatformMBeanServer());
    servers.addAll(MBeanServerFactory.findMBeanServer(null));
    for (final MBeanServer server : servers) {
        Set<ObjectName> mbeans = new HashSet<>();
        mbeans.addAll(server.queryNames(null, null));
        for (final ObjectName mbean : mbeans) {

            try {
                Map<String, String> props = mbean.getKeyPropertyList();
                String category = props.get("category");
                String name = props.get("name");
                if ((category != null && category.toString().equals(Category.CORE.toString()))
                        && (name != null && name.equals("indexDir"))) {
                    String indexDir = server.getAttribute(mbean, "Value").toString();
                    String key = props.get("dom2") + "." + props.get("dom3") + "." + props.get("dom4");
                    if (!indexDirToShardNamesMap.containsKey(indexDir)) {
                        indexDirToShardNamesMap.put(indexDir.toString(), new HashSet<>());
                    }// w  w  w  .  j av  a2  s  .  co  m
                    indexDirToShardNamesMap.get(indexDir.toString()).add(key);
                }
            } catch (Exception e) {
                // ignore, just continue - probably a "Value" attribute
                // not found
            }
        }
    }

    assertTrue(
            "Something is broken in the assert for no shards using the same indexDir - probably something was changed in the attributes published in the MBean of "
                    + SolrCore.class.getSimpleName() + " : " + indexDirToShardNamesMap,
            indexDirToShardNamesMap.size() > 0);
    for (Entry<String, Set<String>> entry : indexDirToShardNamesMap.entrySet()) {
        if (entry.getValue().size() > 1) {
            fail("We have shards using the same indexDir. E.g. shards " + entry.getValue().toString()
                    + " all use indexDir " + entry.getKey());
        }
    }

}

From source file:org.rhq.plugins.jbossas.JBossASDiscoveryComponent.java

@Nullable
private DiscoveredResourceDetails discoverJBossPcIsEmbeddedIn(ResourceDiscoveryContext context) {
    MBeanServer server = JBossMBeanUtility.getJBossMBeanServer();

    try {/*from  ww w.  j  av  a 2 s . c  o m*/
        String jnpAddress = null;
        String jnpPort = null;
        ObjectName namingObjectName = new ObjectName("jboss:service=Naming");
        Set namingSet = server.queryNames(namingObjectName, null);
        if (namingSet.iterator().hasNext()) {
            jnpAddress = (String) server.getAttribute(namingObjectName, "BindAddress");
            jnpPort = String.valueOf(server.getAttribute(namingObjectName, "Port"));
        }

        String bindAddress = null;
        ObjectName systemPropertiesObjectName = new ObjectName("jboss:name=SystemProperties,type=Service");
        Set systemPropertiesSet = server.queryNames(systemPropertiesObjectName, null);
        if (systemPropertiesSet.iterator().hasNext()) {
            bindAddress = (String) server.invoke(systemPropertiesObjectName, "get",
                    new Object[] { JBossProperties.BIND_ADDRESS }, new String[] { String.class.getName() });
        }
        if (bindAddress == null) {
            bindAddress = jnpAddress;
        }

        ObjectName configObjectName = new ObjectName("jboss.system:type=ServerConfig");
        Set set = server.queryNames(configObjectName, null);
        if (set.iterator().hasNext()) {
            // ServerConfig MBean found
            File homeDir = (File) server.getAttribute(configObjectName, "HomeDir");
            JBossInstallationInfo installInfo;
            try {
                installInfo = new JBossInstallationInfo(homeDir);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Failed to determine installation info for JBoss home dir [" + homeDir + "].", e);
            }
            File configDir = (File) server.getAttribute(configObjectName, "ServerHomeDir");

            //if (isEmbeddedInServer(configDir)) {
            //    return null; // abort - we are embedded, but we're inside the enterprise Server
            //}

            String configName = (String) server.getAttribute(configObjectName, "ServerName");
            String version = (String) server.getAttribute(configObjectName, "SpecificationVersion");

            Configuration pluginConfiguration = context.getDefaultPluginConfiguration();

            // Set the connection type (used by JMX plugin to connect to the MBean server).
            pluginConfiguration.put(new PropertySimple(JMXDiscoveryComponent.CONNECTION_TYPE,
                    InternalVMTypeDescriptor.class.getName()));

            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.JBOSS_HOME_DIR_CONFIG_PROP, homeDir));
            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_PATH_CONFIG_PROP, configDir));
            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_SET_CONFIG_PROP, configName));

            // Now set default values on any props that are still not set.
            setPluginConfigurationDefaults(pluginConfiguration);

            JBossProductType productType = installInfo.getProductType();
            String name = formatServerName(bindAddress, jnpPort, context.getSystemInformation().getHostname(),
                    configName, productType, isRhqServer(configDir));
            String description = productType.NAME + " server that the RHQ Plugin Container is running within";
            DiscoveredResourceDetails resource = new DiscoveredResourceDetails(context.getResourceType(),
                    configDir.getAbsolutePath(), name, version, description, pluginConfiguration, null);

            return resource;
        }
    } catch (Exception e) {
        // JBoss MBean doesn't exist - not a JBoss server.
        log.debug("Not detected to be embedded in a JBoss AS Server", e);
    }

    return null;
}

From source file:com.jkoolcloud.tnt4j.streams.custom.kafka.interceptors.reporters.metrics.MetricsReporter.java

/**
 * Collects JMX attributes of MBeans defined by <tt>objNameStr</tt>.
 *
 * @param objNameStr//from  w  ww . ja  va 2s .com
 *            MBeans object name pattern to query
 * @param mBeanServer
 *            MBean server instance to use
 * @param activity
 *            activity instance to put JMX metrics snapshots
 * @throws Exception
 *             if JMX attributes collecting fails
 */
public void collectMetricsJMX(String objNameStr, MBeanServer mBeanServer, Activity activity) throws Exception {
    ObjectName oName = new ObjectName(objNameStr);
    Set<ObjectName> metricsBeans = mBeanServer.queryNames(oName, null);

    for (ObjectName mBeanName : metricsBeans) {
        try {
            PropertySnapshot snapshot = new PropertySnapshot(mBeanName.getCanonicalName());
            MBeanInfo metricsBean = mBeanServer.getMBeanInfo(mBeanName);
            MBeanAttributeInfo[] pMetricsAttrs = metricsBean.getAttributes();
            for (MBeanAttributeInfo pMetricsAttr : pMetricsAttrs) {
                try {
                    String attrName = pMetricsAttr.getName();
                    Object attrValue = mBeanServer.getAttribute(mBeanName, attrName);
                    processAttrValue(snapshot, new PropertyNameBuilder(pMetricsAttr.getName()), attrValue);
                } catch (Exception exc) {
                    Utils.logThrowable(LOGGER, OpLevel.WARNING,
                            StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                            "MetricsReporter.bean.attr.fail", mBeanName, pMetricsAttr.getName(), exc);
                }
            }

            if (getSnapshotPropIgnoreCase(snapshot, OBJ_NAME_ENTRY_KEY) == null) {
                snapshot.add(OBJ_NAME_ENTRY_KEY, mBeanName.getCanonicalName());
            }
            if (useObjectNameProperties) {
                snapshot.add("domain", mBeanName.getDomain()); // NON-NLS
                Map<String, String> objNameProps = mBeanName.getKeyPropertyList();
                for (Map.Entry<String, String> objNameProp : objNameProps.entrySet()) {
                    String propKey = objNameProp.getKey();
                    Object mv = snapshot.get(propKey);
                    snapshot.add(propKey + (mv == null ? "" : "_"), objNameProp.getValue()); // NON-NLS
                }
            }
            activity.addSnapshot(snapshot);
        } catch (Exception exc) {
            Utils.logThrowable(LOGGER, OpLevel.WARNING,
                    StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                    "MetricsReporter.bean.info.fail", mBeanName, exc);
        }
    }
}

From source file:org.wso2.carbon.caching.impl.CacheImpl.java

private void registerMBean() {
    String serverPackage = "org.wso2.carbon";
    try {/*w w w. j  a  va2  s  .c  o m*/
        String objectName = serverPackage + ":type=Cache,tenant=" + ownerTenantDomain + ",manager="
                + cacheManager.getName() + ",name=" + cacheName;
        MBeanServer mserver = getMBeanServer();
        cacheMXBeanObjName = new ObjectName(objectName);
        Set set = mserver.queryNames(new ObjectName(objectName), null);
        if (set.isEmpty()) {
            CacheMXBeanImpl cacheMXBean = new CacheMXBeanImpl(this, ownerTenantDomain, ownerTenantId);
            mserver.registerMBean(cacheMXBean, cacheMXBeanObjName);
        }
    } catch (Exception e) {
        String msg = "Could not register CacheMXBeanImpl MBean";
        log.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Unregister MBeans loaded by the web application class loader
 *//*w w w  .  j a va2s.  c  o m*/
protected void unregisterMBeans() {
    try {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor.java

/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
    try {//from   ww w .j a  va  2s .c  o  m
        JettyJMXRemover jettyJMXRemover = null;
        // If you enable jmx support in jetty 8 or 9  some mbeans (e.g. for the servletholder or sessionmanager) are instanciated in the web application thread 
        // and a reference to the WebappClassloader is stored in a private ObjectMBean._loader which is unfortunatly not the classloader that loaded the class.
        // So for unregisterMBeans to work even for the jetty mbeans we need to access the MBeanContainer class of the jetty container.  
        try {
            jettyJMXRemover = new JettyJMXRemover(getWebApplicationClassLoader());
        } catch (Exception ex) {
            error(ex);
        }

        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                if (jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName)) {
                    continue;
                }
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:org.apache.flink.streaming.connectors.kafka.KafkaConsumerTestBase.java

/**
 * Test metrics reporting for consumer/*from w ww.jav  a 2  s . co m*/
 *
 * @throws Exception
 */
public void runMetricsTest() throws Throwable {

    // create a stream with 5 topics
    final String topic = "metricsStream";
    createTestTopic(topic, 5, 1);

    final Tuple1<Throwable> error = new Tuple1<>(null);
    Runnable job = new Runnable() {
        @Override
        public void run() {
            try {
                // start job writing & reading data.
                final StreamExecutionEnvironment env1 = StreamExecutionEnvironment
                        .createRemoteEnvironment("localhost", flinkPort);
                env1.setParallelism(1);
                env1.getConfig().setRestartStrategy(RestartStrategies.noRestart());
                env1.getConfig().disableSysoutLogging();
                env1.disableOperatorChaining(); // let the source read everything into the network buffers

                Properties props = new Properties();
                props.putAll(standardProps);
                props.putAll(secureProps);

                TypeInformationSerializationSchema<Tuple2<Integer, Integer>> schema = new TypeInformationSerializationSchema<>(
                        TypeInfoParser.<Tuple2<Integer, Integer>>parse("Tuple2<Integer, Integer>"),
                        env1.getConfig());
                DataStream<Tuple2<Integer, Integer>> fromKafka = env1
                        .addSource(kafkaServer.getConsumer(topic, schema, standardProps));
                fromKafka.flatMap(new FlatMapFunction<Tuple2<Integer, Integer>, Void>() {
                    @Override
                    public void flatMap(Tuple2<Integer, Integer> value, Collector<Void> out) throws Exception {// no op
                    }
                });

                DataStream<Tuple2<Integer, Integer>> fromGen = env1
                        .addSource(new RichSourceFunction<Tuple2<Integer, Integer>>() {
                            boolean running = true;

                            @Override
                            public void run(SourceContext<Tuple2<Integer, Integer>> ctx) throws Exception {
                                int i = 0;
                                while (running) {
                                    ctx.collect(Tuple2.of(i++, getRuntimeContext().getIndexOfThisSubtask()));
                                    Thread.sleep(1);
                                }
                            }

                            @Override
                            public void cancel() {
                                running = false;
                            }
                        });

                kafkaServer.produceIntoKafka(fromGen, topic, new KeyedSerializationSchemaWrapper<>(schema),
                        standardProps, null);

                env1.execute("Metrics test job");
            } catch (Throwable t) {
                LOG.warn("Got exception during execution", t);
                if (!(t.getCause() instanceof JobCancellationException)) { // we'll cancel the job
                    error.f0 = t;
                }
            }
        }
    };
    Thread jobThread = new Thread(job);
    jobThread.start();

    try {
        // connect to JMX
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        // wait until we've found all 5 offset metrics
        Set<ObjectName> offsetMetrics = mBeanServer.queryNames(new ObjectName("*current-offsets*:*"), null);
        while (offsetMetrics.size() < 5) { // test will time out if metrics are not properly working
            if (error.f0 != null) {
                // fail test early
                throw error.f0;
            }
            offsetMetrics = mBeanServer.queryNames(new ObjectName("*current-offsets*:*"), null);
            Thread.sleep(50);
        }
        Assert.assertEquals(5, offsetMetrics.size());
        // we can't rely on the consumer to have touched all the partitions already
        // that's why we'll wait until all five partitions have a positive offset.
        // The test will fail if we never meet the condition
        while (true) {
            int numPosOffsets = 0;
            // check that offsets are correctly reported
            for (ObjectName object : offsetMetrics) {
                Object offset = mBeanServer.getAttribute(object, "Value");
                if ((long) offset >= 0) {
                    numPosOffsets++;
                }
            }
            if (numPosOffsets == 5) {
                break;
            }
            // wait for the consumer to consume on all partitions
            Thread.sleep(50);
        }

        // check if producer metrics are also available.
        Set<ObjectName> producerMetrics = mBeanServer.queryNames(new ObjectName("*KafkaProducer*:*"), null);
        Assert.assertTrue("No producer metrics found", producerMetrics.size() > 30);

        LOG.info("Found all JMX metrics. Cancelling job.");
    } finally {
        // cancel
        JobManagerCommunicationUtils.cancelCurrentJob(flink.getLeaderGateway(timeout));
    }

    while (jobThread.isAlive()) {
        Thread.sleep(50);
    }
    if (error.f0 != null) {
        throw error.f0;
    }

    deleteTestTopic(topic);
}

From source file:org.alfresco.solr.SolrInformationServer.java

private String getHttpPort(String defaultPort) {
    try {/*from w w  w  .  j ava  2 s  .  c o  m*/
        MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
        QueryExp query = Query.and(Query.eq(Query.attr("scheme"), Query.value("http")),
                Query.eq(Query.attr("protocol"), Query.value("HTTP/1.1")));
        Set<ObjectName> objectNames = mBeanServer.queryNames(null, query);

        if (objectNames != null && objectNames.size() > 0) {
            for (ObjectName objectName : objectNames) {
                String name = objectName.toString();
                if (name.indexOf("port=") > -1) {
                    String[] parts = name.split("port=");
                    String port = parts[1];
                    try {
                        Integer.parseInt(port);
                        return port;
                    } catch (NumberFormatException e) {
                        log.error("Error parsing http port:" + port);
                        return defaultPort;
                    }
                }
            }
        }
    } catch (Throwable t) {
        log.error("Error getting https port:", t);
    }

    return defaultPort;
}