Example usage for javax.management MBeanServer getAttribute

List of usage examples for javax.management MBeanServer getAttribute

Introduction

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

Prototype

public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;

Source Link

Usage

From source file:org.apache.marmotta.platform.core.services.config.ConfigurationServiceImpl.java

/**
 * Try figuring out on which port the server is running ...
 *//*from   w  ww .  j  ava 2 s.c o  m*/
@Override
public int getServerPort() {

    if (serverPort == 0) {

        if (isTomcat6()) {
            // tomcat <= 6.x
            try {
                Object server = Class.forName("org.apache.catalina.ServerFactory").getMethod("getServer")
                        .invoke(null);
                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat <= 6.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else if (isTomcat7()) {
            // tomcat 7.x
            try {
                MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
                ObjectName name = new ObjectName("Catalina", "type", "Server");
                Object server = mBeanServer.getAttribute(name, "managedResource");

                Object service = Array.get(server.getClass().getMethod("findServices").invoke(server), 0);
                Object connector = Array.get(service.getClass().getMethod("findConnectors").invoke(service), 0);

                int port = (Integer) connector.getClass().getMethod("getPort").invoke(connector);
                log.info("Tomcat 7.x detected, server port: {}", port);
                serverPort = port;
            } catch (Exception e) {
            }
        } else {

            log.warn("not running on Tomcat, could not determine server port, returning default of 8080");
            serverPort = 8080;
        }
    }

    return serverPort;

}

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

public Cluster getCluster(String serverName, String hostName, boolean loadMembers) throws Exception {
    Cluster cluster = null;//from   w  ww .j a  v  a 2  s .  c  o  m

    MBeanServer mBeanServer = new Registry().getMBeanServer();
    ObjectName membershipOName = new ObjectName(serverName + ":type=ClusterMembership,host=" + hostName);
    ObjectName receiverOName = new ObjectName(serverName + ":type=ClusterReceiver,host=" + hostName);
    ObjectName senderOName = new ObjectName(serverName + ":type=ClusterSender,host=" + hostName);

    //
    // should be just one set, this is just to find out if this instance
    // is cluster-enabled and the cluster supports JMX
    //
    Set clusters = mBeanServer.queryMBeans(new ObjectName("*:type=Cluster,host=" + hostName), null);
    Set membership = mBeanServer.queryMBeans(membershipOName, null);
    if (clusters != null && clusters.size() > 0 && membership != null && membership.size() > 0) {
        ObjectName clusterOName = ((ObjectInstance) clusters.iterator().next()).getObjectName();
        cluster = new Cluster();

        cluster.setName(JmxTools.getStringAttr(mBeanServer, clusterOName, "clusterName"));
        cluster.setInfo(JmxTools.getStringAttr(mBeanServer, clusterOName, "info"));
        cluster.setManagerClassName(JmxTools.getStringAttr(mBeanServer, clusterOName, "managerClassName"));

        cluster.setMcastAddress(JmxTools.getStringAttr(mBeanServer, membershipOName, "mcastAddr"));
        cluster.setMcastBindAddress(JmxTools.getStringAttr(mBeanServer, membershipOName, "mcastBindAddress"));
        cluster.setMcastClusterDomain(
                JmxTools.getStringAttr(mBeanServer, membershipOName, "mcastClusterDomain"));
        cluster.setMcastDropTime(JmxTools.getLongAttr(mBeanServer, membershipOName, "mcastDropTime"));
        cluster.setMcastFrequency(JmxTools.getLongAttr(mBeanServer, membershipOName, "mcastFrequency"));
        cluster.setMcastPort(JmxTools.getIntAttr(mBeanServer, membershipOName, "mcastPort"));
        cluster.setMcastSoTimeout(JmxTools.getIntAttr(mBeanServer, membershipOName, "mcastSoTimeout"));
        cluster.setMcastTTL(JmxTools.getIntAttr(mBeanServer, membershipOName, "mcastTTL"));

        cluster.setTcpListenAddress(JmxTools.getStringAttr(mBeanServer, receiverOName, "tcpListenAddress"));
        cluster.setTcpListenPort(JmxTools.getIntAttr(mBeanServer, receiverOName, "tcpListenPort"));
        cluster.setNrOfMsgsReceived(JmxTools.getLongAttr(mBeanServer, receiverOName, "nrOfMsgsReceived"));
        cluster.setTotalReceivedBytes(JmxTools.getLongAttr(mBeanServer, receiverOName, "totalReceivedBytes"));
        //            cluster.setTcpSelectorTimeout(getLongAttr(mBeanServer, receiverOName, "tcpSelectorTimeout"));
        //            cluster.setTcpThreadCount(getIntAttr(mBeanServer, receiverOName, "tcpThreadCount"));

        cluster.setSenderAckTimeout(JmxTools.getLongAttr(mBeanServer, senderOName, "ackTimeout"));
        cluster.setSenderAutoConnect(
                ((Boolean) mBeanServer.getAttribute(senderOName, "autoConnect")).booleanValue());
        cluster.setSenderFailureCounter(JmxTools.getLongAttr(mBeanServer, senderOName, "failureCounter"));
        cluster.setSenderNrOfRequests(JmxTools.getLongAttr(mBeanServer, senderOName, "nrOfRequests"));
        cluster.setSenderReplicationMode(JmxTools.getStringAttr(mBeanServer, senderOName, "replicationMode"));
        cluster.setSenderTotalBytes(JmxTools.getLongAttr(mBeanServer, senderOName, "totalBytes"));

        if (loadMembers) {
            ObjectName senders[] = (ObjectName[]) mBeanServer.getAttribute(senderOName, "senderObjectNames");
            for (int i = 0; i < senders.length; i++) {

                ClusterSender sender;

                if ("pooled".equals(cluster.getSenderReplicationMode())) {
                    sender = new PooledClusterSender();
                } else if ("synchronous".equals(cluster.getSenderReplicationMode())) {
                    sender = new SyncClusterSender();
                } else if ("asynchronous".equals(cluster.getSenderReplicationMode())
                        || "fastasyncqueue".equals(cluster.getSenderReplicationMode())) {
                    sender = new AsyncClusterSender();
                } else {
                    sender = new ClusterSender();
                }
                ObjectName localSenderOName = senders[i];

                sender.setAddress(JmxTools.getStringAttr(mBeanServer, localSenderOName, "address"));
                sender.setPort(JmxTools.getIntAttr(mBeanServer, localSenderOName, "port"));

                sender.setAvgMessageSize(
                        JmxTools.getLongAttr(mBeanServer, localSenderOName, "avgMessageSize", -1));
                sender.setAvgProcessingTime(
                        JmxTools.getLongAttr(mBeanServer, localSenderOName, "avgProcessingTime", -1));

                sender.setConnectCounter(JmxTools.getLongAttr(mBeanServer, localSenderOName, "connectCounter"));
                sender.setDisconnectCounter(
                        JmxTools.getLongAttr(mBeanServer, localSenderOName, "disconnectCounter"));
                sender.setConnected(
                        ((Boolean) mBeanServer.getAttribute(localSenderOName, "connected")).booleanValue());
                sender.setKeepAliveTimeout(
                        JmxTools.getLongAttr(mBeanServer, localSenderOName, "keepAliveTimeout"));
                sender.setNrOfRequests(JmxTools.getLongAttr(mBeanServer, localSenderOName, "nrOfRequests"));
                sender.setTotalBytes(JmxTools.getLongAttr(mBeanServer, localSenderOName, "totalBytes"));
                sender.setResend(
                        ((Boolean) mBeanServer.getAttribute(localSenderOName, "resend")).booleanValue());
                sender.setSuspect(
                        ((Boolean) mBeanServer.getAttribute(localSenderOName, "suspect")).booleanValue());

                if (sender instanceof PooledClusterSender) {
                    ((PooledClusterSender) sender).setMaxPoolSocketLimit(
                            JmxTools.getIntAttr(mBeanServer, localSenderOName, "maxPoolSocketLimit"));
                }

                if (sender instanceof SyncClusterSender) {
                    SyncClusterSender syncSender = (SyncClusterSender) sender;
                    syncSender.setDataFailureCounter(
                            JmxTools.getLongAttr(mBeanServer, localSenderOName, "dataFailureCounter"));
                    syncSender.setDataResendCounter(
                            JmxTools.getLongAttr(mBeanServer, localSenderOName, "dataResendCounter"));
                    syncSender.setSocketOpenCounter(
                            JmxTools.getIntAttr(mBeanServer, localSenderOName, "socketOpenCounter"));
                    syncSender.setSocketCloseCounter(
                            JmxTools.getIntAttr(mBeanServer, localSenderOName, "socketCloseCounter"));
                    syncSender.setSocketOpenFailureCounter(
                            JmxTools.getIntAttr(mBeanServer, localSenderOName, "socketOpenFailureCounter"));
                }

                if (sender instanceof AsyncClusterSender) {
                    AsyncClusterSender asyncSender = (AsyncClusterSender) sender;
                    asyncSender.setInQueueCounter(
                            JmxTools.getLongAttr(mBeanServer, localSenderOName, "inQueueCounter"));
                    asyncSender.setOutQueueCounter(
                            JmxTools.getLongAttr(mBeanServer, localSenderOName, "outQueueCounter"));
                    asyncSender.setQueueSize(JmxTools.getIntAttr(mBeanServer, localSenderOName, "queueSize"));
                    asyncSender.setQueuedNrOfBytes(
                            JmxTools.getLongAttr(mBeanServer, localSenderOName, "queuedNrOfBytes"));
                }
                cluster.getMembers().add(sender);
            }
        }
    }
    return cluster;
}

From source file:psiprobe.beans.ClusterWrapperBean.java

/**
 * Gets the cluster./*from  w w w.  j a  va 2 s. c  o m*/
 *
 * @param serverName the server name
 * @param hostName the host name
 * @param loadMembers the load members
 * @return the cluster
 * @throws Exception the exception
 */
public Cluster getCluster(String serverName, String hostName, boolean loadMembers) throws Exception {

    Cluster cluster = null;

    MBeanServer mbeanServer = new Registry().getMBeanServer();
    ObjectName membershipOName = new ObjectName(serverName + ":type=ClusterMembership,host=" + hostName);
    ObjectName receiverOName = new ObjectName(serverName + ":type=ClusterReceiver,host=" + hostName);
    ObjectName senderOName = new ObjectName(serverName + ":type=ClusterSender,host=" + hostName);

    /*
     * should be just one set, this is just to find out if this instance is cluster-enabled and the
     * cluster supports JMX
     */
    Set<ObjectInstance> clusters = mbeanServer.queryMBeans(new ObjectName("*:type=Cluster,host=" + hostName),
            null);
    Set<ObjectInstance> membership = mbeanServer.queryMBeans(membershipOName, null);
    if (clusters != null && !clusters.isEmpty() && membership != null && membership.size() > 0) {
        ObjectName clusterOName = clusters.iterator().next().getObjectName();
        cluster = new Cluster();

        cluster.setName(JmxTools.getStringAttr(mbeanServer, clusterOName, "clusterName"));
        cluster.setInfo(JmxTools.getStringAttr(mbeanServer, clusterOName, "info"));
        cluster.setManagerClassName(JmxTools.getStringAttr(mbeanServer, clusterOName, "managerClassName"));

        cluster.setMcastAddress(JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastAddr"));
        cluster.setMcastBindAddress(JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastBindAddress"));
        cluster.setMcastClusterDomain(
                JmxTools.getStringAttr(mbeanServer, membershipOName, "mcastClusterDomain"));
        cluster.setMcastDropTime(JmxTools.getLongAttr(mbeanServer, membershipOName, "mcastDropTime"));
        cluster.setMcastFrequency(JmxTools.getLongAttr(mbeanServer, membershipOName, "mcastFrequency"));
        cluster.setMcastPort(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastPort"));
        cluster.setMcastSoTimeout(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastSoTimeout"));
        cluster.setMcastTtl(JmxTools.getIntAttr(mbeanServer, membershipOName, "mcastTTL"));

        cluster.setTcpListenAddress(JmxTools.getStringAttr(mbeanServer, receiverOName, "tcpListenAddress"));
        cluster.setTcpListenPort(JmxTools.getIntAttr(mbeanServer, receiverOName, "tcpListenPort"));
        cluster.setNrOfMsgsReceived(JmxTools.getLongAttr(mbeanServer, receiverOName, "nrOfMsgsReceived"));
        cluster.setTotalReceivedBytes(JmxTools.getLongAttr(mbeanServer, receiverOName, "totalReceivedBytes"));
        // cluster.setTcpSelectorTimeout(
        // JmxTools.getLongAttr(mBeanServer, receiverOName, "tcpSelectorTimeout"));
        // cluster.setTcpThreadCount(
        // JmxTools.getIntAttr(mBeanServer, receiverOName, "tcpThreadCount"));

        cluster.setSenderAckTimeout(JmxTools.getLongAttr(mbeanServer, senderOName, "ackTimeout"));
        cluster.setSenderAutoConnect((Boolean) mbeanServer.getAttribute(senderOName, "autoConnect"));
        cluster.setSenderFailureCounter(JmxTools.getLongAttr(mbeanServer, senderOName, "failureCounter"));
        cluster.setSenderNrOfRequests(JmxTools.getLongAttr(mbeanServer, senderOName, "nrOfRequests"));
        cluster.setSenderReplicationMode(JmxTools.getStringAttr(mbeanServer, senderOName, "replicationMode"));
        cluster.setSenderTotalBytes(JmxTools.getLongAttr(mbeanServer, senderOName, "totalBytes"));

        if (loadMembers) {
            ObjectName[] senders = (ObjectName[]) mbeanServer.getAttribute(senderOName, "senderObjectNames");
            for (ObjectName localSenderOName : senders) {
                ClusterSender sender;

                if ("pooled".equals(cluster.getSenderReplicationMode())) {
                    sender = new PooledClusterSender();
                } else if ("synchronous".equals(cluster.getSenderReplicationMode())) {
                    sender = new SyncClusterSender();
                } else if ("asynchronous".equals(cluster.getSenderReplicationMode())
                        || "fastasyncqueue".equals(cluster.getSenderReplicationMode())) {
                    sender = new AsyncClusterSender();
                } else {
                    sender = new ClusterSender();
                }

                sender.setAddress(JmxTools.getStringAttr(mbeanServer, localSenderOName, "address"));
                sender.setPort(JmxTools.getIntAttr(mbeanServer, localSenderOName, "port"));

                sender.setAvgMessageSize(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "avgMessageSize", -1));
                sender.setAvgProcessingTime(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "avgProcessingTime", -1));

                sender.setConnectCounter(JmxTools.getLongAttr(mbeanServer, localSenderOName, "connectCounter"));
                sender.setDisconnectCounter(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "disconnectCounter"));
                sender.setConnected((Boolean) mbeanServer.getAttribute(localSenderOName, "connected"));
                sender.setKeepAliveTimeout(
                        JmxTools.getLongAttr(mbeanServer, localSenderOName, "keepAliveTimeout"));
                sender.setNrOfRequests(JmxTools.getLongAttr(mbeanServer, localSenderOName, "nrOfRequests"));
                sender.setTotalBytes(JmxTools.getLongAttr(mbeanServer, localSenderOName, "totalBytes"));
                sender.setResend((Boolean) mbeanServer.getAttribute(localSenderOName, "resend"));
                sender.setSuspect((Boolean) mbeanServer.getAttribute(localSenderOName, "suspect"));

                if (sender instanceof PooledClusterSender) {
                    ((PooledClusterSender) sender).setMaxPoolSocketLimit(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "maxPoolSocketLimit"));
                }

                if (sender instanceof SyncClusterSender) {
                    SyncClusterSender syncSender = (SyncClusterSender) sender;
                    syncSender.setDataFailureCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "dataFailureCounter"));
                    syncSender.setDataResendCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "dataResendCounter"));
                    syncSender.setSocketOpenCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketOpenCounter"));
                    syncSender.setSocketCloseCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketCloseCounter"));
                    syncSender.setSocketOpenFailureCounter(
                            JmxTools.getIntAttr(mbeanServer, localSenderOName, "socketOpenFailureCounter"));
                }

                if (sender instanceof AsyncClusterSender) {
                    AsyncClusterSender asyncSender = (AsyncClusterSender) sender;
                    asyncSender.setInQueueCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "inQueueCounter"));
                    asyncSender.setOutQueueCounter(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "outQueueCounter"));
                    asyncSender.setQueueSize(JmxTools.getIntAttr(mbeanServer, localSenderOName, "queueSize"));
                    asyncSender.setQueuedNrOfBytes(
                            JmxTools.getLongAttr(mbeanServer, localSenderOName, "queuedNrOfBytes"));
                }
                cluster.getMembers().add(sender);
            }
        }
    }
    return cluster;
}

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

/**
 * Test metrics reporting for consumer/*w  ww  . ja va 2  s .  c  om*/
 *
 * @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);
}