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.apache.geode.management.internal.ManagementAgent.java

/**
 * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html #gdfvq
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector
 * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 *///from  www  . j a v  a  2  s  . c om
private void configureAndStart() throws IOException {
    // get the port for RMI Registry and RMI Connector Server
    final int port = this.config.getJmxManagerPort();
    final String hostname;
    final InetAddress bindAddr;
    if (StringUtils.isBlank(this.config.getJmxManagerBindAddress())) {
        hostname = SocketCreator.getLocalHost().getHostName();
        bindAddr = null;
    } else {
        hostname = this.config.getJmxManagerBindAddress();
        bindAddr = InetAddress.getByName(hostname);
    }

    String jmxManagerHostnameForClients = this.config.getJmxManagerHostnameForClients();
    if (StringUtils.isNotBlank(jmxManagerHostnameForClients)) {
        System.setProperty("java.rmi.server.hostname", jmxManagerHostnameForClients);
    }

    final SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.JMX);

    final boolean ssl = socketCreator.useSSL();

    if (logger.isDebugEnabled()) {
        logger.debug("Starting jmx manager agent on port {}{}", port,
                (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
    }
    RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null;
    RMIServerSocketFactory rmiServerSocketFactory = new GemFireRMIServerSocketFactory(socketCreator, bindAddr);

    // Following is done to prevent rmi causing stop the world gcs
    System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE - 1));

    // Create the RMI Registry using the SSL socket factories above.
    // In order to use a single port, we must use these factories
    // everywhere, or nowhere. Since we want to use them in the JMX
    // RMI Connector server, we must also use them in the RMI Registry.
    // Otherwise, we wouldn't be able to use a single port.

    // Start an RMI registry on port <port>.
    registry = LocateRegistry.createRegistry(port, rmiClientSocketFactory, rmiServerSocketFactory);

    // Retrieve the PlatformMBeanServer.
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Environment map. why is this declared as HashMap?
    final HashMap<String, Object> env = new HashMap<>();

    // Manually creates and binds a JMX RMI Connector Server stub with the
    // registry created above: the port we pass here is the port that can
    // be specified in "service:jmx:rmi://"+hostname+":"+port - where the
    // RMI server stub and connection objects will be exported.
    // Here we choose to use the same port as was specified for the
    // RMI Registry. We can do so because we're using \*the same\* client
    // and server socket factories, for the registry itself \*and\* for this
    // object.
    final RMIServerImpl stub = new RMIJRMPServerImpl(port, rmiClientSocketFactory, rmiServerSocketFactory, env);

    // Create an RMI connector server.
    //
    // As specified in the JMXServiceURL the RMIServer stub will be
    // registered in the RMI registry running in the local host on
    // port <port> with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    // The port specified in "service:jmx:rmi://"+hostname+":"+port
    // is the second port, where RMI connection objects will be exported.
    // Here we use the same port as that we choose for the RMI registry.
    // The port for the RMI registry is specified in the second part
    // of the URL, in "rmi://"+hostname+":"+port
    //
    // We construct a JMXServiceURL corresponding to what we have done
    // for our stub...
    final JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi://" + hostname + ":" + port + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");

    // Create an RMI connector server with the JMXServiceURL
    //
    // JDK 1.5 cannot use JMXConnectorServerFactory because of
    // http://bugs.sun.com/view_bug.do?bug_id=5107423
    // but we're using JDK 1.6
    jmxConnectorServer = new RMIConnectorServer(new JMXServiceURL("rmi", hostname, port), env, stub, mbs) {
        @Override
        public JMXServiceURL getAddress() {
            return url;
        }

        @Override
        public synchronized void start() throws IOException {
            try {
                registry.bind("jmxrmi", stub);
            } catch (AlreadyBoundException x) {
                throw new IOException(x.getMessage(), x);
            }
            super.start();
        }
    };

    if (securityService.isIntegratedSecurity()) {
        shiroAuthenticator = new JMXShiroAuthenticator(this.securityService);
        env.put(JMXConnectorServer.AUTHENTICATOR, shiroAuthenticator);
        jmxConnectorServer.addNotificationListener(shiroAuthenticator, null,
                jmxConnectorServer.getAttributes());
        // always going to assume authorization is needed as well, if no custom AccessControl, then
        // the CustomAuthRealm
        // should take care of that
        MBeanServerWrapper mBeanServerWrapper = new MBeanServerWrapper(this.securityService);
        jmxConnectorServer.setMBeanServerForwarder(mBeanServerWrapper);
        registerAccessControlMBean();
    } else {
        /* Disable the old authenticator mechanism */
        String pwFile = this.config.getJmxManagerPasswordFile();
        if (pwFile != null && pwFile.length() > 0) {
            env.put("jmx.remote.x.password.file", pwFile);
        }

        String accessFile = this.config.getJmxManagerAccessFile();
        if (accessFile != null && accessFile.length() > 0) {
            // Rewire the mbs hierarchy to set accessController
            ReadOpFileAccessController controller = new ReadOpFileAccessController(accessFile);
            controller.setMBeanServer(mbs);
        }
    }

    jmxConnectorServer.start();
    if (logger.isDebugEnabled()) {
        logger.debug("Finished starting jmx manager agent.");
    }
}

From source file:org.apache.cassandra.db.ColumnFamilyStore.java

void unregisterMBean() {
    try {// w ww .j ava 2 s.co  m
        invalid = true;
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName nameObj = new ObjectName(mbeanName);
        if (mbs.isRegistered(nameObj))
            mbs.unregisterMBean(nameObj);
        for (ColumnFamilyStore index : indexedColumns.values())
            index.unregisterMBean();
    } catch (Exception e) {
        // this shouldn't block anything.
        logger.warn(e.getMessage(), e);
    }
}

From source file:org.openspaces.pu.container.jee.jetty.JettyJeeProcessingUnitContainerProvider.java

private void initJettyJmx(JettyHolder jettyHolder) {
    String jmxEnabled = getBeanLevelProperties().getContextProperties().getProperty(JETTY_JMX_PROP, "false");
    if ("true".equals(jmxEnabled)) {
        MBeanContainer mBeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
        String domain = "gigaspaces.jetty";
        if (!jettyHolder.isSingleInstance()) {
            domain += "." + getClusterInfo().getName() + "." + getClusterInfo().getRunningNumberOffset1();
        }// ww w .j  a  va 2  s  .  c  om
        mBeanContainer.setDomain(domain);
        jettyHolder.getServer().addEventListener(mBeanContainer);
    }
}

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

/**
 * Collects Kafka consumer domain {@code 'kafka.consumer'} JMX attributes values.
 *
 * @param tracker/*from w w  w.  j av  a  2 s. c o m*/
 *            tracker instance to use
 * @return activity containing snapshots of Kafka consumer JMX attributes values
 *
 * @see #collectMetricsJMX(String, javax.management.MBeanServer, com.jkoolcloud.tnt4j.core.Activity)
 */
private TrackingActivity collectKafkaConsumerMetricsJMX(Tracker tracker) {
    TrackingActivity activity = tracker.newActivity(OpLevel.INFO, "Kafka consumer JMX metrics"); // NON-NLS

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        collectMetricsJMX("kafka.consumer:*", mBeanServer, activity); // NON-NLS
    } catch (Exception exc) {
        Utils.logThrowable(LOGGER, OpLevel.WARNING,
                StreamsResources.getBundle(KafkaStreamConstants.RESOURCE_BUNDLE_NAME),
                "MetricsReporter.consumer.jmx.fail", exc);
    }

    return activity;
}

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

/**
 * Utility method to allow transports to register MBeans
 * @param mbeanInstance bean instance/*from   www .  j a  v  a2  s. c  om*/
 * @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.rhq.enterprise.server.core.StartupBean.java

/**
 * Installs the JAAS login modules so our users can login.
 *
 * @throws RuntimeException/*w  w  w .  java  2  s.c om*/
 */
private void upgradeRhqUserSecurityDomainIfNeeded() throws RuntimeException {

    try {
        CustomJaasDeploymentServiceMBean jaas_mbean;
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = CustomJaasDeploymentServiceMBean.OBJECT_NAME;
        Class<?> iface = CustomJaasDeploymentServiceMBean.class;
        jaas_mbean = (CustomJaasDeploymentServiceMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, name,
                iface, false);
        jaas_mbean.upgradeRhqUserSecurityDomainIfNeeded();
    } catch (Exception e) {
        error += (error.isEmpty() ? "" : ", ") + "security domain upgrade";
        throw new RuntimeException("Cannot upgrade JAAS login modules!", e);
    }
}

From source file:org.eclipse.virgo.web.test.AbstractWebIntegrationTests.java

private void awaitWebAppStart(String name, String version) throws InterruptedException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {/*from   w ww.  ja  v  a2 s  .  co m*/
        ObjectName objectName = new ObjectName(String.format(
                "org.eclipse.virgo.kernel:type=ArtifactModel,artifact-type=bundle,name=%s,version=%s,region=%s",
                name, version, USER_REGION_NAME));
        ManageableArtifact artifact = JMX.newMXBeanProxy(mBeanServer, objectName, ManageableArtifact.class);

        long startTime = System.currentTimeMillis();

        while (artifact.getProperties().get("org.eclipse.virgo.web.contextPath") == null) {
            Thread.sleep(100);
            if (System.currentTimeMillis() - startTime > HOT_DEPLOY_TIMEOUT) {
                throw new RuntimeException(name + " " + version + " failed to set its context path within "
                        + (HOT_DEPLOY_TIMEOUT / 1000) + " seconds.");
            }
        }
    } catch (JMException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jumpmind.symmetric.SymmetricWebServer.java

protected void removeHttpJmxAdaptor() {
    if (AppUtils.isSystemPropertySet(SystemConstants.SYSPROP_JMX_HTTP_CONSOLE_ENABLED, true) && jmxEnabled) {
        try {//  w w w. ja  v  a 2  s .com
            MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
            mbeanServer.unregisterMBean(getHttpJmxAdaptorName());
            mbeanServer.unregisterMBean(getXslJmxAdaptorName());
        } catch (Exception e) {
            log.warn("Could not unregister the JMX HTTP Adaptor");
        }
    }
}

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

public static void RegisterJmxBean(Object bean, String beanName, String jmxAppName) {
    try {// w  ww  . j a  v  a  2  s .  c o  m
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        if (!StringUtils.isBlank(jmxAppName))
            beanName += ",app=" + jmxAppName;

        ObjectName name = new ObjectName(beanName);

        // Make sure the bean doesn't already exist.  If it does, unregister it.
        try {
            mbs.getMBeanInfo(name); // Throws InstanceNotFoundException if not found.
            mbs.unregisterMBean(name); // Unregister a bean if it exists.
        } catch (InstanceNotFoundException e) {
            // If we get here then the mbean isn't currently registered.  This is valid
            // so we'll ignore it.
        }

        mbs.registerMBean(bean, name);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Bean Name = %s, app=%s", beanName, jmxAppName)
                .appendMessage("Bean class = %s", bean.getClass().getName());

    }

}

From source file:com.web.server.SARDeployer.java

/**
 * This method undeployed the SAR/*from ww  w .  j av  a 2 s.  c o m*/
 * @param dir
 * @return
 */
public boolean deleteDir(File dir) {
    String fileName = dir.getName();
    System.out.println("Dirname to be deleted" + fileName);
    Sar sar = null;
    try {
        sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
    } catch (IOException | SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
    if (sarClassLoader != null) {
        ClassLoaderUtil.closeClassLoader(sarClassLoader);
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        try {
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                System.out.println(mbean.getObjectname());
                System.out.println(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                if (mbs.isRegistered(objName)) {
                    mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbs.unregisterMBean(objName);
                }
            }
            sarsMap.remove(fileName);
        } catch (MalformedObjectNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return recursiveDelete(dir);

}