Example usage for java.lang.management ManagementFactory getPlatformMBeanServer

List of usage examples for java.lang.management ManagementFactory getPlatformMBeanServer

Introduction

In this page you can find the example usage for java.lang.management ManagementFactory getPlatformMBeanServer.

Prototype

public static synchronized MBeanServer getPlatformMBeanServer() 

Source Link

Document

Returns the platform javax.management.MBeanServer MBeanServer .

Usage

From source file:org.red5.server.undertow.UndertowLoader.java

protected void registerJMX() {
    // register with jmx
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*from   ww  w . j  a v  a  2 s . com*/
        ObjectName oName = new ObjectName("org.red5.server:type=UndertowLoader");
        // check for existing registration before registering
        if (!mbs.isRegistered(oName)) {
            mbs.registerMBean(this, oName);
        } else {
            log.debug("ContextLoader is already registered in JMX");
        }
    } catch (Exception e) {
        log.warn("Error on jmx registration", e);
    }
}

From source file:org.red5.server.scope.Scope.java

protected void registerJMX() {
    // register with jmx
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {/*from   w ww  .ja  va  2  s .c o m*/
        String cName = this.getClass().getName();
        if (cName.indexOf('.') != -1) {
            cName = cName.substring(cName.lastIndexOf('.')).replaceFirst("[\\.]", "");
        }
        oName = new ObjectName(String.format("org.red5.server:type=%s,name=%s", cName, name));
        // don't reregister
        if (!mbs.isRegistered(oName)) {
            mbs.registerMBean(new StandardMBean(this, ScopeMXBean.class, true), oName);
        }
    } catch (Exception e) {
        log.warn("Error on jmx registration", e);
    }
}

From source file:org.red5.server.undertow.UndertowLoader.java

protected void unregisterJMX() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {// www. j ava 2 s .  com
        ObjectName oName = new ObjectName("org.red5.server:type=UndertowLoader");
        mbs.unregisterMBean(oName);
    } catch (Exception e) {
        log.warn("Exception unregistering", e);
    }
}

From source file:org.wso2.carbon.dataservices.core.DBDeployer.java

/**
 * Registers an MBean representing the given data service.
 *//*from   w ww.  j  a  va 2 s .  c  o m*/
private void registerMBean(DataService dataService) {
    DataServiceInstanceMBean dsMBean = new DataServiceInstance(dataService);
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    if (server != null) {
        try {
            ObjectName objectName = new ObjectName(DBConstants.DATA_SERVICES_JMX_DOMAIN
                    + ":section=Services,service=" + dsMBean.getServiceName());
            try {
                server.unregisterMBean(objectName);
            } catch (Exception ignore) {
                /* ignore if it doesn't exist */
            }
            server.registerMBean(dsMBean, objectName);
        } catch (Exception e) {
            log.error("Error in Registering Data Services MBean", e);
        }
    }
}

From source file:azkaban.webapp.AzkabanWebServer.java

private void configureMBeanServer() {
    logger.info("Registering MBeans...");
    mbeanServer = ManagementFactory.getPlatformMBeanServer();

    registerMbean("jetty", new JmxJettyServer(server));
    registerMbean("triggerManager", new JmxTriggerManager(triggerManager));
    if (executorManager instanceof ExecutorManager) {
        registerMbean("executorManager", new JmxExecutorManager((ExecutorManager) executorManager));
    }//from ww  w.  j  a  va2 s.c  o m

    // Register Log4J loggers as JMX beans so the log level can be
    // updated via JConsole or Java VisualVM
    HierarchyDynamicMBean log4jMBean = new HierarchyDynamicMBean();
    registerMbean("log4jmxbean", log4jMBean);
    ObjectName accessLogLoggerObjName = log4jMBean.addLoggerMBean(AZKABAN_ACCESS_LOGGER_NAME);

    if (accessLogLoggerObjName == null) {
        System.out.println("************* loginLoggerObjName is null, make sure there is a logger with name "
                + AZKABAN_ACCESS_LOGGER_NAME);
    } else {
        System.out.println("******** loginLoggerObjName: " + accessLogLoggerObjName.getCanonicalName());
    }
}

From source file:org.marketcetera.strategy.StrategyTestBase.java

/**
 * Returns an <code>MXBean</code> interface to the given strategy.
 *
 * @param inModuleURN a <code>ModuleURN</code> value containing a strategy
 * @return a <code>StrategyMXBean</code> value
 * @throws Exception if an error occurs/*from  ww  w .  j  a va 2s  .c o m*/
 */
protected StrategyMXBean getMXProxy(ModuleURN inModuleURN) throws Exception {
    ObjectName objectName = inModuleURN.toObjectName();
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    return JMX.newMXBeanProxy(server, objectName, StrategyMXBean.class, true);
}

From source file:com.frameworkset.commons.dbcp2.BasicDataSource.java

/**
 * <p>Closes and releases all idle connections that are currently stored in the connection pool
 * associated with this data source.</p>
 *
 * <p>Connections that are checked out to clients when this method is invoked are not affected.
 * When client applications subsequently invoke {@link Connection#close()} to return
 * these connections to the pool, the underlying JDBC connections are closed.</p>
 *
 * <p>Attempts to acquire connections using {@link #getConnection()} after this method has been
 * invoked result in SQLExceptions.</p>
 *
 * <p>This method is idempotent - i.e., closing an already closed BasicDataSource has no effect
 * and does not generate exceptions.</p>
 *
 * @throws SQLException if an error occurs closing idle connections
 *///w  w w  . j  a  va 2s.  c om
public synchronized void close() throws SQLException {
    if (registeredJmxName != null) {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {
            mbs.unregisterMBean(registeredJmxName);
        } catch (JMException e) {
            log.warn("Failed to unregister the JMX name: " + registeredJmxName, e);
        } finally {
            registeredJmxName = null;
        }
    }
    closed = true;
    GenericObjectPool<?> oldpool = connectionPool;
    connectionPool = null;
    dataSource = null;
    try {
        if (oldpool != null) {
            oldpool.close();
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException(Utils.getMessage("pool.close.fail"), e);
    }
}

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

/**
 * Test metrics reporting for consumer//from  ww w  .  j a  v a2 s.com
 *
 * @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:JDBCPool.dbcp.demo.sourcecode.BasicDataSource.java

private void jmxRegister() {
    // Return immediately if this DataSource has already been registered
    if (registeredJmxName != null) {
        return;//w w w. j ava 2  s .  co m
    }
    // Return immediately if no JMX name has been specified
    String requestedName = getJmxName();
    if (requestedName == null) {
        return;
    }
    ObjectName oname;
    try {
        oname = new ObjectName(requestedName);
    } catch (MalformedObjectNameException e) {
        log.warn("The requested JMX name [" + requestedName + "] was not valid and will be ignored.");
        return;
    }

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        mbs.registerMBean(this, oname);
    } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
        log.warn("Failed to complete JMX registration", e);
    }
}

From source file:com.frameworkset.commons.dbcp2.BasicDataSource.java

private void jmxRegister() {
    // Return immediately if this DataSource has already been registered
    if (registeredJmxName != null) {
        return;/* w  w w  . ja va  2s  .co  m*/
    }
    // Return immediately if no JMX name has been specified
    String requestedName = getJmxName();
    if (requestedName == null) {
        return;
    }
    ObjectName oname;
    try {
        oname = new ObjectName(requestedName);
    } catch (MalformedObjectNameException e) {
        log.warn("The requested JMX name [" + requestedName + "] was not valid and will be ignored.");
        return;
    }

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        mbs.registerMBean(this, oname);
    } catch (InstanceAlreadyExistsException e) {
        log.warn("Failed to complete JMX registration", e);
    } catch (MBeanRegistrationException e) {
        log.warn("Failed to complete JMX registration", e);
    } catch (NotCompliantMBeanException e) {
        log.warn("Failed to complete JMX registration", e);
    }
}