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.killbill.billing.server.listeners.KillbillPlatformGuiceListener.java

protected void registerEhcacheMBeans() {
    final CacheManager cacheManager = injector.getInstance(CacheManager.class);
    if (cacheManager != null) {
        final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        ManagementService.registerMBeans(cacheManager, mBeanServer, false, true, true, true);
    }/* w  ww.ja  v a 2s.  c  om*/
}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine/*from www . j  av a2 s.c om*/
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}

From source file:ddf.catalog.cache.solr.impl.SolrCache.java

private void configureMBean() {
    LOGGER.info("Registering Cache Manager Service MBean");
    mbeanServer = ManagementFactory.getPlatformMBeanServer();

    try {//from  ww  w .ja  va2 s .  c  o  m
        try {

            mbeanServer.registerMBean(new StandardMBean(this, SolrCacheMBean.class), objectName);
        } catch (InstanceAlreadyExistsException e) {
            LOGGER.info("Re-registering Cache Manager MBean");
            mbeanServer.unregisterMBean(objectName);
            mbeanServer.registerMBean(new StandardMBean(this, SolrCacheMBean.class), objectName);
        }
    } catch (Exception e) {
        LOGGER.warn("Could not register MBean.", e);
    }
}

From source file:org.mule.module.management.agent.AbstractJmxAgent.java

/**
 * {@inheritDoc}/*from w w w .  j ava 2  s .  c o m*/
 */
public void initialise() throws InitialisationException {
    if (initialized.get()) {
        return;
    }

    this.containerMode = muleContext.getConfiguration().isContainerMode();

    try {
        Object agent = muleContext.getRegistry().lookupObject(this.getClass());
        // if we find ourselves, but not initialized yet - proceed with init, otherwise return
        if (agent == this && this.initialized.get()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Found an existing JMX agent in the registry, we're done here.");
            }
            return;
        }
    } catch (Exception e) {
        throw new InitialisationException(e, this);
    }

    if (mBeanServer == null && createServer) {
        // here we create a new mbean server, not using a platform one
        mBeanServer = MBeanServerFactory.createMBeanServer();
        serverCreated.set(true);
    }

    if (mBeanServer == null && locateServer) {
        mBeanServer = ManagementFactory.getPlatformMBeanServer();
    }

    if (mBeanServer == null) {
        throw new InitialisationException(ManagementMessages.cannotLocateOrCreateServer(), this);
    }

    if (StringUtils.isBlank(muleContext.getConfiguration().getId())) {
        // TODO i18n the message properly
        throw new IllegalArgumentException(
                "Manager ID is mandatory when running with JmxAgent. Give your Mule configuration a valid ID.");
    }

    try {
        // We need to register all the services once the server has initialised
        muleContextStartedListener = new MuleContextStartedListener();
        muleContext.registerListener(muleContextStartedListener);
        // and unregister once context stopped
        muleContextStoppedListener = new MuleContextStoppedListener();
        muleContext.registerListener(muleContextStoppedListener);
    } catch (NotificationException e) {
        throw new InitialisationException(e, this);
    }
    initialized.compareAndSet(false, true);
}

From source file:org.apache.solr.servlet.SolrDispatchFilter.java

private void setupJvmMetrics() {
    MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
    SolrMetricManager metricManager = cores.getMetricManager();
    try {/*from   w  w w. j a  v a2  s.  c om*/
        String registry = SolrMetricManager.getRegistryName(SolrInfoMBean.Group.jvm);
        metricManager.registerAll(registry, new BufferPoolMetricSet(platformMBeanServer), true, "buffers");
        metricManager.registerAll(registry, new ClassLoadingGaugeSet(), true, "classes");
        metricManager.registerAll(registry, new OperatingSystemMetricSet(platformMBeanServer), true, "os");
        metricManager.registerAll(registry, new GarbageCollectorMetricSet(), true, "gc");
        metricManager.registerAll(registry, new MemoryUsageGaugeSet(), true, "memory");
        metricManager.registerAll(registry, new ThreadStatesGaugeSet(), true, "threads"); // todo should we use CachedThreadStatesGaugeSet instead?
    } catch (Exception e) {
        log.warn("Error registering JVM metrics", e);
    }
}

From source file:org.jolokia.backend.MBeanServerHandler.java

/**
 * Register a MBean under a certain name to the platform MBeanServer
 *
 * @param pMBean MBean to register//  w w  w.  j  ava  2 s  .c  o m
 * @param pOptionalName optional name under which the bean should be registered. If not provided,
 * it depends on whether the MBean to register implements {@link javax.management.MBeanRegistration} or
 * not.
 *
 * @return the name under which the MBean is registered.
 */
public final ObjectName registerMBean(Object pMBean, String... pOptionalName)
        throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException {
    synchronized (mBeanHandles) {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        try {
            String name = pOptionalName != null && pOptionalName.length > 0 ? pOptionalName[0] : null;
            ObjectName registeredName = serverHandle.registerMBeanAtServer(server, pMBean, name);
            mBeanHandles.add(new MBeanHandle(server, registeredName));
            return registeredName;
        } catch (RuntimeException exp) {
            throw new IllegalStateException("Could not register " + pMBean + ": " + exp, exp);
        } catch (MBeanRegistrationException exp) {
            throw new IllegalStateException("Could not register " + pMBean + ": " + exp, exp);
        }
    }
}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the message store's health status
 *
 * @return true if healthy, else false.//from w ww . j a  va 2  s .c o m
 * @throws ClusterMgtException
 */
public boolean getStoreHealth() throws ClusterMgtException {
    boolean storeHealth = false;
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.STORE_HEALTH);
        if (result != null) {
            storeHealth = (Boolean) result;
        }
        return storeHealth;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot get message store health.", e);
    }
}

From source file:com.enioka.jqm.tools.JndiContext.java

@Override
public Object lookup(String name) throws NamingException {
    if (name == null) {
        throw new IllegalArgumentException("name cannot be null");
    }/* w ww  .j a v  a  2  s .  com*/
    jqmlogger.trace("Looking up a JNDI element named " + name);

    // Special delegated cases
    if (name.startsWith("rmi:")) {
        try {
            return this.r.lookup(name.split("/")[3]);
        } catch (Exception e) {
            NamingException e1 = new NamingException();
            e1.setRootCause(e);
            throw e1;
        }
    }
    if (name.endsWith("serverName")) {
        return JqmEngine.latestNodeStartedName;
    }

    // If in cache...
    if (singletons.containsKey(name)) {
        jqmlogger.trace("JNDI element named " + name + " found in cache.");
        return singletons.get(name);
    }

    // Retrieve the resource description from the database or the XML file
    JndiResourceDescriptor d = ResourceParser.getDescriptor(name);
    jqmlogger.trace("JNDI element named " + name + " not found in cache. Will be created. Singleton status: "
            + d.isSingleton());

    // Singleton handling is synchronized to avoid double creation
    if (d.isSingleton()) {
        synchronized (singletons) {
            if (singletons.containsKey(name)) {
                return singletons.get(name);
            }

            // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
            // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
            Object res = null;
            try {
                ResourceFactory rf = new ResourceFactory(Thread.currentThread()
                        .getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                                ? Thread.currentThread().getContextClassLoader()
                                : extResources);
                res = rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
            } catch (Exception e) {
                jqmlogger.warn("Could not instanciate singleton JNDI object resource " + name, e);
                NamingException ex = new NamingException(e.getMessage());
                ex.initCause(e);
                throw ex;
            }

            // Cache result
            if (res.getClass().getClassLoader() instanceof JarClassLoader) {
                jqmlogger.warn(
                        "A JNDI resource was defined as singleton but was loaded by a payload class loader - it won't be cached to avoid class loader leaks");
            } else {
                singletons.put(name, res);

                // Pool JMX registration (only if cached - avoids leaks)
                if ("org.apache.tomcat.jdbc.pool.DataSourceFactory".equals(d.getFactoryClassName())
                        && (d.get("jmxEnabled") == null ? true
                                : Boolean.parseBoolean((String) d.get("jmxEnabled").getContent()))) {
                    try {
                        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                        ObjectName jmxname = new ObjectName("com.enioka.jqm:type=JdbcPool,name=" + name);
                        mbs.registerMBean(res.getClass().getMethod("getPool").invoke(res).getClass()
                                .getMethod("getJmxPool")
                                .invoke(res.getClass().getMethod("getPool").invoke(res)), jmxname);
                        jmxNames.add(jmxname);
                    } catch (Exception e) {
                        jqmlogger.warn("Could not register JMX MBean for resource.", e);
                    }
                }
            }

            // Done
            return res;
        }
    }

    // Non singleton
    try {
        // We use the current thread loader to find the resource and resource factory class - ext is inside that CL.
        // This is done only for payload CL - engine only need ext, not its own CL (as its own CL does NOT include ext).
        ResourceFactory rf = new ResourceFactory(
                Thread.currentThread().getContextClassLoader() instanceof com.enioka.jqm.tools.JarClassLoader
                        ? Thread.currentThread().getContextClassLoader()
                        : extResources);
        return rf.getObjectInstance(d, null, this, new Hashtable<String, Object>());
    } catch (Exception e) {
        jqmlogger.warn("Could not instanciate JNDI object resource " + name, e);
        NamingException ex = new NamingException(e.getMessage());
        ex.initCause(e);
        throw ex;
    }
}

From source file:org.lilyproject.hadooptestfw.HBaseProxy.java

/**
 * @param timestampReusingTables map containing table name as key and column family as value. Since HBase does
 *                               not support supporting writing data older than a deletion thombstone, these tables
 *                               will be compacted and waited for until inserting data works again.
 *///from  w w  w  . j  a  va2 s.c  o m
public void start(Map<String, byte[]> timestampReusingTables) throws Exception {
    System.out.println("HBaseProxy mode: " + mode);

    conf = HBaseConfiguration.create();

    switch (mode) {
    case EMBED:
        addHBaseTestProps(conf);
        addUserProps(conf);

        initTestHome();

        System.out.println("HBaseProxy embedded mode temp dir: " + testHome.getAbsolutePath());

        hbaseTestUtil = HBaseTestingUtilityFactory.create(conf, testHome, clearData);
        hbaseTestUtil.startMiniCluster(1);
        if (enableMapReduce) {
            hbaseTestUtil.startMiniMapReduceCluster(1);
        }

        writeConfiguration(testHome, conf);

        // In the past, it happened that HMaster would not become initialized, blocking later on
        // the proper shutdown of the mini cluster. Now added this as an early warning mechanism.
        long before = System.currentTimeMillis();
        while (!hbaseTestUtil.getMiniHBaseCluster().getMaster().isInitialized()) {
            if (System.currentTimeMillis() - before > 60000) {
                throw new RuntimeException("HMaster.isInitialized() does not become true.");
            }
            System.out.println("Waiting for HMaster to be initialized");
            Thread.sleep(500);
        }

        conf = hbaseTestUtil.getConfiguration();
        cleanupUtil = new CleanupUtil(conf, getZkConnectString());
        break;
    case CONNECT:
        conf.set("hbase.zookeeper.quorum", "localhost");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conf.set("hbase.replication", "true");

        addUserProps(conf);

        cleanupUtil = new CleanupUtil(conf, getZkConnectString());
        if (cleanStateOnConnect) {
            cleanupUtil.cleanZooKeeper();

            Map<String, byte[]> allTimestampReusingTables = new HashMap<String, byte[]>();
            allTimestampReusingTables.putAll(cleanupUtil.getDefaultTimestampReusingTables());
            allTimestampReusingTables.putAll(timestampReusingTables);
            cleanupUtil.cleanTables(allTimestampReusingTables);

            List<String> removedPeers = cleanupUtil.cleanHBaseReplicas();
            for (String removedPeer : removedPeers) {
                waitOnReplicationPeerStopped(removedPeer);
            }
        }

        break;
    default:
        throw new RuntimeException("Unexpected mode: " + mode);
    }

    ManagementFactory.getPlatformMBeanServer().registerMBean(mbean,
            new ObjectName("LilyHBaseProxy:name=ReplicationPeer"));
}

From source file:edu.umd.cs.buildServer.BuildServer.java

protected void configureBuildServerForMBeanManagement() {
    buildServerConfiguration = new BuildServerConfiguration();
    // Try to configure a BuildServerConfiguration object
    try {/*from www .j a  va 2s.c o  m*/
        buildServerConfiguration.loadAllProperties(getConfig(), getLog());
        // Get MBeanServer
        MBeanServer platformMBeanserver = ManagementFactory.getPlatformMBeanServer();
        // Register the BuildServerMBean
        ObjectName buildServerName = new ObjectName("edu.umd.cs.buildServer:id=BuildServerManager");
        platformMBeanserver.registerMBean(buildServerConfiguration, buildServerName);
    } catch (MalformedObjectNameException e) {
        throw new RuntimeException(e);
    } catch (MBeanRegistrationException e) {
        throw new RuntimeException(e);
    } catch (NotCompliantMBeanException e) {
        throw new RuntimeException(e);
    } catch (InstanceAlreadyExistsException e) {
        throw new RuntimeException(e);
    } catch (MissingConfigurationPropertyException e) {
        // getLog().warn("Unable to configure (experimental) BuildServerConfiguration object");
        if (!isQuiet()) {
            System.out.println(e);
            e.printStackTrace();
        }

    }
}