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:com.continuent.tungsten.common.jmx.JmxManager.java

public static DynamicMBeanHelper createHelper(Class<?> mbeanClass) throws Exception {
    ObjectName mbeanName = generateMBeanObjectName(mbeanClass);

    MBeanInfo info = ManagementFactory.getPlatformMBeanServer().getMBeanInfo(mbeanName);

    DynamicMBeanHelper helper = new DynamicMBeanHelper(mbeanClass, mbeanName, info);

    return helper;

}

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

public static DynamicMBeanHelper createHelper(Class<?> mbeanClass, String alias) throws Exception {
    ObjectName mbeanName = generateMBeanObjectName(mbeanClass.getName(), alias);

    // ObjectName mbeanName = generateMBeanObjectName(mbeanClass);

    MBeanInfo info = ManagementFactory.getPlatformMBeanServer().getMBeanInfo(mbeanName);

    DynamicMBeanHelper helper = new DynamicMBeanHelper(mbeanClass, mbeanName, info);

    return helper;

}

From source file:org.rhq.enterprise.server.core.StartupBean.java

/**
 * Starts the embedded agent, but only if the embedded agent is installed and it is enabled.
 *
 * @throws RuntimeException if the agent is installed and enabled but failed to start
 *
 * @deprecated we don't have an embedded agent anymore, leaving this in case we resurrect it
 *///from   ww w  .j  av  a 2  s  . com
@Deprecated
private void startEmbeddedAgent() throws RuntimeException {
    // we can't use EmbeddedAgentBootstrapServiceMBean because if the embedded agent
    // isn't installed, that class will not be available; we must use JMX API
    final ObjectName agentBootstrapMBean = ObjectNameFactory.create("rhq:service=EmbeddedAgentBootstrap");
    final String agentEnabledAttribute = "AgentEnabled";
    final String startAgentMethod = "startAgent";
    final String configurationOverridesAttribute = "ConfigurationOverrides";
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    try {
        // this will fail if the embedded agent isn't installed
        String enabled = (String) mbs.getAttribute(agentBootstrapMBean, agentEnabledAttribute);

        // if we got this far, the embedded agent is at least installed
        // now check to see if its enabled - if so start it; any startup exceptions now are thrown
        try {
            if (Boolean.valueOf(enabled)) {
                log.info("The embedded Agent is installed and enabled - it will now be started...");

                // NOTE: we cannot directly import AgentConfigurationConstants, so we hardcode the
                // actual constant values here - need to keep an eye on these in the unlikely event
                // the constant values change.
                String AgentConfigurationConstants_SERVER_TRANSPORT = "rhq.agent.server.transport";
                String AgentConfigurationConstants_SERVER_BIND_ADDRESS = "rhq.agent.server.bind-address";
                String AgentConfigurationConstants_SERVER_BIND_PORT = "rhq.agent.server.bind-port";

                // Get the configuration overrides as set in the configuration file.
                // If the agent's bind address isn't overridden with a non-empty value,
                // then we need to get the Server bind address and use it for the agent's bind address.
                // If the agent's server endpoint address/port are empty, we again use the values
                // appropriate for the Server this agent is embedded in.
                // Note that we don't look for the values in persisted preferences - we assume they
                // are always present in the configuration overrides (which they should always be);
                Properties overrides;
                String serverTransport;
                String serverAddress;
                String serverPort;
                String agentAddress;

                overrides = (Properties) mbs.getAttribute(agentBootstrapMBean, configurationOverridesAttribute);

                serverTransport = overrides.getProperty(AgentConfigurationConstants_SERVER_TRANSPORT);
                serverAddress = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS);
                serverPort = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_PORT);
                agentAddress = overrides
                        .getProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS);

                Server server = serverManager.getServer();

                if (agentAddress == null || agentAddress.trim().equals("")) {
                    overrides.setProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS,
                            server.getAddress());
                }
                if (serverAddress == null || serverAddress.trim().equals("")) {
                    overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS, server.getAddress());
                }
                if (serverPort == null || serverPort.trim().equals("")) {
                    if (SecurityUtil.isTransportSecure(serverTransport)) {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getSecurePort()));
                    } else {
                        overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT,
                                Integer.toString(server.getPort()));
                    }
                }

                mbs.setAttribute(agentBootstrapMBean,
                        new Attribute(configurationOverridesAttribute, overrides));

                // We need to do the agent startup in a separate thread so we do not hang
                // this startup servlet.  JBossAS 4.2 will not begin accepting HTTP requests
                // until this startup servlet has finished (this is different from JBossAS 4.0).
                // The agent needs to submit an HTTP request in order to complete its startup
                // (it needs to register with the server).
                // The side effect of this is the RHQ Server will still start even if the embedded
                // agent fails to start - this may not be a bad thing.  We probably do not want
                // the entire RHQ Server to go down if its agent fails to start.
                Runnable agentStartRunnable = new Runnable() {
                    public void run() {
                        // this returns only when the agent has started and is registered (sends HTTP request)
                        try {
                            mbs.invoke(agentBootstrapMBean, startAgentMethod, new Object[0], new String[0]);
                        } catch (Throwable t) {
                            log.error("Failed to start the embedded Agent - it will not be available!", t);
                        }
                    }
                };

                Thread agentStartThread = new Thread(agentStartRunnable, "Embedded Agent Startup");
                agentStartThread.setDaemon(true);
                agentStartThread.start();
            } else {
                log.debug("The embedded Agent is not enabled, so it will not be started.");
            }
        } catch (Throwable t) {
            throw new RuntimeException("Failed to start the embedded Agent.", t);
        }
    } catch (RuntimeException se) {
        throw se;
    } catch (Throwable t) {
        log.info("The embedded Agent is not installed, so it will not be started (" + t + ").");
    }

    return;
}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

@Override
public void sendComplete() {
    try {/*  w ww .j a  v a 2  s  . c o m*/
        boolean doPost = false;
        if (post != null) {
            int sample = 0;
            if (postRate > 1) {
                File sampleFile = new File("post.sample");
                if (Files.isFileReadable("post.sample")) {
                    try {
                        sample = Integer.parseInt(Bytes.toString(Files.read(sampleFile)));
                        sample = (sample + 1) % postRate;
                    } catch (NumberFormatException ignored) {

                    }
                }
                doPost = (sample == 0);
                Files.write(sampleFile, Bytes.toBytes(Integer.toString(sample)), false);
            } else {
                doPost = true;
            }
            if (doPost) {
                log.warn("post-chain: " + post);
                processBundle(new KVBundle(), post);
                processed.incrementAndGet();
            } else {
                log.warn("skipping post-chain: " + post + ". Sample rate is " + sample + " out of " + postRate);
            }
        }
        if (outputs != null) {
            for (PathOutput output : outputs) {
                log.warn("output: " + output);
                output.exec(tree);
            }
        }
        // turn off live queries
        if (liveQueryServer != null) {
            liveQueryServer.close();
        }
        // disable web interface
        jetty.stop();
        boolean doValidate;
        switch (validateTree) {
        case ALL:
            doValidate = true;
            break;
        case POST:
            doValidate = doPost;
            break;
        case NONE:
        default:
            doValidate = false;
        }
        // close storage
        log.info("[close] closing tree storage");
        CloseOperation closeOperation = CloseOperation.NONE;
        if (doValidate) {
            closeOperation = repairTree ? CloseOperation.REPAIR : CloseOperation.TEST;
        }
        tree.close(false, closeOperation);
        if (jmxname != null) {
            log.info("[close] unregistering JMX");
            ManagementFactory.getPlatformMBeanServer().unregisterMBean(jmxname);
            if (jmxremote != null) {
                jmxremote.stop();
                jmxremote = null;
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.red5.server.stream.ClientBroadcastStream.java

protected void registerJMX() {
    if (registerJMX) {
        // register with jmx
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {/*from w ww  .j a  v a2s .  c  om*/
            ObjectName oName = new ObjectName(
                    String.format("org.red5.server:type=ClientBroadcastStream,scope=%s,publishedName=%s",
                            getScope().getName(), publishedName));
            mbs.registerMBean(new StandardMBean(this, ClientBroadcastStreamMXBean.class, true), oName);
        } catch (InstanceAlreadyExistsException e) {
            log.debug("Instance already registered", e);
        } catch (Exception e) {
            log.warn("Error on jmx registration", e);
        }
    }
}

From source file:JDBCPool.dbcp.demo.sourcecode.BaseGenericObjectPool.java

/**
 * Unregisters this pool's MBean./* w ww  .jav  a 2s.co m*/
 */
final void jmxUnregister() {
    if (oname != null) {
        try {
            ManagementFactory.getPlatformMBeanServer().unregisterMBean(oname);
        } catch (MBeanRegistrationException e) {
            swallowException(e);
        } catch (InstanceNotFoundException e) {
            swallowException(e);
        }
    }
}

From source file:org.red5.server.stream.ClientBroadcastStream.java

protected void unregisterJMX() {
    if (registerJMX) {
        if (StringUtils.isNotEmpty(publishedName) && !"false".equals(publishedName)) {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            try {
                ObjectName oName = new ObjectName(
                        String.format("org.red5.server:type=ClientBroadcastStream,scope=%s,publishedName=%s",
                                getScope().getName(), publishedName));
                mbs.unregisterMBean(oName);
            } catch (Exception e) {
                log.warn("Exception unregistering", e);
            }/* ww w  .  j  a  va  2  s  . c o  m*/
        }
    }
}

From source file:JDBCPool.dbcp.demo.sourcecode.BaseGenericObjectPool.java

/**
 * Registers the pool with the platform MBean server.
 * The registered name will be//from   ww  w  .  j a  v a2  s .c o  m
 * <code>jmxNameBase + jmxNamePrefix + i</code> where i is the least
 * integer greater than or equal to 1 such that the name is not already
 * registered. Swallows MBeanRegistrationException, NotCompliantMBeanException
 * returning null.
 *
 * @param config Pool configuration
 * @param jmxNameBase default base JMX name for this pool
 * @param jmxNamePrefix name prefix
 * @return registered ObjectName, null if registration fails
 */
private ObjectName jmxRegister(BaseObjectPoolConfig config, String jmxNameBase, String jmxNamePrefix) {
    ObjectName objectName = null;
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    int i = 1;
    boolean registered = false;
    String base = config.getJmxNameBase();
    if (base == null) {
        base = jmxNameBase;
    }
    while (!registered) {
        try {
            ObjectName objName;
            // Skip the numeric suffix for the first pool in case there is
            // only one so the names are cleaner.
            if (i == 1) {
                objName = new ObjectName(base + jmxNamePrefix);
            } else {
                objName = new ObjectName(base + jmxNamePrefix + i);
            }
            mbs.registerMBean(this, objName);
            objectName = objName;
            registered = true;
        } catch (MalformedObjectNameException e) {
            if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals(jmxNamePrefix)
                    && jmxNameBase.equals(base)) {
                // Shouldn't happen. Skip registration if it does.
                registered = true;
            } else {
                // Must be an invalid name. Use the defaults instead.
                jmxNamePrefix = BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX;
                base = jmxNameBase;
            }
        } catch (InstanceAlreadyExistsException e) {
            // Increment the index and try again
            i++;
        } catch (MBeanRegistrationException e) {
            // Shouldn't happen. Skip registration if it does.
            registered = true;
        } catch (NotCompliantMBeanException e) {
            // Shouldn't happen. Skip registration if it does.
            registered = true;
        }
    }
    return objectName;
}

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

protected void unregisterJMX() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    if (oName != null && mbs.isRegistered(oName)) {
        try {/*from   w w  w .j a  v a2s.c o m*/
            mbs.unregisterMBean(oName);
        } catch (Exception e) {
            log.warn("Exception unregistering: {}", oName, e);
        }
        oName = null;
    }
}

From source file:com.jagornet.dhcp.server.JagornetDhcpServer.java

/**
 * Register Log4J in JMX to allow dynamic configuration
 * of server logging using JMX client (e.g. jconsole).
 *///from  www . j  a v  a2 s.c o  m
@SuppressWarnings("unchecked")
public static void registerLog4jInJmx() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        // Create and Register the top level Log4J MBean
        HierarchyDynamicMBean hdm = new HierarchyDynamicMBean();
        ObjectName mbo = new ObjectName("log4j:hiearchy=default");
        mbs.registerMBean(hdm, mbo);

        // Add the root logger to the Hierarchy MBean
        org.apache.log4j.Logger rootLogger = org.apache.log4j.Logger.getRootLogger();
        hdm.addLoggerMBean(rootLogger.getName());

        // Get each logger from the Log4J Repository and add it to
        // the Hierarchy MBean created above.
        LoggerRepository r = LogManager.getLoggerRepository();
        Enumeration<Logger> loggers = r.getCurrentLoggers();
        if (loggers != null) {
            while (loggers.hasMoreElements()) {
                org.apache.log4j.Logger logger = (org.apache.log4j.Logger) loggers.nextElement();
                hdm.addLoggerMBean(logger.getName());
            }
        }
    } catch (Exception ex) {
        log.error("Failure registering Log4J in JMX: " + ex);
    }
}