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.nuxeo.ecm.core.management.jtajca.internal.DefaultConnectionMonitor.java

protected void bindManagementInterface(String repositoryName, DefaultConnectionMonitor monitor) {
    try {//from  w ww  .j  a v  a2 s . c om
        mbs = ManagementFactory.getPlatformMBeanServer();
        mbs.registerMBean(monitor, getObjectName(repositoryName));
    } catch (JMException cause) {
        throw new RuntimeException("Cannot register connection monitor", cause);
    }
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static List<String> getEndPoints()
        throws MalformedObjectNameException, NullPointerException, UnknownHostException,
        AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> objs = mbs.queryNames(new ObjectName("*:type=Connector,*"),
            Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
    String hostname = InetAddress.getLocalHost().getHostName();
    InetAddress[] addresses = InetAddress.getAllByName(hostname);
    ArrayList<String> endPoints = new ArrayList<>();
    for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
        ObjectName obj = i.next();
        String scheme = mbs.getAttribute(obj, "scheme").toString();
        String port = obj.getKeyProperty("port");
        for (InetAddress addr : addresses) {
            String host = addr.getHostAddress();
            String ep = scheme + "://" + host + ":" + port;
            endPoints.add(ep);/*from   w  w w .ja v  a  2s .c o  m*/
        }
    }
    return endPoints;
}

From source file:co.runrightfast.vertx.core.application.RunRightFastVertxApplicationLauncherTest.java

@Test
public void testRunApp() throws Exception {
    ForkJoinPool.commonPool().execute(() -> RunRightFastVertxApplicationLauncher.run(() -> app));

    final RunRightFastVerticleId verticleManagerId = RunRightFastVerticleManager.VERTICLE_ID;
    final CompletableFuture future = new CompletableFuture();
    final String address = EventBusAddress.eventBusAddress(verticleManagerId, "get-verticle-deployments");
    final Vertx vertx = app.vertxService().getVertx();
    vertx.eventBus().send(address, GetVerticleDeployments.Request.newBuilder().build(),
            new DeliveryOptions().setSendTimeout(2000L), getVerticleDeploymentsResponseHandler(future));
    final Object result = future.get(2000L, TimeUnit.MILLISECONDS);

    final ApplicationMXBean appMXBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(),
            applicationMBeanObjectName(JmxUtils.RUNRIGHTFAST_JMX_DOMAIN, ApplicationMXBean.class),
            ApplicationMXBean.class);
    assertThat(appMXBean.getApplicationGroup(), is("co.runrightfast"));
    assertThat(appMXBean.getApplicationName(), is("test-app"));
    assertThat(appMXBean.getApplicationVersion(), is("1.0.0"));
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHConf", appMXBean.configAsHConf() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configAsHJson", appMXBean.configAsJson() });
    log.logp(INFO, getClass().getName(), "testRunApp", "{0}:\n{1}",
            new Object[] { "configWithCommentsAndSourceInfo", appMXBean.configWithCommentsAndSourceInfo() });
    appMXBean.shutdown();/*from w  w w  . j a  v  a  2  s .  co m*/
    app.vertxService().awaitTerminated();
}

From source file:com.haulmont.cuba.core.app.ClusterManager.java

protected void registerJmxBeans() {
    try {// ww w. ja v  a 2 s  .c o  m
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        JmxConfigurator.registerChannel(channel, mBeanServer, getMBeanDomain(), getClusterName(), true);
    } catch (Exception e) {
        log.error("Failed to register channel in jmx", e);
    }
}

From source file:com.magnet.mmx.server.plugin.mmxmgmt.MMXPlugin.java

public void destroyPlugin() {
    XMPPServer server = XMPPServer.getInstance();
    IQRouter iqRouter = server.getIQRouter();
    iqRouter.removeHandler(mIQAppRegHandler);
    iqRouter.removeHandler(mIQDevRegHandler);
    iqRouter.removeHandler(mIQUserRegHandler);
    iqRouter.removeHandler(mIQMessageStateHandler);
    iqRouter.removeHandler(mIQPubSubHandler);
    iqRouter.removeHandler(mIQWakeupNSHandler);
    iqRouter.removeHandler(mIQPushNSHandler);
    iqRouter.removeHandler(mIQMsgAckNSHandler);
    InterceptorManager.getInstance().removeInterceptor(mmxPacketInterceptor);
    wakeupExecutionManager.stopWakeupExecution();
    timeoutExecutionManager.stopTimeoutCheck();

    // shutdown geo event dispatcher
    contextDispatcher.shutdown();/*from   w w w. jav  a2 s. c o  m*/

    //Teardown the APNS Connection pool
    APNSConnectionPoolImpl.teardown();
    adminAPIServer.stop();
    publicAPIServer.stop();

    try {
        ObjectName mbeanName = new ObjectName(MMXServerConstants.MMX_MBEAN_NAME);
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        mbs.unregisterMBean(mbeanName);
    } catch (Exception e) {
        Log.error("destroyPlugin : error unregistering mbean={}", MMXServerConstants.MMX_MBEAN_NAME);
    }
    apnsFeedbackProcessExecutionManager.stop();
    Log.info("App Management Plugin is destroyed");
}

From source file:com.bigdata.dastor.service.StorageService.java

public StorageService() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {//from  ww  w  .  ja va2s .  co  m
        mbs.registerMBean(this, new ObjectName("com.bigdata.dastor.service:type=StorageService"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    bootstrapSet = Multimaps.synchronizedSetMultimap(HashMultimap.<InetAddress, String>create());

    /* register the verb handlers */
    MessagingService.instance.registerVerbHandlers(Verb.BINARY, new BinaryVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.MUTATION, new RowMutationVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ_REPAIR, new ReadRepairVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ, new ReadVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.RANGE_SLICE, new RangeSliceVerbHandler());
    // see BootStrapper for a summary of how the bootstrap verbs interact
    MessagingService.instance.registerVerbHandlers(Verb.BOOTSTRAP_TOKEN,
            new BootStrapper.BootstrapTokenVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_REQUEST, new StreamRequestVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_INITIATE, new StreamInitiateVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_INITIATE_DONE,
            new StreamInitiateDoneVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.STREAM_FINISHED, new StreamFinishedVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.READ_RESPONSE, new ResponseVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.TREE_REQUEST, new TreeRequestVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.TREE_RESPONSE,
            new AntiEntropyService.TreeResponseVerbHandler());

    MessagingService.instance.registerVerbHandlers(Verb.JOIN, new GossiperJoinVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_SYN, new GossipDigestSynVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK, new GossipDigestAckVerbHandler());
    MessagingService.instance.registerVerbHandlers(Verb.GOSSIP_DIGEST_ACK2, new GossipDigestAck2VerbHandler());

    replicationStrategies = new HashMap<String, AbstractReplicationStrategy>();
    for (String table : DatabaseDescriptor.getNonSystemTables()) {
        AbstractReplicationStrategy strat = getReplicationStrategy(tokenMetadata_, table);
        replicationStrategies.put(table, strat);
    }
    replicationStrategies = Collections.unmodifiableMap(replicationStrategies);

    // spin up the streaming serivice so it is available for jmx tools.
    if (StreamingService.instance == null)
        throw new RuntimeException("Streaming service is unavailable.");
}

From source file:com.continuent.tungsten.common.jmx.JmxManager.java

/**
 * Starts the JMX connector for the server.
 *//* w  ww .j  a v  a2  s. co m*/
protected void startJmxConnector() {
    String serviceAddress = null;
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        serviceAddress = generateServiceAddress(host, beanPort, registryPort, serviceName);
        JMXServiceURL address = new JMXServiceURL(serviceAddress);

        // --- Define security attributes ---
        HashMap<String, Object> env = new HashMap<String, Object>();

        // --- Authentication based on password and access files---
        if (authenticationInfo != null && authenticationInfo.isAuthenticationNeeded()) {

            if (authenticationInfo.isUseTungstenAuthenticationRealm())
                env.put(JMXConnectorServer.AUTHENTICATOR, new RealmJMXAuthenticator(authenticationInfo));
            else
                env.put("jmx.remote.x.password.file", authenticationInfo.getPasswordFileLocation());

            env.put("jmx.remote.x.access.file", authenticationInfo.getAccessFileLocation());
        }

        // --- SSL encryption ---
        if (authenticationInfo != null && authenticationInfo.isEncryptionNeeded()) {
            // Keystore
            System.setProperty("javax.net.ssl.keyStore", authenticationInfo.getKeystoreLocation());
            System.setProperty("javax.net.ssl.keyStorePassword", authenticationInfo.getKeystorePassword());
            /**
             * Configure SSL. Protocols and ciphers are set in
             * securityHelper.setSecurityProperties and used by
             * SslRMIClientSocketFactory
             */
            try {
                String[] protocolArray = authenticationInfo.getEnabledProtocols().toArray(new String[0]);
                String[] allowedCipherSuites = authenticationInfo.getEnabledCipherSuites()
                        .toArray(new String[0]);
                String[] cipherArray;

                if (protocolArray.length == 0)
                    protocolArray = null;
                if (allowedCipherSuites.length == 0)
                    cipherArray = null;
                else {
                    // Ensure we choose an allowed cipher suite.
                    cipherArray = authenticationInfo.getJvmEnabledCipherSuites().toArray(new String[0]);
                    if (cipherArray.length == 0) {
                        // We don't have any cipher suites in common. This
                        // is not good!
                        String message = "Unable to find approved ciphers in the supported cipher suites on this JVM";
                        StringBuffer sb = new StringBuffer(message).append("\n");
                        sb.append(String.format("JVM supported cipher suites: %s\n",
                                StringUtils.join(SecurityHelper.getJvmSupportedCiphers())));
                        sb.append(String.format("Approved cipher suites from security.properties: %s\n",
                                StringUtils.join(allowedCipherSuites)));
                        logger.error(sb.toString());
                        throw new RuntimeException(message);
                    }
                }

                logger.info("Setting allowed JMX server protocols: " + StringUtils.join(protocolArray, ","));
                logger.info("Setting allowed JMX server ciphers: " + StringUtils.join(cipherArray, ","));
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(cipherArray, protocolArray,
                        false);
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            } catch (IllegalArgumentException ie) {
                logger.warn("Some of the protocols or ciphers are not supported. " + ie.getMessage());
                throw new RuntimeException(ie.getLocalizedMessage(), ie);
            }
        }

        env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true");
        JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(address, env, mbs);
        connector.start();

        logger.info(MessageFormat.format("JMXConnector: security.properties={0}",
                (authenticationInfo != null) ? authenticationInfo.getParentPropertiesFileLocation()
                        : "No security.properties file found !..."));
        if (authenticationInfo != null)
            logger.info(authenticationInfo.toString());
        logger.info(String.format("JMXConnector started at address %s", serviceAddress));

        jmxConnectorServer = connector;
    } catch (Throwable e) {
        throw new ServerRuntimeException(
                MessageFormat.format("Unable to create RMI listener: {0} -> {1}", getServiceProps(), e), e);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

private void createArtemisServer(String securityConfigScope) {
    ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager(securityConfigScope);
    HashMap<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(5672));
    params.put(TransportConstants.PROTOCOLS_PROP_NAME, "AMQP");

    HashMap<String, Object> amqpParams = new HashMap<>();
    amqpParams.put("saslMechanisms", "GSSAPI");
    amqpParams.put("saslLoginConfigScope", "amqp-sasl-gssapi");

    Configuration configuration = new ConfigurationImpl().setSecurityEnabled(true)
            .addAcceptorConfiguration(/*ww  w . j av  a 2  s  .c  o  m*/
                    new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-amqp", amqpParams))
            .setJournalDirectory(ActiveMQTestBase.getJournalDir(testDir, 0, false))
            .setBindingsDirectory(ActiveMQTestBase.getBindingsDir(testDir, 0, false))
            .setPagingDirectory(ActiveMQTestBase.getPageDir(testDir, 0, false))
            .setLargeMessagesDirectory(ActiveMQTestBase.getLargeMessagesDir(testDir, 0, false));
    server = ActiveMQServers.newActiveMQServer(configuration, ManagementFactory.getPlatformMBeanServer(),
            securityManager, false);
}

From source file:com.haulmont.cuba.core.app.ClusterManager.java

protected void unregisterJmxBeans() {
    try {//from  www .  j av  a  2  s.co  m
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        JmxConfigurator.unregisterChannel(channel, mBeanServer, getMBeanDomain(), getClusterName());
    } catch (Exception e) {
        log.error("Failed to unregister channel in jmx", e);
    }
}