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.springframework.ldap.config.LdapTemplateNamespaceHandlerTest.java

@Test
public void verifyParsePool2SizeSet() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/ldap-namespace-config-pool2-configured-poolsize.xml");

    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    assertThat(outerContextSource).isNotNull();

    ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
    assertThat(pooledContextSource).isNotNull();

    org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(
            pooledContextSource, "keyedObjectPool");
    assertThat(objectPool.getMaxTotal()).isEqualTo(12);
    assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(20);
    assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(10);
    assertThat(objectPool.getMaxWaitMillis()).isEqualTo(13);
    assertThat(objectPool.getMinIdlePerKey()).isEqualTo(14);
    assertThat(objectPool.getBlockWhenExhausted()).isEqualTo(true);
    assertThat(objectPool.getEvictionPolicyClassName())
            .isEqualTo("org.springframework.ldap.pool2.DummyEvictionPolicy");
    assertThat(objectPool.getFairness()).isEqualTo(true);
    assertThat(objectPool.getLifo()).isEqualTo(false);

    // ensures the pool is registered
    ObjectName oname = objectPool.getJmxName();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> result = mbs.queryNames(oname, null);
    assertThat(result).hasSize(1);/*from ww  w . ja v a 2  s. c o  m*/
    assertThat(oname.toString()).isEqualTo("org.springframework.ldap.pool2:type=ldap-pool,name=test-pool");
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Get a list of strings(scheme + host + port) that the specified connector is running on
 *
 * @param name/*from   w w w . j  a  v  a2  s .co  m*/
 * @return
 */
private ArrayList<String> getConnectorStrings(String name) {
    ArrayList<String> connectorStrings = new ArrayList<String>();

    try {
        MBeanServer mbeanServer = getServerForName(name);
        Set<ObjectName> objs = mbeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);

        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
            ObjectName obj = i.next();
            String scheme = mbeanServer.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            connectorStrings.add(scheme + "://localhost:" + port);
            logger.info("Adding: {}", scheme + "://localhost:" + port);
        }
    } catch (Exception e) {
    }

    return connectorStrings;
}

From source file:org.wso2.carbon.core.ServerManagement.java

/**
 * Wait till all service requests have been serviced. This method will only wait for a maximum
 * of {@link ServerManagement#TIMEOUT}//from w  w w.ja va2s .  c  o  m
 *
 * @throws Exception If an error occurs while trying to connect to the Tomcat MBean
 */
public void waitForRequestCompletion() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Waiting for request service completion...");
    /**
     * Get all MBeans with names such as Catalina:type=RequestProcessor,worker=http-9762,name=HttpRequest<n>
     * & Catalina:type=RequestProcessor,worker=http-9762,name=HttpsRequest<n>
     */
    MBeanServer mbs = ManagementFactory.getMBeanServer();
    boolean areRequestsInService;
    long start = System.currentTimeMillis();
    do {
        // Check whether there are any processors which are currently in the SERVICE stage (3)
        QueryExp query = Query.eq(Query.attr("stage"), Query.value(3)); // 3 = org.apache.coyote.Constants.STAGE_SERVICE
        Set set = mbs.queryNames(new ObjectName("Catalina:type=RequestProcessor,*"), query);
        if (set.size() > 0) {
            areRequestsInService = true;
            if (System.currentTimeMillis() - start > TIMEOUT) {
                log.warn("Timeout occurred even though there are active connections.");
                break;
            }
            Thread.sleep(2000);
        } else {
            areRequestsInService = false;
        }
    } while (areRequestsInService);
    log.info("All requests have been served.");
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Returns an MBeanServer with the specified name
 *
 * @param name/* w  w w  . jav a2  s . com*/
 * @return
 */
private MBeanServer getServerForName(String name) {
    try {
        MBeanServer mbeanServer = null;
        final ObjectName objectNameQuery = new ObjectName(name + ":type=Service,*");

        for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
            if (server.queryNames(objectNameQuery, null).size() > 0) {
                mbeanServer = server;
                // we found it, bail out
                break;
            }
        }

        return mbeanServer;
    } catch (Exception e) {
    }

    return null;
}

From source file:org.springframework.ldap.config.LdapTemplateNamespaceHandlerTest.java

@Test
public void verifyParsePooling2Defaults() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
            "/ldap-namespace-config-pooling2-defaults.xml");

    ContextSource outerContextSource = ctx.getBean(ContextSource.class);
    assertThat(outerContextSource).isNotNull();
    assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue();

    ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget();
    assertThat(pooledContextSource).isNotNull();
    assertThat(pooledContextSource instanceof PooledContextSource).isTrue();
    assertThat(getInternalState(pooledContextSource, "poolConfig")).isNotNull();

    Object objectFactory = getInternalState(pooledContextSource, "dirContextPooledObjectFactory");
    assertThat(getInternalState(objectFactory, "contextSource")).isNotNull();
    assertThat(getInternalState(objectFactory, "dirContextValidator")).isNull();
    Set<Class<? extends Throwable>> nonTransientExceptions = (Set<Class<? extends Throwable>>) getInternalState(
            objectFactory, "nonTransientExceptions");
    assertThat(nonTransientExceptions).hasSize(1);
    assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue();

    org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(
            pooledContextSource, "keyedObjectPool");
    assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(8);
    assertThat(objectPool.getMaxTotal()).isEqualTo(-1);
    assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(8);
    assertThat(objectPool.getMinIdlePerKey()).isEqualTo(0);
    assertThat(objectPool.getBlockWhenExhausted()).isEqualTo(true);
    assertThat(objectPool.getEvictionPolicyClassName())
            .isEqualTo(GenericKeyedObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME);
    assertThat(objectPool.getFairness()).isEqualTo(false);

    // ensures the pool is registered
    ObjectName oname = objectPool.getJmxName();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> result = mbs.queryNames(oname, null);
    assertThat(result).hasSize(1);//  w w w.  jav a2  s.  c o  m

    assertThat(objectPool.getLifo()).isEqualTo(true);
    assertThat(objectPool.getMaxWaitMillis()).isEqualTo(-1L);
    assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(1000L * 60L * 30L);
    assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(3);
    assertThat(objectPool.getSoftMinEvictableIdleTimeMillis()).isEqualTo(-1L);
    assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(-1L);
    assertThat(objectPool.getTestOnBorrow()).isEqualTo(false);
    assertThat(objectPool.getTestOnCreate()).isEqualTo(false);
    assertThat(objectPool.getTestOnReturn()).isEqualTo(false);
    assertThat(objectPool.getTestWhileIdle()).isEqualTo(false);
}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void writeJmx(BundleWriter writer) throws IOException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    try (JsonGenerator generator = writer.createGenerator("runtime/jmx.json")) {
        generator.useDefaultPrettyPrinter();
        generator.writeStartObject();//from  www.  jav  a  2 s. com
        generator.writeArrayFieldStart("beans");

        for (ObjectName objectName : mBeanServer.queryNames(null, null)) {
            MBeanInfo info;
            try {
                info = mBeanServer.getMBeanInfo(objectName);
            } catch (InstanceNotFoundException | IntrospectionException | ReflectionException ex) {
                LOG.warn("Exception accessing MBeanInfo ", ex);
                continue;
            }

            generator.writeStartObject();
            generator.writeStringField("name", objectName.toString());
            generator.writeObjectFieldStart("attributes");

            for (MBeanAttributeInfo attr : info.getAttributes()) {
                try {
                    writeAttribute(generator, attr.getName(),
                            mBeanServer.getAttribute(objectName, attr.getName()));
                } catch (MBeanException | AttributeNotFoundException | InstanceNotFoundException
                        | ReflectionException | RuntimeMBeanException ex) {
                    generator.writeStringField(attr.getName(), "Exception: " + ex.toString());
                }
            }

            generator.writeEndObject();
            generator.writeEndObject();
            writer.writeLn("");
        }

        generator.writeEndArray();
        generator.writeEndObject();
    } finally {
        writer.markEndOfFile();
    }
}

From source file:org.apache.axis2.transport.base.AbstractTransportListener.java

/**
 * Utility method to allow transports to register MBeans
 * @param mbeanInstance bean instance//from   w ww .  j ava  2 s  .  c  o m
 * @param objectName name
 */
private void registerMBean(Object mbeanInstance, String objectName) {
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName(objectName);
        Set set = mbs.queryNames(name, null);
        if (set != null && set.isEmpty()) {
            mbs.registerMBean(mbeanInstance, name);
        } else {
            mbs.unregisterMBean(name);
            mbs.registerMBean(mbeanInstance, name);
        }
    } catch (Exception e) {
        log.warn("Error registering a MBean with objectname ' " + objectName + " ' for JMX management", e);
    }
}

From source file:org.apache.geode.management.internal.cli.commands.DestroyRegionCommand.java

private Set<DistributedMember> findMembersForRegion(InternalCache cache, ManagementService managementService,
        String regionPath) {//www  .ja v a2  s. c  om
    Set<DistributedMember> membersList = new HashSet<>();
    Set<String> regionMemberIds = new HashSet<>();
    MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;

    // needs to be escaped with quotes if it contains a hyphen
    if (regionPath.contains("-")) {
        regionPath = "\"" + regionPath + "\"";
    }

    String queryExp = MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*");

    try {
        ObjectName queryExpON = new ObjectName(queryExp);
        Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON);
        if (queryNames == null || queryNames.isEmpty()) {
            return membersList; // protects against null pointer exception below
        }

        boolean addedOneRemote = false;
        for (ObjectName regionMBeanObjectName : queryNames) {
            try {
                RegionMXBean regionMXBean = managementService.getMBeanInstance(regionMBeanObjectName,
                        RegionMXBean.class);
                if (regionMXBean != null) {
                    RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes();
                    String scope = regionAttributes.getScope();
                    // For Scope.LOCAL regions we need to identify each hosting member, but for
                    // other scopes we just need a single member as the region destroy will be
                    // propagated.
                    if (Scope.LOCAL.equals(Scope.fromString(scope))) {
                        regionMemberIds.add(regionMXBean.getMember());
                    } else {
                        if (!addedOneRemote) {
                            regionMemberIds.add(regionMXBean.getMember());
                            addedOneRemote = true;
                        }
                    }
                }
            } catch (ClassCastException e) {
                LogWriter logger = cache.getLogger();
                if (logger.finerEnabled()) {
                    logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(), e);
                }
            }
        }

        if (!regionMemberIds.isEmpty()) {
            membersList = getMembersByIds(cache, regionMemberIds);
        }
    } catch (MalformedObjectNameException | NullPointerException e) {
        LogWrapper.getInstance().info(e.getMessage(), e);
    }

    return membersList;
}

From source file:org.hyperic.hq.plugin.weblogic.jmx.WeblogicDiscover.java

public void find(MBeanServer mServer, WeblogicQuery query, List types) throws WeblogicDiscoverException {
    ObjectName scope;/*ww w .j a  v  a 2s.c om*/

    try {
        scope = new ObjectName(domain + ":" + query.getScope() + ",*");
        log.debug("[find] scope=" + scope);
    } catch (MalformedObjectNameException e) {
        // wont happen
        throw new IllegalArgumentException(e.getMessage());
    }

    try {
        for (Iterator it = mServer.queryNames(scope, null).iterator(); it.hasNext();) {
            ObjectName obj = (ObjectName) it.next();
            String name = obj.getKeyProperty("Name");
            if (name != null) {
                if (name.startsWith("__") || (name.indexOf("uuid-") != -1)) // wierdo 9.1 stuff i.e __weblogic_admin_rmi_queue
                {
                    continue;
                }
            }
            WeblogicQuery type = query.cloneInstance();
            if (type.getAttributes(mServer, obj)) {
                types.add(type);
                WeblogicQuery[] childQueries = query.getChildQueries();

                for (int i = 0; i < childQueries.length; i++) {
                    WeblogicQuery childQuery = childQueries[i];
                    childQuery.setParent(type);
                    childQuery.setVersion(type.getVersion());
                    find(mServer, childQuery, types);
                }
            }
        }
    } catch (Exception e) {
        throw new WeblogicDiscoverException(e);
    }
}

From source file:net.centro.rtb.monitoringcenter.metrics.tomcat.TomcatConnectorMetricSet.java

TomcatConnectorMetricSet(ObjectName threadPoolObjectName) {
    Preconditions.checkNotNull(threadPoolObjectName);

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

    this.name = threadPoolObjectName.getKeyProperty("name");
    this.port = JmxUtil.getJmxAttribute(threadPoolObjectName, "port", Integer.class, null);

    Set<ObjectName> connectorObjectNames = null;
    try {//w  ww .  j a  v  a 2s. c o  m
        connectorObjectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,port=" + port),
                null);
    } catch (MalformedObjectNameException e) {
        logger.debug("Invalid ObjectName defined for the Tomcat's Connector MxBean for the {} thread pool",
                name, e);
    }

    if (connectorObjectNames != null && !connectorObjectNames.isEmpty()) {
        ObjectName connectorObjectName = connectorObjectNames.iterator().next();
        String internalPortStr = JmxUtil.getJmxAttribute(connectorObjectName, "internalPort", String.class,
                Boolean.FALSE.toString());
        this.isInternalPort = Boolean.TRUE.toString().equalsIgnoreCase(internalPortStr);
    }

    this.isSecure = JmxUtil.getJmxAttribute(threadPoolObjectName, "sSLEnabled", Boolean.class, Boolean.FALSE);
    this.isAjp = isAjpFromName(name);

    Map<String, Metric> metricsByNames = new HashMap<>();

    this.currentPoolSizeGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "currentThreadCount",
            Integer.class, 0);
    if (currentPoolSizeGauge != null) {
        metricsByNames.put("currentPoolSize", currentPoolSizeGauge);
    }

    this.maxPoolSizeGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "maxThreads", Integer.class,
            0);
    if (maxPoolSizeGauge != null) {
        metricsByNames.put("maxPoolSize", maxPoolSizeGauge);
    }

    this.busyThreadsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "currentThreadsBusy",
            Integer.class, 0);
    if (busyThreadsGauge != null) {
        metricsByNames.put("busyThreads", busyThreadsGauge);
    }

    this.activeConnectionsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "connectionCount",
            Long.class, 0L);
    if (activeConnectionsGauge != null) {
        metricsByNames.put("activeConnections", activeConnectionsGauge);
    }

    this.maxConnectionsGauge = JmxUtil.getJmxAttributeAsGauge(threadPoolObjectName, "maxConnections",
            Integer.class, 0);
    if (maxConnectionsGauge != null) {
        metricsByNames.put("maxConnections", maxConnectionsGauge);
    }

    Set<ObjectName> globalRequestProcessorObjectNames = null;
    try {
        globalRequestProcessorObjectNames = mBeanServer
                .queryNames(new ObjectName("Catalina:type=GlobalRequestProcessor,name=" + name), null);
    } catch (MalformedObjectNameException e) {
        logger.debug(
                "Invalid ObjectName defined for the Tomcat's GlobalRequestProcessor MxBean for the {} thread pool",
                name, e);
    }

    if (globalRequestProcessorObjectNames != null && !globalRequestProcessorObjectNames.isEmpty()) {
        ObjectName globalRequestProcessorObjectName = globalRequestProcessorObjectNames.iterator().next();
        this.totalRequestsGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName,
                "requestCount", Integer.class, 0);

        if (totalRequestsGauge != null) {
            metricsByNames.put("totalRequests", totalRequestsGauge);

            this.qpsHolder = new AtomicInteger();
            this.previousRequestCount = totalRequestsGauge.getValue();

            this.qpsGauge = new Gauge<Integer>() {
                @Override
                public Integer getValue() {
                    return qpsHolder.get();
                }
            };
            metricsByNames.put("qps", qpsGauge);
        }

        this.errorsGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName, "errorCount",
                Integer.class, 0);
        if (errorsGauge != null) {
            metricsByNames.put("errors", errorsGauge);
        }

        this.receivedBytesGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName,
                "bytesReceived", Long.class, 0L);
        if (receivedBytesGauge != null) {
            metricsByNames.put("receivedBytes", receivedBytesGauge);
        }

        this.sentBytesGauge = JmxUtil.getJmxAttributeAsGauge(globalRequestProcessorObjectName, "bytesSent",
                Long.class, 0L);
        if (sentBytesGauge != null) {
            metricsByNames.put("sentBytes", sentBytesGauge);
        }
    }

    this.metricsByNames = metricsByNames;
}