Example usage for javax.management.remote JMXServiceURL JMXServiceURL

List of usage examples for javax.management.remote JMXServiceURL JMXServiceURL

Introduction

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

Prototype

public JMXServiceURL(String serviceURL) throws MalformedURLException 

Source Link

Document

Constructs a JMXServiceURL by parsing a Service URL string.

Usage

From source file:org.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator.java

/**
 * determines the jmxServiceUrl depending on jmxmp.
 * // ww  w.j a  va 2 s  .  c  o  m
 * @param jmxmp
 * @param hostName
 * @param port
 * @return
 * @throws MalformedURLException
 */
public JMXServiceURL getJmxServiceURL(Boolean jmxmp, String hostName, String port)
        throws MalformedURLException {
    if (jmxmp) {
        return new JMXServiceURL("service:jmx:jmxmp://" + hostName + ":" + port);
    }
    return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + hostName + ":" + port + "/jmxrmi");
}

From source file:org.wso2.carbon.analytics.common.jmx.agent.JmxAgentWebInterface.java

private JMXConnector getJmxConnector(String url, String userName, String password) throws IOException {
    JMXServiceURL jmxServiceURL = new JMXServiceURL(url);
    Map<String, String[]> map = new HashMap<String, String[]>(1);

    map.put(JmxConstant.JMX_REMOTE_CREDENTIALS_STR, new String[] { userName, password });
    return JMXConnectorFactory.connect(jmxServiceURL, map);
}

From source file:org.rhq.cassandra.ClusterInitService.java

private String getSchemaVersionForNode(String storageNode, int jmxPort) throws Exception {
    String url = this.getJMXConnectionURL(storageNode, jmxPort);
    JMXServiceURL serviceURL = new JMXServiceURL(url);
    Map<String, String> env = new HashMap<String, String>();
    JMXConnector connector = null;

    try {//from ww w. ja  v  a  2 s  .c  o  m
        connector = JMXConnectorFactory.connect(serviceURL, env);
        MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
        ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
        String attribute = "SchemaVersion";
        try {
            return (String) serverConnection.getAttribute(storageService, attribute);
        } catch (Exception e) {
            // It is ok to just catch and log exceptions here particularly in an integration
            // test environment where we could potentially try to do the JMX query before
            // Cassandra is fully initialized. We can query StorageService before the native
            // transport server is initialized which will result in Cassandra throwing a NPE.
            // We do not want propagate that exception because it is just a matter of waiting
            // for Cassandra to finish initializing.
            if (log.isDebugEnabled()) {
                log.debug("Failed to read attribute [" + attribute + "] from " + storageService, e);
            } else {
                log.info("Faied to read attribute [" + attribute + "] from " + storageService + ": "
                        + e.getMessage());
            }
        }
    } finally {
        if (connector != null) {
            connector.close();
        }
    }
    return null;
}

From source file:org.apache.camel.management.DefaultManagementAgent.java

protected void createJmxConnector(String host) throws IOException {
    ObjectHelper.notEmpty(serviceUrlPath, "serviceUrlPath");
    ObjectHelper.notNull(registryPort, "registryPort");

    try {/*from  w w  w.j a va 2s  . c om*/
        LocateRegistry.createRegistry(registryPort);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created JMXConnector RMI registry on port " + registryPort);
        }
    } catch (RemoteException ex) {
        // The registry may had been created, we could get the registry instead
    }

    // must start with leading slash
    String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
    // Create an RMI connector and start it
    final JMXServiceURL url;
    if (connectorPort > 0) {
        url = new JMXServiceURL("service:jmx:rmi://" + host + ":" + connectorPort + "/jndi/rmi://" + host + ":"
                + registryPort + path);
    } else {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

    if (executorService == null) {
        // we only need a single for the JMX connector
        executorService = camelContext.getExecutorServiceStrategy().newSingleThreadExecutor(this,
                "JMXConnector: " + url);
    }

    // execute the JMX connector
    executorService.execute(new Runnable() {
        public void run() {
            try {
                cs.start();
            } catch (IOException ioe) {
                LOG.warn("Could not start JMXConnector thread.", ioe);
            }
        }
    });

    LOG.info("JMX Connector thread started and listening at: " + url);
}

From source file:com.cisco.oss.foundation.message.HornetQMessagingFactory.java

private static void printHQVersion(final String host, final String port) {
    LOGGER.info("HornetQ version: {}", VersionLoader.getVersion().getVersionName());

    Runnable getVersionFromServer = new Runnable() {
        @Override/*from w w  w .  j  ava  2  s . c  o  m*/
        public void run() {
            try {

                // Step 9. Retrieve the ObjectName of the queue. This is used to identify the server resources to manage
                ObjectName on = ObjectNameBuilder.DEFAULT.getHornetQServerObjectName();

                // Step 10. Create JMX Connector to connect to the server's MBeanServer
                String url = MessageFormat.format("service:jmx:rmi://{0}/jndi/rmi://{0}:{1}/jmxrmi", host,
                        port == null ? "3900" : port);
                LOGGER.debug("HornetQ Server jmx url: {}", url);
                JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(url), new HashMap());

                // Step 11. Retrieve the MBeanServerConnection
                MBeanServerConnection mbsc = connector.getMBeanServerConnection();

                // Step 12. Create a JMSQueueControl proxy to manage the queue on the server
                JMSServerControl serverControl = MBeanServerInvocationHandler.newProxyInstance(mbsc, on,
                        JMSServerControl.class, false);

                String serverControlVersion = serverControl.getVersion();
                LOGGER.info("HornetQ Server version: {}", serverControlVersion);

            } catch (Exception e) {
                LOGGER.info("can't log server version. error is: {}", e.toString());
            }
        }
    };

    try {

        new Thread(getVersionFromServer).start();

    } catch (Exception e) {
        LOGGER.info("can't log server version. error is: {}", e.toString());
    }
}

From source file:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java

private String javaRegister(MonitoringMXBean mxBean, String serviceURL) throws MalformedObjectNameException,
        IOException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {
    serverInfo = new ServerInfo(mxBean, configuration);

    String strAppObjectName = Utility.getObjectName("Application", this.exposedObject);

    jurl = new JMXServiceURL(serviceURL);
    appObjectName = new ObjectName(strAppObjectName);

    jmxEnvironmentMap = null;//from  w  w  w .ja  va 2  s .c om

    int agentPort = configuration.getInt(FoundationMonitoringConstants.MX_PORT);
    if (!RMIRegistryManager.isRMIRegistryRunning(configuration, agentPort)) {
        RMIRegistryManager.startRMIRegistry(configuration, agentPort);
    } else {
        LOGGER.info("rmiregistry is already running on port " + agentPort);
    }

    String serviceName = serviceURL.substring(serviceURL.indexOf("jmxrmi/"));
    if (isServiceExported(configuration, serviceName)) {
        MonitoringClient client = new MonitoringClient(serviceURL, strAppObjectName);
        if (client.connect()) {
            client.disconnect();
        } else {
            jmxEnvironmentMap = Utility.prepareJmxEnvironmentMap();
            LOGGER.info("Found a stale entry for " + serviceName + " in rmiregistry , it will be overwritten");
        }
    }
    mbs = ManagementFactory.getPlatformMBeanServer();
    rmis = JMXConnectorServerFactory.newJMXConnectorServer(jurl, jmxEnvironmentMap, mbs);

    mbs.registerMBean(mxBean, appObjectName);
    registerComponentInfo();
    registerMonitoringConfiguration();
    registerServices();
    registerConnections();
    registerNotificationDetails();
    rmis.start();

    if (mxBean instanceof INotifier) {
        INotifier notifier = (INotifier) mxBean;
        notifier.setNotificationSender(serverInfo);
    }

    serverThread = new ServerRecoveryDaemon();
    serverThread.start();

    return strAppObjectName;
}

From source file:com.googlecode.jmxtrans.model.Server.java

@JsonIgnore
public JMXServiceURL getJmxServiceURL() throws IOException {
    if (this.pid != null) {
        return JMXServiceURLFactory.extractJMXServiceURLFromPid(this.pid);
    }/*from   w w  w .  j  a  va2  s . c o  m*/
    return new JMXServiceURL(getUrl());
}

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  ww .  j  a v  a2s .  com

        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.linkedin.databus2.core.container.netty.ServerContainer.java

protected void initializeContainerJmx() {

    if (_containerStaticConfig.getJmx().isRmiEnabled()) {
        try {/*w w w.j  a v a 2 s  .c o m*/
            JMXServiceURL jmxServiceUrl = new JMXServiceURL(
                    "service:jmx:rmi://" + _containerStaticConfig.getJmx().getJmxServiceHost() + ":"
                            + _containerStaticConfig.getJmx().getJmxServicePort() + "/jndi/rmi://"
                            + _containerStaticConfig.getJmx().getRmiRegistryHost() + ":"
                            + _containerStaticConfig.getJmx().getRmiRegistryPort() + "/jmxrmi"
                            + _containerStaticConfig.getJmx().getJmxServicePort());

            _jmxConnServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxServiceUrl, null,
                    getMbeanServer());
        } catch (Exception e) {
            LOG.warn("Unable to instantiate JMX server", e);
        }
    }
}

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

public static JMXConnector getMBeanConnector(Properties config) throws MalformedURLException, IOException {

    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    Map map = new HashMap();

    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);

    map.put(JMXConnector.CREDENTIALS, new String[] { user, pass });

    // required for Oracle AS
    String providerPackages = config.getProperty(PROP_JMX_PROVIDER_PKGS);
    if (providerPackages != null)
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, providerPackages);

    if (jmxUrl == null) {
        throw new MalformedURLException(PROP_JMX_URL + "==null");
    }/*from  ww w .  j  a v  a 2  s . co  m*/

    if (jmxUrl.startsWith(PTQL_PREFIX)) {
        jmxUrl = getUrlFromPid(jmxUrl.substring(PTQL_PREFIX.length()));
    }

    JMXServiceURL url = new JMXServiceURL(jmxUrl);

    String proto = url.getProtocol();
    if (proto.equals("t3") || proto.equals("t3s")) {
        //http://edocs.bea.com/wls/docs92/jmx/accessWLS.html
        //WebLogic support, requires:
        //cp $WLS_HOME/server/lib/wljmxclient.jar pdk/lib/
        //cp $WLS_HOME/server/lib/wlclient.jar pdk/lib/
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
        map.put(Context.SECURITY_PRINCIPAL, user);
        map.put(Context.SECURITY_CREDENTIALS, pass);
    }

    JMXConnector connector = JMXConnectorFactory.connect(url, map);
    if (log.isDebugEnabled()) {
        log.debug("created new JMXConnector url=" + url + ", classloader="
                + Thread.currentThread().getContextClassLoader());
    }
    return connector;
}