Example usage for javax.management.remote JMXServiceURL toString

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

Introduction

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

Prototype

String toString

To view the source code for javax.management.remote JMXServiceURL toString.

Click Source Link

Document

Cached result of #toString() .

Usage

From source file:dk.netarkivet.common.utils.JMXUtils.java

/**
 * Connects to the given (url-specified) service point,
 * sending the given credentials as login.
 * @param url The JMX service url of some JVM on some machine.
 * @param credentials a map with (at least) one entry, mapping
 * "jmx.remote.credentials" to a String array of length 2.
 * Its first item should be the user name.
 * Its second item should be the password.
 * @return An MBeanServerConnection representing the
 * connected session./* w ww . ja v  a  2  s. co m*/
 */
public static MBeanServerConnection getMBeanServerConnection(JMXServiceURL url,
        Map<String, String[]> credentials) {
    ArgumentNotValid.checkNotNull(url, "JMXServiceURL url");
    ArgumentNotValid.checkNotNull(credentials, "Map<String,String[]> credentials");
    try {
        ensureJndiInitialContext();
        return JMXConnectorFactory.connect(url, credentials).getMBeanServerConnection();
    } catch (IOException e) {
        throw new IOFailure("Could not connect to " + url.toString(), e);
    }
}

From source file:dk.netarkivet.common.management.MBeanConnectorCreator.java

/**
 * Registers an RMI connector to the local mbean server in a private RMI
 * registry, under the name "jmxrmi". The port for the registry is read from
 * settings, and the RMI port used for exposing the connector is also read
 * from settings. Access to the mbean server is restricted by the rules set
 * in the password file, likewise read from settings.
 *
 * @throws IOFailure on trouble exposing the server.
 *//*  w ww  .j a v  a2 s .  com*/
public static synchronized void exposeJMXMBeanServer() {
    try {
        if (!isExposed) {
            int jmxPort = Settings.getInt(CommonSettings.JMX_PORT);
            int rmiPort = Settings.getInt(CommonSettings.JMX_RMI_PORT);
            String passwordFile = Settings.get(CommonSettings.JMX_PASSWORD_FILE);

            // Create a private registry for the exposing the JMX connector.
            LocateRegistry.createRegistry(jmxPort);
            // Create a URL that signifies that we wish to use the local
            // registry created above, and listen for rmi callbacks on the
            // RMI port of this machine, exposing the mbeanserver with the
            // name "jmxrmi".
            String canonicalHostName = SystemUtils.getLocalHostName();
            JMXServiceURL url = new JMXServiceURL(MessageFormat.format(SERVICE_JMX_RMI_URL, canonicalHostName,
                    Integer.toString(rmiPort), Integer.toString(jmxPort)));
            // Insert the password file into environment used when creating
            // the connector server.
            Map<String, Serializable> env = new HashMap<String, Serializable>();
            env.put(ENVIRONMENT_PASSWORD_FILE_PROPERTY, passwordFile);
            // Register the connector to the local mbean server in this
            // registry under that URL, using the created environment
            // settings.
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            // Start the connector server.
            cs.start();
            isExposed = true;
            // Register the JMX server at the registry.
            MonitorRegistryClientFactory.getInstance().register(canonicalHostName,
                    Settings.getInt(CommonSettings.JMX_PORT), Settings.getInt(CommonSettings.JMX_RMI_PORT));

            if (log.isInfoEnabled()) {
                log.info("Registered mbean server in registry on port " + jmxPort + " communicating on port "
                        + rmiPort + " using password file '" + passwordFile + "'." + "\nService URL is "
                        + url.toString());
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Error creating and registering an" + " RMIConnector to the platform mbean server.",
                e);
    }
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Connect to JMX interface on the given host and port.
 *
 * @param handler  Implementation of {@link RepairStatusHandler} to process incoming
 *                 notifications//from w w w  . j  a  va2s  . c  om
 *                 of repair events.
 * @param host     hostname or ip address of Cassandra node
 * @param port     port number to use for JMX connection
 * @param username username to use for JMX authentication
 * @param password password to use for JMX authentication
 */
static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username,
        String password) throws ReaperException {
    ObjectName ssMbeanName;
    ObjectName cmMbeanName;
    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port));
        ssMbeanName = new ObjectName(SS_OBJECT_NAME);
        cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
    } catch (MalformedURLException | MalformedObjectNameException e) {
        LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port));
        throw new ReaperException("Failure during preparations for JMX connection", e);
    }
    try {
        Map<String, Object> env = new HashMap<String, Object>();
        if (username != null && password != null) {
            String[] creds = { username, password };
            env.put(JMXConnector.CREDENTIALS, creds);
        }
        JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection();
        Object ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class);
        String cassandraVersion = ((StorageServiceMBean) ssProxy).getReleaseVersion();
        if (cassandraVersion.startsWith("2.0") || cassandraVersion.startsWith("1.")) {
            ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean20.class);
        }

        CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName,
                CompactionManagerMBean.class);
        JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn,
                cmProxy);
        // registering a listener throws bunch of exceptions, so we do it here rather than in the
        // constructor
        mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null);
        LOG.debug("JMX connection to {} properly connected: {}", host, jmxUrl.toString());
        return proxy;
    } catch (IOException | InstanceNotFoundException e) {
        LOG.error("Failed to establish JMX connection to {}:{}", host, port);
        throw new ReaperException("Failure when establishing JMX connection", e);
    }
}

From source file:org.jbosson.plugins.amq.ArtemisServerComponent.java

protected void internalStart() throws Exception {
    Configuration pluginConfig = context.getPluginConfiguration();
    String connectionTypeDescriptorClassName = pluginConfig.getSimple(JMXDiscoveryComponent.CONNECTION_TYPE)
            .getStringValue();/*  w  ww.  j  a  v  a2  s  .c om*/
    if (JMXDiscoveryComponent.PARENT_TYPE.equals(connectionTypeDescriptorClassName)) {
        // Our parent is itself a JMX component, so just reuse its connection.
        this.connection = ((JMXComponent) context.getParentResourceComponent()).getEmsConnection();
        this.connectionProvider = this.connection.getConnectionProvider();
    } else {
        final File tempDir = this.context.getTemporaryDirectory();
        try {
            this.connectionProvider = ConnectionProviderFactory.createConnectionProvider(pluginConfig,
                    this.context.getNativeProcess(), tempDir);
        } catch (RuntimeException e) {
            // check if Attach API failed, since this resource may have been discovered using jvmstat API
            // avoid loading AttachNotSupportedException class, since its optional
            if (e.getCause() != null && e.getCause().getClass().getName()
                    .equals(ArtemisServerDiscoveryComponent.ATTACH_NOT_SUPPORTED_EXCEPTION_CLASS_NAME)) {

                // create a connection provider using JvmStatUtility
                final Class<?> connectionTypeDescriptorClass;
                connectionTypeDescriptorClass = Class.forName(connectionTypeDescriptorClassName);
                ConnectionTypeDescriptor connectionType = (ConnectionTypeDescriptor) connectionTypeDescriptorClass
                        .newInstance();

                // create connection provider settings
                ConnectionSettings settings = new ConnectionSettings();
                if (!(connectionType instanceof J2SE5ConnectionTypeDescriptor)) {
                    throw new Exception(
                            "Unsupported connection type descriptor " + connectionTypeDescriptorClass);
                }
                settings.setConnectionType(connectionType);

                // get service URL using jvmstat
                final JMXServiceURL jmxServiceURL = JvmStatUtility
                        .extractJMXServiceURL(context.getNativeProcess());
                if (jmxServiceURL == null) {
                    throw new Exception("Failed to get JMX service URL using jvmstat");
                }
                settings.setServerUrl(jmxServiceURL.toString());

                settings.getControlProperties().setProperty(ConnectionFactory.COPY_JARS_TO_TEMP,
                        String.valueOf(Boolean.TRUE));
                settings.getControlProperties().setProperty(ConnectionFactory.JAR_TEMP_DIR,
                        tempDir.getAbsolutePath());

                ConnectionFactory connectionFactory = new ConnectionFactory();
                connectionFactory.discoverServerClasses(settings);

                connectionProvider = connectionFactory.getConnectionProvider(settings);

            } else {
                // re-throw
                throw e;
            }
        }
        this.connection = this.connectionProvider.connect();
        this.connection.loadSynchronous(false);
    }
}