Example usage for javax.management MBeanServer getAttribute

List of usage examples for javax.management MBeanServer getAttribute

Introduction

In this page you can find the example usage for javax.management MBeanServer getAttribute.

Prototype

public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;

Source Link

Usage

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

private void awaitInitialArtifactDeployment() throws JMException, InterruptedException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName objectName = new ObjectName(
            "org.eclipse.virgo.kernel:type=ArtifactModel,artifact-type=plan,name=org.eclipse.virgo.web.tomcat,version="
                    + CURRENT_VERSION + ",region=global");

    Object state = null;//from  w  w  w  . ja  v  a  2s .  c  om
    long startTime = System.currentTimeMillis();

    while (!"ACTIVE".equals(state)) {
        try {
            state = mBeanServer.getAttribute(objectName, "State");
            Thread.sleep(100);
        } catch (InstanceNotFoundException _) {
        }
        if (System.currentTimeMillis() - startTime > WEB_PLAN_DEPLOY_TIMEOUT) {
            throw new RuntimeException(
                    "Web plan did not start within " + (WEB_PLAN_DEPLOY_TIMEOUT / 1000) + " seconds.");
        }
    }
}

From source file:org.rhq.plugins.jbossas.JBossASDiscoveryComponent.java

@Nullable
private DiscoveredResourceDetails discoverJBossPcIsEmbeddedIn(ResourceDiscoveryContext context) {
    MBeanServer server = JBossMBeanUtility.getJBossMBeanServer();

    try {// ww  w  .ja v a 2s .  c  o  m
        String jnpAddress = null;
        String jnpPort = null;
        ObjectName namingObjectName = new ObjectName("jboss:service=Naming");
        Set namingSet = server.queryNames(namingObjectName, null);
        if (namingSet.iterator().hasNext()) {
            jnpAddress = (String) server.getAttribute(namingObjectName, "BindAddress");
            jnpPort = String.valueOf(server.getAttribute(namingObjectName, "Port"));
        }

        String bindAddress = null;
        ObjectName systemPropertiesObjectName = new ObjectName("jboss:name=SystemProperties,type=Service");
        Set systemPropertiesSet = server.queryNames(systemPropertiesObjectName, null);
        if (systemPropertiesSet.iterator().hasNext()) {
            bindAddress = (String) server.invoke(systemPropertiesObjectName, "get",
                    new Object[] { JBossProperties.BIND_ADDRESS }, new String[] { String.class.getName() });
        }
        if (bindAddress == null) {
            bindAddress = jnpAddress;
        }

        ObjectName configObjectName = new ObjectName("jboss.system:type=ServerConfig");
        Set set = server.queryNames(configObjectName, null);
        if (set.iterator().hasNext()) {
            // ServerConfig MBean found
            File homeDir = (File) server.getAttribute(configObjectName, "HomeDir");
            JBossInstallationInfo installInfo;
            try {
                installInfo = new JBossInstallationInfo(homeDir);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Failed to determine installation info for JBoss home dir [" + homeDir + "].", e);
            }
            File configDir = (File) server.getAttribute(configObjectName, "ServerHomeDir");

            //if (isEmbeddedInServer(configDir)) {
            //    return null; // abort - we are embedded, but we're inside the enterprise Server
            //}

            String configName = (String) server.getAttribute(configObjectName, "ServerName");
            String version = (String) server.getAttribute(configObjectName, "SpecificationVersion");

            Configuration pluginConfiguration = context.getDefaultPluginConfiguration();

            // Set the connection type (used by JMX plugin to connect to the MBean server).
            pluginConfiguration.put(new PropertySimple(JMXDiscoveryComponent.CONNECTION_TYPE,
                    InternalVMTypeDescriptor.class.getName()));

            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.JBOSS_HOME_DIR_CONFIG_PROP, homeDir));
            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_PATH_CONFIG_PROP, configDir));
            pluginConfiguration
                    .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_SET_CONFIG_PROP, configName));

            // Now set default values on any props that are still not set.
            setPluginConfigurationDefaults(pluginConfiguration);

            JBossProductType productType = installInfo.getProductType();
            String name = formatServerName(bindAddress, jnpPort, context.getSystemInformation().getHostname(),
                    configName, productType, isRhqServer(configDir));
            String description = productType.NAME + " server that the RHQ Plugin Container is running within";
            DiscoveredResourceDetails resource = new DiscoveredResourceDetails(context.getResourceType(),
                    configDir.getAbsolutePath(), name, version, description, pluginConfiguration, null);

            return resource;
        }
    } catch (Exception e) {
        // JBoss MBean doesn't exist - not a JBoss server.
        log.debug("Not detected to be embedded in a JBoss AS Server", e);
    }

    return null;
}

From source file:com.betfair.cougar.core.impl.jmx.HtmlAdaptorParser.java

private void appendMBean(MBeanServer server, ObjectName on, String attrName, String separator,
        StringBuilder buf) {/* w  w  w. jav  a  2s . c  o  m*/
    StringBuilder local = new StringBuilder();
    try {

        MBeanInfo info = server.getMBeanInfo(on);
        local.append(on.toString());
        MBeanAttributeInfo[] attr = info.getAttributes();
        for (int i = 0; i < attr.length; i++) {
            if ((attrName == null || attrName.equals(attr[i].getName())) && attr[i].isReadable()) {
                local.append(separator);
                local.append(attr[i].getName());
                local.append(separator);
                local.append(server.getAttribute(on, attr[i].getName()));
            }
        }
    } catch (Exception e) {
        LOGGER.debug("Unable to retrieve Bean information for bean " + on, e);
        return;
    }
    buf.append(local);
}

From source file:org.rhq.enterprise.gui.startup.StartupServlet.java

/**
 * Starts the embedded agent, but only if the embedded agent is installed and it is enabled.
 *
 * @throws ServletException if the agent is installed and enabled but failed to start
 *///from  w ww  .  j  ava  2  s.  c o m
private void startEmbeddedAgent() throws ServletException {
    // 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 = MBeanServerLocator.locateJBoss();

    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 = LookupUtil.getServerManager().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 ServletException("Failed to start the embedded Agent.", t);
        }
    } catch (ServletException 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:org.apache.openejb.server.cli.command.LocalJMXCommand.java

private void listMBeans() {
    final MBeanServer mBeanServer = LocalMBeanServer.get();

    final Set<ObjectName> names;
    try {/*from w  w  w  .  j a v a  2 s  .  com*/
        names = mBeanServer.queryNames(null, null);
    } catch (Exception e) {
        streamManager.writeErr(e);
        return;
    }

    final Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        streamManager.writeOut("Name: " + oname.toString());

        try {
            final MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mBeanServer.getAttribute(oname, "modelerType");
            }
            streamManager.writeOut("  + modelerType: " + code);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable()) {
                    continue;
                }

                final String attName = attrs[i].getName();
                if ("modelerType".equals(attName)) {
                    continue;
                }

                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mBeanServer.getAttribute(oname, attName);
                } catch (RuntimeMBeanException uoe) {
                    // ignored
                } catch (Throwable t) {
                    streamManager.writeErr(new Exception(t));
                    continue;
                }

                try {
                    String valueString = stringify(value);
                    streamManager.writeOut("  + " + attName + ": " + valueString);
                } catch (Throwable t) {
                    streamManager.writeErr(new Exception(t));
                }
            }
        } catch (Throwable t) {
            streamManager.writeErr(new Exception(t));
        }
        streamManager.writeOut("");
    }
}

From source file:org.hyperic.hq.plugin.weblogic.jmx.WeblogicDiscover.java

private void discoverInit(MBeanServer mServer) throws Exception {

    // only exists on the admin server
    final String scope = "*:Type=ApplicationConfig,*";

    for (Iterator it = mServer.queryNames(new ObjectName(scope), null).iterator(); it.hasNext();) {
        ObjectName oName = (ObjectName) it.next();
        if (this.domain == null) {
            this.domain = oName.getDomain();
        }//from w w w . j av a2 s.  c o m
        if (this.adminName == null) {
            this.adminName = oName.getKeyProperty("Location");
        }

        String name = oName.getKeyProperty("Name");

        // special case for console so we can control it
        if (name.equals("console")) {
            continue;
        }

        boolean isInternal = ((Boolean) mServer.getAttribute(oName, "InternalApp")).booleanValue();

        if (isInternal) {
            this.internalApps.put(name, Boolean.TRUE);
        }
    }
}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * Get a list of strings(scheme + host + port) that the specified connector is running on
 *
 * @param name/*  w  ww  .j  av a2 s. c  o  m*/
 * @return
 */
private ArrayList<String> getConnectorStrings(String name) {
    ArrayList<String> connectorStrings = new ArrayList<String>();

    try {
        MBeanServer mbeanServer = getServerForName(name);
        Set<ObjectName> objs = mbeanServer.queryNames(new ObjectName("*:type=Connector,*"), null);
        String hostname = InetAddress.getLocalHost().getHostName();
        InetAddress[] addresses = InetAddress.getAllByName(hostname);

        for (Iterator<ObjectName> i = objs.iterator(); i.hasNext();) {
            ObjectName obj = i.next();
            String scheme = mbeanServer.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            connectorStrings.add(scheme + "://localhost:" + port);
            logger.info("Adding: {}", scheme + "://localhost:" + port);
        }
    } catch (Exception e) {
    }

    return connectorStrings;
}

From source file:com.app.services.ExecutorServiceThread.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    try {/*w  w w . ja  v  a  2  s .c o m*/
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel
                .bind(new InetSocketAddress("0.0.0.0", Integer.parseInt(serverConfig.getServicesport())));
        serverSocketChannel.configureBlocking(false);
        this.executorServiceMap = (Hashtable) mbeanServer.getAttribute(new ObjectName(warDeployerName),
                "ExecutorServiceMap");
        this.urlClassLoaderMap = (Hashtable) mbeanServer.getAttribute(new ObjectName(warDeployerName),
                "UrlClassLoaderMap");
        this.deployDirectory = serverConfig.getDeploydirectory();
        //log.info("Nodesport=" + nodesport);
        this.nodesport = serverConfig.getNodesport().split(",");

    } catch (Exception e) {
        log.error("Error in creating server socket channel " + serverConfig.getServicesport(), e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }

    log.info("initialized");

}

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  w  ww . j  a  v a2  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:org.apache.hadoop.raid.TestBlockFixer.java

private void verifyMXBean(RaidNode cnode) throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanName = new ObjectName("hadoop:service=RaidNode,name=RaidNodeState");
    Long timeSinceLastSuccessfulFix = (Long) mbs.getAttribute(mxbeanName, "TimeSinceLastSuccessfulFix");
    assertNotNull(timeSinceLastSuccessfulFix);
    if (timeSinceLastSuccessfulFix == 0) {
        assertEquals("No files need to fix", 0, cnode.blockIntegrityMonitor.approximateNumRecoverableFiles);
    }/* w w w  .ja  va  2 s.c  om*/
    LOG.info("timeSinceLastSuccessfulFix:" + timeSinceLastSuccessfulFix + "\t"
            + "approximateNumRecoverableFiles:" + cnode.blockIntegrityMonitor.approximateNumRecoverableFiles
            + "\t" + "lastSuccessfulFixTime:" + cnode.blockIntegrityMonitor.lastSuccessfulFixTime);
}