Example usage for javax.management.remote JMXConnector getMBeanServerConnection

List of usage examples for javax.management.remote JMXConnector getMBeanServerConnection

Introduction

In this page you can find the example usage for javax.management.remote JMXConnector getMBeanServerConnection.

Prototype

public MBeanServerConnection getMBeanServerConnection() throws IOException;

Source Link

Document

Returns an MBeanServerConnection object representing a remote MBean server.

Usage

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;
    try {//from w ww. j a  v  a2  s  .c  o m
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

From source file:org.hyperic.hq.plugin.weblogic.WeblogicServiceControlPlugin.java

protected void invokeMethod(ControlPlugin plugin, String objectName, String action, String[] args) {
    log.debug("invoking " + action + " " + MBeanUtil.anyToString(args));
    JMXConnector jmxConnector;
    try {/*from  www. jav a2 s . co  m*/
        jmxConnector = WeblogicUtil.getManagedServerConnection(plugin.getConfig().toProperties());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
        return;
    }
    try {
        String result = null;
        Object obj = invoke(jmxConnector.getMBeanServerConnection(), objectName, action, args, new String[0]);
        if (obj != null) {
            result = MBeanUtil.anyToString(obj);
        }
        log.debug(objectName + "." + action + "() returned: " + obj);
        plugin.setResult(RESULT_SUCCESS);
        if (result != null) {
            plugin.setMessage(result);
        }
    } catch (PluginException e) {
        log.error(e.getMessage(), e);
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        // anything not explicitly thrown by invoke
        // needs to have the full stack trace logged for debugging.
        plugin.setMessage(e.getMessage());
        plugin.setResult(RESULT_FAILURE);
    } finally {
        try {
            jmxConnector.close();
        } catch (IOException e) {
            log.warn("Error closing remote JMX connection", e);
        }
    }
}

From source file:org.talend.esb.monitoring.hq.DynamicMxFieldMeasurementPlugin.java

/**
 * Looks up for a ObjectName based on a given pattern ObjectName.
 * /*from   www  .j  a v a 2s. c om*/
 * @param patternObjectName
 *            a pattern object name
 * @param connectionProps
 *            connection properties
 * @return Returns the found ObjectName, otherwise throws an exception
 * @throws MetricNotFoundException
 *             is thrown when no metric was found using specified pattern
 * @throws MetricUnreachableException
 *             is thrown when it is impossible to find the object name
 *             because of connection problems
 * @throws MetricInvalidException
 *             is thrown if patter format is wrong
 * @throws PluginException
 *             if some unexpected problem happened
 */
private String findObjectName(final String patternObjectName, final Properties connectionProps)
        throws MetricNotFoundException, MetricUnreachableException, MetricInvalidException, PluginException {

    ObjectName patternOn;
    try {
        patternOn = new ObjectName(patternObjectName);
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException(MSG_ERR_MALFORMED, e);
    }

    JMXConnector jmxConnector = null;
    try {
        jmxConnector = MxUtil.getCachedMBeanConnector(connectionProps);
        final MBeanServerConnection conn = jmxConnector.getMBeanServerConnection();
        final Set<ObjectName> result = conn.queryNames(patternOn, null);

        if (result.iterator().hasNext()) {
            return result.iterator().next().getCanonicalName();
        }
    } catch (IOException e) {
        log.debug(MSG_ERR_CONNECT, e);
        throw new MetricUnreachableException(MSG_ERR_CONNECT, e);
    } catch (Exception e) {
        log.debug(MSG_ERR_UNEXPECTED, e);
        throw new PluginException(MSG_ERR_UNEXPECTED, e);
    } finally {
        // it's null-proof
        MxUtil.close(jmxConnector);
    }

    throw new MetricNotFoundException(MSG_ERR_NOTFOUND);
}

From source file:org.apache.hadoop.test.system.AbstractDaemonClient.java

/**
 * Create connection with the remove JMX server at given host and port
 * @param host name of the remote JMX server host
 * @param port port number of the remote JXM server host
 * @return instance of MBeanServerConnection or <code>null</code> if one
 *    hasn't been established//  w  w w .  ja  va 2  s .  c  o  m
 * @throws IOException in case of comminication errors
 */
protected MBeanServerConnection establishJmxConnection(String host, int port) throws IOException {
    if (connection != null)
        return connection;
    String urlPattern = null;
    try {
        urlPattern = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        JMXServiceURL url = new JMXServiceURL(urlPattern);
        JMXConnector connector = JMXConnectorFactory.connect(url, null);
        connection = connector.getMBeanServerConnection();
    } catch (java.net.MalformedURLException badURLExc) {
        LOG.debug("bad url: " + urlPattern, badURLExc);
        throw new IOException(badURLExc);
    }
    return connection;
}

From source file:uk.co.gidley.jmxmonitor.monitoring.MonitoringGroup.java

/**
 * Initialise the monitor. If possible we start the JMX connection now. If not we create a placeholder.
 *
 * @param monitorUrlKey//from w ww .j  av  a2  s.co m
 * @param monitorsConfiguration
 * @throws MalformedObjectNameException
 * @throws MalformedURLException
 */
private void initialiseMonitorUrl(String monitorUrlKey, CompositeConfiguration monitorsConfiguration)
        throws MalformedObjectNameException, MalformedURLException {
    logger.debug("Initialising Monitor Connection {}", monitorUrlKey);

    String url = monitorsConfiguration.getString(ThreadManager.PROPERTY_PREFIX + monitorUrlKey + URL);
    try {
        // Create JMX connection
        JMXServiceURL serviceUrl = new JMXServiceURL(url);
        JMXConnector jmxc = JMXConnectorFactory.connect(serviceUrl, null);
        logger.debug("JMX connection made {}", jmxc);
        MonitoringGroup.MonitorUrlHolder monitorUrlHolder = monitorUrlHolders.get(monitorUrlKey);
        monitorUrlHolder.setmBeanServerConnection(jmxc.getMBeanServerConnection());
        monitorUrlHolder.getMonitors().clear();

        // Parse monitors inside this
        List<String> loadedMonitors = new ArrayList<String>();
        Iterator<String> monitorKeys = monitorsConfiguration
                .getKeys(ThreadManager.PROPERTY_PREFIX + monitorUrlKey);
        while (monitorKeys.hasNext()) {
            String key = monitorKeys.next();
            if (!key.endsWith(URL)) {
                String monitorName = key.substring(
                        ThreadManager.PROPERTY_PREFIX.length() + monitorUrlKey.length() + 1,
                        key.lastIndexOf("."));
                // Only load each on once (there will be n keys)
                if (!loadedMonitors.contains(monitorName)) {
                    constructMonitor(monitorUrlKey, monitorsConfiguration, monitorUrlHolder, monitorName);
                    loadedMonitors.add(monitorName);
                }
            }
        }
    } catch (IOException e) {
        if (e instanceof MalformedURLException) {
            throw (MalformedURLException) e;
        }
        logger.warn("Unable to connect to {}, {}", monitorUrlKey, e);
    }
}

From source file:org.rhq.plugins.jmx.JMXDiscoveryComponent.java

protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext context, ProcessInfo process,
        JMXServiceURL jmxServiceURL, Integer jmxRemotingPort) {
    JvmResourceKey key;/*from  w ww . j  ava2  s  .  c o m*/
    String mainClassName = getJavaMainClassName(process);
    String keyString = getSystemPropertyValue(process, SYSPROP_RHQ_RESOURCE_KEY);
    if (keyString != null && !keyString.equals("")) {
        log.debug("Using explicitly specified Resource key: [" + keyString + "]...");
        key = JvmResourceKey.fromExplicitValue(mainClassName, keyString);
    } else {
        if (jmxRemotingPort != null) {
            log.debug("Using JMX remoting port [" + jmxRemotingPort + "] as Resource key...");
            key = JvmResourceKey.fromJmxRemotingPort(mainClassName, jmxRemotingPort);
        } else {
            log.debug("Process [" + process.getPid() + "] with command line ["
                    + Arrays.asList(process.getCommandLine())
                    + "] cannot be discovered, because it does not specify either of the following system properties: "
                    + "-D" + SYSPROP_JMXREMOTE_PORT + "=12345, -D" + SYSPROP_RHQ_RESOURCE_KEY + "=UNIQUE_KEY");
            return null;
        }
    }

    String name = buildResourceName(key);

    String version;
    try {
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
        MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
        RuntimeMXBean runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConnection,
                ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
        version = runtimeMXBean.getSystemProperties().get(SYSPROP_JAVA_VERSION);
        if (version == null) {
            throw new IllegalStateException("System property [" + SYSPROP_JAVA_VERSION + "] is not defined.");
        }
    } catch (Exception e) {
        log.error("Failed to determine JVM version for process [" + process.getPid() + "] with command line ["
                + Arrays.asList(process.getCommandLine()) + "].", e);
        version = null;
    }

    String description = "JVM, monitored via "
            + ((jmxRemotingPort != null) ? "JMX Remoting" : "Sun JVM Attach API");

    Configuration pluginConfig = context.getDefaultPluginConfiguration();
    pluginConfig.put(new PropertySimple(CONNECTION_TYPE, J2SE5ConnectionTypeDescriptor.class.getName()));
    if (jmxRemotingPort != null) {
        pluginConfig.put(new PropertySimple(CONNECTOR_ADDRESS_CONFIG_PROPERTY, jmxServiceURL));
    }

    return new DiscoveredResourceDetails(context.getResourceType(), key.toString(), name, version, description,
            pluginConfig, process);
}

From source file:org.rhq.plugins.jmx.JMXDiscoveryComponent.java

@Override
public ResourceUpgradeReport upgrade(ResourceUpgradeContext inventoriedResource) {
    JvmResourceKey oldKey = JvmResourceKey.valueOf(inventoriedResource.getResourceKey());
    JvmResourceKey.Type oldKeyType = oldKey.getType();
    if (oldKeyType == JvmResourceKey.Type.Legacy || oldKeyType == JvmResourceKey.Type.JmxRemotingPort) {
        if (!inventoriedResource.getSystemInformation().isNative()) {
            log.warn("Cannot attempt to upgrade Resource key [" + inventoriedResource.getResourceKey()
                    + "] of JVM Resource, because this Agent is not running with native system info support (i.e. SIGAR).");
            return null;
        }/*from  w w  w  .  j  a va  2 s  . co  m*/

        Configuration pluginConfig = inventoriedResource.getPluginConfiguration();
        String connectorAddress = pluginConfig.getSimpleValue(CONNECTOR_ADDRESS_CONFIG_PROPERTY, null);
        JMXServiceURL jmxServiceURL;
        try {
            jmxServiceURL = new JMXServiceURL(connectorAddress);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Failed to parse connector address: " + connectorAddress, e);
        }

        Long pid;
        try {
            JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
            MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
            RuntimeMXBean runtimeMXBean = ManagementFactory.newPlatformMXBeanProxy(mbeanServerConnection,
                    ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
            pid = getJvmPid(runtimeMXBean);
            if (pid == null) {
                throw new RuntimeException("Failed to determine JVM pid by parsing JVM name.");
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to determine JVM pid.", e);
        }

        List<ProcessInfo> processes = inventoriedResource.getSystemInformation()
                .getProcesses("process|pid|match=" + pid);
        if (processes.size() != 1) {
            throw new IllegalStateException("Failed to find process with PID [" + pid + "].");
        }
        ProcessInfo process = processes.get(0);
        String mainClassName = getJavaMainClassName(process);
        String explicitKeyValue = getSystemPropertyValue(process, SYSPROP_RHQ_RESOURCE_KEY);
        if (oldKeyType == JvmResourceKey.Type.Legacy || explicitKeyValue != null) {
            // We need to upgrade the key.
            JvmResourceKey newKey;
            if (explicitKeyValue != null) {
                newKey = JvmResourceKey.fromExplicitValue(mainClassName, explicitKeyValue);
            } else {
                newKey = JvmResourceKey.fromJmxRemotingPort(mainClassName, oldKey.getJmxRemotingPort());
            }

            ResourceUpgradeReport resourceUpgradeReport = new ResourceUpgradeReport();
            resourceUpgradeReport.setNewResourceKey(newKey.toString());
            return resourceUpgradeReport;
        }
    }

    return null;
}

From source file:com.mustardgrain.solr.SolrClient.java

private static Runnable getStatsRunner(final WeakReference<SolrClient> lbRef) {
    return new Runnable() {

        @Override/*from ww w. j  a  va 2  s  .c  o m*/
        public void run() {
            SolrClient lb = lbRef.get();
            if (lb != null && lb.serverStats != null && LOG.isInfoEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("server responses over past ");
                sb.append(TimeUnit.MILLISECONDS.toMinutes(lb.statsInterval));
                sb.append(" mins (good/timeout/zero found) and cache hit ratio: ");
                boolean appendComma = false;

                for (Map.Entry<String, SolrStats> entry : lb.serverStats.entrySet()) {
                    if (appendComma)
                        sb.append(", ");

                    String server = entry.getKey();
                    SolrStats stats = entry.getValue();
                    String hitRatio = getHitRatio(server);

                    sb.append(server);
                    sb.append(": ");
                    sb.append(stats.getSuccesses());
                    sb.append("/");
                    sb.append(stats.getReadTimeouts());
                    sb.append("/");
                    sb.append(stats.getEmptyResults());
                    sb.append(" ");
                    sb.append(hitRatio);

                    appendComma = true;

                    stats.reset(); // Reset the counters once printed
                }

                LOG.info(sb);
            }
        }

        /**
         * Determines the hit ratio for the query result cache by calling
         * the SolrServer via JMX and reading its MBean containing that
         * information.
         * @param server Server from which to pull information
         * @return String form of hit ratio (either "n/a" or "xx%")
         */

        private String getHitRatio(String server) {
            String hitRatio = "n/a";
            JMXConnector jmxc = null;

            try {
                URL url = new URL(server);
                String domain = url.getPath();

                if (domain.startsWith("/"))
                    domain = domain.substring(1);

                ObjectName name = new ObjectName(
                        domain + ":id=org.apache.solr.search.LRUCache,type=queryResultCache");
                JMXServiceURL jmxUrl = new JMXServiceURL(
                        "service:jmx:rmi:///jndi/rmi://" + url.getHost() + ":7199/jmxrmi");
                jmxc = JMXConnectorFactory.connect(jmxUrl, null);
                MBeanServerConnection con = jmxc.getMBeanServerConnection();

                Object result = con.getAttribute(name, "hitratio");
                hitRatio = (int) (Float.parseFloat(String.valueOf(result)) * 100.0f) + "%";
            } catch (Exception e) {
                LOG.error(getNestedErrorMessages(e));
            } finally {
                if (jmxc != null) {
                    try {
                        jmxc.close();
                    } catch (Exception e) {
                        LOG.error(getNestedErrorMessages(e));
                    }
                }
            }

            return hitRatio;
        }

    };
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

@Override
public MBeanServerConnection getLocalMBeanServerConnection(String connectionName)
        throws ConnectException, NoLocalJmxConnectionException {
    JMXConnector connector = getLocalJmxConnector(connectionName);

    try {/*from ww w. j  ava 2  s .c o  m*/
        return connector.getMBeanServerConnection();
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }
}

From source file:org.hyperic.hq.product.jmx.MxServerDetector.java

protected List discoverServices(ConfigResponse serverConfig) throws PluginException {
    log.debug("[discoverServices] serverConfig=" + serverConfig);

    JMXConnector connector = null;
    MBeanServerConnection mServer;

    try {//from ww w  . j a va  2s. com
        connector = MxUtil.getCachedMBeanConnector(serverConfig.toProperties());
        mServer = connector.getMBeanServerConnection();
    } catch (Exception e) {
        MxUtil.close(connector);
        throw new PluginException(e.getMessage(), e);
    }

    try {
        return discoverMxServices(mServer, serverConfig);
    } finally {
        MxUtil.close(connector);
    }
}