Example usage for javax.rmi.ssl SslRMIClientSocketFactory SslRMIClientSocketFactory

List of usage examples for javax.rmi.ssl SslRMIClientSocketFactory SslRMIClientSocketFactory

Introduction

In this page you can find the example usage for javax.rmi.ssl SslRMIClientSocketFactory SslRMIClientSocketFactory.

Prototype

public SslRMIClientSocketFactory() 

Source Link

Document

Creates a new SslRMIClientSocketFactory.

Usage

From source file:org.apache.geode.tools.pulse.internal.data.JMXDataUpdater.java

/**
 * Get the jmx connection/*from www . j  a  v  a  2  s . co  m*/
 */
public JMXConnector connect(String username, String password) {
    // Reference to repository
    Repository repository = Repository.get();
    try {

        String jmxSerURL = "";

        logger.info("{}:{}", resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE"),
                repository.getJmxUseLocator());

        if (repository.getJmxUseLocator()) {
            JmxManagerInfo jmxManagerInfo = getManagerInfoFromLocator(repository);

            if (jmxManagerInfo.port == 0) {
                logger.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
            } else {
                logger.info("{}: {}={} & {}={}, {}", resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER"),
                        resourceBundle.getString("LOG_MSG_HOST"), jmxManagerInfo.host,
                        resourceBundle.getString("LOG_MSG_PORT"), jmxManagerInfo.port,
                        (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));

                jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host, String.valueOf(jmxManagerInfo.port));
            }
        } else {
            logger.info("{}={} & {}={}", resourceBundle.getString("LOG_MSG_HOST"), this.serverName,
                    resourceBundle.getString("LOG_MSG_PORT"), this.port);
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotBlank(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);
            String[] creds = { username, password };
            Map<String, Object> env = new HashMap<String, Object>();
            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }
            logger.info("Connecting to jmxURL : {}", jmxSerURL);
            this.conn = JMXConnectorFactory.connect(url, env);
            this.mbs = this.conn.getMBeanServerConnection();
            cluster.setConnectedFlag(true);
        }
    } catch (Exception e) {
        cluster.setConnectedFlag(false);
        cluster.setConnectionErrorMsg(e.getMessage());
        logger.fatal(e.getMessage(), e);
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                logger.fatal(e1.getMessage(), e1);
            }
            this.conn = null;
        }
    }
    return this.conn;
}

From source file:org.apache.cassandra.tools.NodeProbe.java

private RMIClientSocketFactory getRMIClientSocketFactory() throws IOException {
    if (Boolean.parseBoolean(System.getProperty("ssl.enable")))
        return new SslRMIClientSocketFactory();
    else//from   ww w .ja v  a 2s . co  m
        return RMISocketFactory.getDefaultSocketFactory();
}

From source file:org.apereo.portal.jmx.JavaManagementServerBean.java

/**
 * Generates the environment Map for the JMX server based on system properties
 * @return A non-null Map of environment settings for the JMX server.
 *///from w  ww .j  a  v a 2s. co  m
protected Map<String, Object> getJmxServerEnvironment() {
    final Map<String, Object> jmxEnv = new HashMap<String, Object>();

    //SSL Options
    final String enableSSL = System.getProperty(JMX_SSL_PROPERTY);
    if (Boolean.getBoolean(enableSSL)) {
        SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
        jmxEnv.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);

        SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
        jmxEnv.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
    }

    //Password file options
    final String passwordFile = System.getProperty(JMX_PASSWORD_FILE_PROPERTY);
    if (passwordFile != null) {
        jmxEnv.put(JMX_REMOTE_X_PASSWORD_FILE, passwordFile);
    }

    //Access file options
    final String accessFile = System.getProperty(JMX_ACCESS_FILE_PROPERTY);
    if (accessFile != null) {
        jmxEnv.put(JMX_REMOTE_X_ACCESS_FILE, accessFile);
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Configured JMX Server Environment = '" + jmxEnv + "'");
    }

    return jmxEnv;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.data.JMXDataUpdater.java

private JMXConnector getJMXConnection() {
    JMXConnector connection = null;
    // Reference to repository
    Repository repository = Repository.get();
    try {/* w  w w.  j  av a  2 s .  c om*/

        String jmxSerURL = "";

        if (LOGGER.infoEnabled()) {
            LOGGER.info(resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE") + ":"
                    + repository.getJmxUseLocator());
        }

        if (repository.getJmxUseLocator()) {

            String locatorHost = repository.getJmxHost();
            int locatorPort = Integer.parseInt(repository.getJmxPort());

            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + locatorHost + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + locatorPort);
            }

            InetAddress inetAddr = InetAddress.getByName(locatorHost);

            if ((inetAddr instanceof Inet4Address) || (inetAddr instanceof Inet6Address)) {

                if (inetAddr instanceof Inet4Address) {
                    // Locator has IPv4 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV4_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                } else {
                    // Locator has IPv6 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV6_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                }

                JmxManagerInfo jmxManagerInfo = JmxManagerFinder.askLocatorForJmxManager(inetAddr, locatorPort,
                        15000, repository.isUseSSLLocator());

                if (jmxManagerInfo.port == 0) {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
                    }
                } else {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER") + " : "
                                + resourceBundle.getString("LOG_MSG_HOST") + " : " + jmxManagerInfo.host + " & "
                                + resourceBundle.getString("LOG_MSG_PORT") + " : " + jmxManagerInfo.port
                                + (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                        : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));
                    }

                    jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host,
                            String.valueOf(jmxManagerInfo.port));
                }

            } /*
               * else if (inetAddr instanceof Inet6Address) { // Locator has IPv6
               * Address if(LOGGER.infoEnabled()){
               * LOGGER.info(resourceBundle.getString
               * ("LOG_MSG_LOCATOR_IPV6_ADDRESS")); } // update message to display
               * on UI cluster.setConnectionErrorMsg(resourceBundle.getString(
               * "LOG_MSG_JMX_CONNECTION_IPv6_ADDRESS"));
               * 
               * }
               */else {
                // Locator has Invalid locator Address
                if (LOGGER.infoEnabled()) {
                    LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_BAD_ADDRESS"));
                }
                // update message to display on UI
                cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_BAD_ADDRESS"));

            }

        } else {
            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + this.serverName + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + this.port);
            }
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);

            // String[] creds = {"controlRole", "R&D"};
            String[] creds = { this.userName, this.userPassword };
            Map<String, Object> env = new HashMap<String, Object>();

            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }

            connection = JMXConnectorFactory.connect(url, env);

            // Register Pulse URL if not already present in the JMX Manager
            registerPulseUrlToManager(connection);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            // update message to display on UI
            cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_UNKNOWN_HOST"));
        }

        // write errors
        StringWriter swBuffer = new StringWriter();
        PrintWriter prtWriter = new PrintWriter(swBuffer);
        e.printStackTrace(prtWriter);
        LOGGER.severe("Exception Details : " + swBuffer.toString() + "\n");
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                LOGGER.severe("Error closing JMX connection " + swBuffer.toString() + "\n");
            }
            this.conn = null;
        }
    }

    return connection;
}

From source file:org.red5.server.jmx.JMXAgent.java

public void init() {
    //environmental var holder
    HashMap env = null;/*from  www .j a  v a2s. c o  m*/
    if (enableHtmlAdapter) {
        // setup the adapter
        try {
            //instance an html adaptor
            int port = htmlAdapterPort == null ? 8082 : Integer.valueOf(htmlAdapterPort);
            html = new HtmlAdaptorServer(port);
            ObjectName htmlName = new ObjectName(
                    JMXFactory.getDefaultDomain() + ":type=HtmlAdaptorServer,port=" + port);
            log.debug("Created HTML adaptor on port: " + port);
            //add the adaptor to the server
            mbs.registerMBean(html, htmlName);
            //start the adaptor
            html.start();
            log.info("JMX HTML connector server successfully started");

        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (HTML adapter)", e);
        }
    } else {
        log.info("JMX HTML adapter was not enabled");
    }
    if (enableRmiAdapter) {
        // Create an RMI connector server
        log.debug("Create an RMI connector server");
        try {

            Registry r = null;
            try {
                //lookup the registry
                r = LocateRegistry.getRegistry(Integer.valueOf(rmiAdapterPort));
                //ensure we are not already registered with the registry
                for (String regName : r.list()) {
                    if (regName.equals("red5")) {
                        //unbind connector from rmi registry
                        r.unbind("red5");
                    }
                }
            } catch (RemoteException re) {
                log.info("RMI Registry server was not found on port " + rmiAdapterPort);
                //if we didnt find the registry and the user wants it created
                if (startRegistry) {
                    log.info("Starting an internal RMI registry");
                    // create registry for rmi port 9999
                    r = LocateRegistry.createRegistry(Integer.valueOf(rmiAdapterPort));
                }
            }
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + rmiAdapterPort + "/red5");
            //if SSL is requested to secure rmi connections
            if (enableSsl) {
                // Environment map
                log.debug("Initialize the environment map");
                env = new HashMap();
                // Provide SSL-based RMI socket factories
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            }

            //if authentication is requested
            if (StringUtils.isNotBlank(remoteAccessProperties)) {
                //if ssl is not used this will be null
                if (null == env) {
                    env = new HashMap();
                }
                //check the existance of the files
                //in the war version the full path is needed
                File file = new File(remoteAccessProperties);
                if (!file.exists()) {
                    log.debug("Access file was not found on path, will prepend config_root");
                    //pre-pend the system property set in war startup
                    remoteAccessProperties = System.getProperty("red5.config_root") + '/'
                            + remoteAccessProperties;
                    remotePasswordProperties = System.getProperty("red5.config_root") + '/'
                            + remotePasswordProperties;
                }
                env.put("jmx.remote.x.access.file", remoteAccessProperties);
                env.put("jmx.remote.x.password.file", remotePasswordProperties);
            }

            // create the connector server
            cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            // add a listener for shutdown
            cs.addNotificationListener(this, null, null);
            // Start the RMI connector server
            log.debug("Start the RMI connector server");
            cs.start();
            log.info("JMX RMI connector server successfully started");
        } catch (ConnectException e) {
            log.warn("Could not establish RMI connection to port " + rmiAdapterPort
                    + ", please make sure \"rmiregistry\" is running and configured to listen on this port.");
        } catch (IOException e) {
            String errMsg = e.getMessage();
            if (errMsg.indexOf("NameAlreadyBoundException") != -1) {
                log.error("JMX connector (red5) already registered, you will need to restart your rmiregistry");
            } else {
                log.error("{}", e);
            }
        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (RMI connector)", e);
        }
    } else {
        log.info("JMX RMI adapter was not enabled");
    }
}

From source file:org.ut.biolab.medsavant.MedSavantClient.java

public static void initializeRegistry(String serverAddress, String serverPort)
        throws RemoteException, NotBoundException, NoRouteToHostException, ConnectIOException {

    if (initialized) {
        return;//from w  w  w  . j a va2 s .c  o m
    }

    int port = (new Integer(serverPort)).intValue();

    Registry registry;

    LOG.debug("Connecting to MedSavantServerEngine @ " + serverAddress + ":" + serverPort + "...");

    try {
        registry = LocateRegistry.getRegistry(serverAddress, port, new SslRMIClientSocketFactory());
        LOG.debug("Retrieving adapters...");
        setAdaptersFromRegistry(registry);
        LOG.info("Connected with SSL/TLS Encryption");
    } catch (ConnectIOException ex) {
        if (ex.getCause() instanceof SSLHandshakeException) {
            registry = LocateRegistry.getRegistry(serverAddress, port);
            LOG.debug("Retrieving adapters...");
            setAdaptersFromRegistry(registry);
            LOG.info("Connected without SSL/TLS encryption");
        }
    }
    LOG.debug("Done");

}

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

/**
 * Starts the JMX connector for the server.
 *//* ww w .  j av a2s .  c om*/
protected void startJmxConnector() {
    String serviceAddress = null;
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        serviceAddress = generateServiceAddress(host, beanPort, registryPort, serviceName);
        JMXServiceURL address = new JMXServiceURL(serviceAddress);

        // --- Define security attributes ---
        HashMap<String, Object> env = new HashMap<String, Object>();

        // --- Authentication based on password and access files---
        if (authenticationInfo != null && authenticationInfo.isAuthenticationNeeded()) {

            if (authenticationInfo.isUseTungstenAuthenticationRealm())
                env.put(JMXConnectorServer.AUTHENTICATOR, new RealmJMXAuthenticator(authenticationInfo));
            else
                env.put("jmx.remote.x.password.file", authenticationInfo.getPasswordFileLocation());

            env.put("jmx.remote.x.access.file", authenticationInfo.getAccessFileLocation());
        }

        // --- SSL encryption ---
        if (authenticationInfo != null && authenticationInfo.isEncryptionNeeded()) {
            // Keystore
            System.setProperty("javax.net.ssl.keyStore", authenticationInfo.getKeystoreLocation());
            System.setProperty("javax.net.ssl.keyStorePassword", authenticationInfo.getKeystorePassword());
            /**
             * Configure SSL. Protocols and ciphers are set in
             * securityHelper.setSecurityProperties and used by
             * SslRMIClientSocketFactory
             */
            try {
                String[] protocolArray = authenticationInfo.getEnabledProtocols().toArray(new String[0]);
                String[] allowedCipherSuites = authenticationInfo.getEnabledCipherSuites()
                        .toArray(new String[0]);
                String[] cipherArray;

                if (protocolArray.length == 0)
                    protocolArray = null;
                if (allowedCipherSuites.length == 0)
                    cipherArray = null;
                else {
                    // Ensure we choose an allowed cipher suite.
                    cipherArray = authenticationInfo.getJvmEnabledCipherSuites().toArray(new String[0]);
                    if (cipherArray.length == 0) {
                        // We don't have any cipher suites in common. This
                        // is not good!
                        String message = "Unable to find approved ciphers in the supported cipher suites on this JVM";
                        StringBuffer sb = new StringBuffer(message).append("\n");
                        sb.append(String.format("JVM supported cipher suites: %s\n",
                                StringUtils.join(SecurityHelper.getJvmSupportedCiphers())));
                        sb.append(String.format("Approved cipher suites from security.properties: %s\n",
                                StringUtils.join(allowedCipherSuites)));
                        logger.error(sb.toString());
                        throw new RuntimeException(message);
                    }
                }

                logger.info("Setting allowed JMX server protocols: " + StringUtils.join(protocolArray, ","));
                logger.info("Setting allowed JMX server ciphers: " + StringUtils.join(cipherArray, ","));
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(cipherArray, protocolArray,
                        false);
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            } catch (IllegalArgumentException ie) {
                logger.warn("Some of the protocols or ciphers are not supported. " + ie.getMessage());
                throw new RuntimeException(ie.getLocalizedMessage(), ie);
            }
        }

        env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true");
        JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(address, env, mbs);
        connector.start();

        logger.info(MessageFormat.format("JMXConnector: security.properties={0}",
                (authenticationInfo != null) ? authenticationInfo.getParentPropertiesFileLocation()
                        : "No security.properties file found !..."));
        if (authenticationInfo != null)
            logger.info(authenticationInfo.toString());
        logger.info(String.format("JMXConnector started at address %s", serviceAddress));

        jmxConnectorServer = connector;
    } catch (Throwable e) {
        throw new ServerRuntimeException(
                MessageFormat.format("Unable to create RMI listener: {0} -> {1}", getServiceProps(), e), e);
    }
}

From source file:edu.nwpu.gemfire.monitor.data.JMXDataUpdater.java

private JMXConnector getJMXConnection() {
    JMXConnector connection = null;
    // Reference to repository
    Repository repository = Repository.get();
    try {/*from w ww  .  j a v  a  2  s. c o  m*/

        String jmxSerURL = "";

        if (LOGGER.infoEnabled()) {
            LOGGER.info(resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE") + ":"
                    + repository.getJmxUseLocator());
        }

        if (repository.getJmxUseLocator()) {

            String locatorHost = repository.getJmxHost();
            int locatorPort = Integer.parseInt(repository.getJmxPort());

            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + locatorHost + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + locatorPort);
            }

            InetAddress inetAddr = InetAddress.getByName(locatorHost);

            if ((inetAddr instanceof Inet4Address) || (inetAddr instanceof Inet6Address)) {

                if (inetAddr instanceof Inet4Address) {
                    // Locator has IPv4 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV4_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                } else {
                    // Locator has IPv6 Address
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV6_ADDRESS") + " - "
                                + inetAddr.toString());
                    }
                }

                JmxManagerInfo jmxManagerInfo = JmxManagerFinder.askLocatorForJmxManager(inetAddr, locatorPort,
                        15000, repository.isUseSSLLocator());

                if (jmxManagerInfo.port == 0) {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER"));
                    }
                } else {
                    if (LOGGER.infoEnabled()) {
                        LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER") + " : "
                                + resourceBundle.getString("LOG_MSG_HOST") + " : " + jmxManagerInfo.host + " & "
                                + resourceBundle.getString("LOG_MSG_PORT") + " : " + jmxManagerInfo.port
                                + (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL")
                                        : resourceBundle.getString("LOG_MSG_WITHOUT_SSL")));
                    }

                    jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host,
                            String.valueOf(jmxManagerInfo.port));
                }

            } /*
               * else if (inetAddr instanceof Inet6Address) { // Locator has IPv6
               * Address if(LOGGER.infoEnabled()){
               * LOGGER.info(resourceBundle.getString
               * ("LOG_MSG_LOCATOR_IPV6_ADDRESS")); } // update message to display
               * on UI cluster.setConnectionErrorMsg(resourceBundle.getString(
               * "LOG_MSG_JMX_CONNECTION_IPv6_ADDRESS"));
               *
               * }
               */else {
                // Locator has Invalid locator Address
                if (LOGGER.infoEnabled()) {
                    LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_BAD_ADDRESS"));
                }
                // update message to display on UI
                cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_BAD_ADDRESS"));

            }

        } else {
            if (LOGGER.infoEnabled()) {
                LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + this.serverName + " & "
                        + resourceBundle.getString("LOG_MSG_PORT") + " : " + this.port);
            }
            jmxSerURL = formJMXServiceURLString(this.serverName, this.port);
        }

        if (StringUtils.isNotNullNotEmptyNotWhiteSpace(jmxSerURL)) {
            JMXServiceURL url = new JMXServiceURL(jmxSerURL);

            // String[] creds = {"controlRole", "R&D"};
            String[] creds = { this.userName, this.userPassword };
            Map<String, Object> env = new HashMap<String, Object>();

            env.put(JMXConnector.CREDENTIALS, creds);

            if (repository.isUseSSLManager()) {
                // use ssl to connect
                env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
            }

            connection = JMXConnectorFactory.connect(url, env);

            // Register Pulse URL if not already present in the JMX Manager
            registerPulseUrlToManager(connection);
        }
    } catch (Exception e) {
        if (e instanceof UnknownHostException) {
            // update message to display on UI
            cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_UNKNOWN_HOST"));
        }

        // write errors
        StringWriter swBuffer = new StringWriter();
        PrintWriter prtWriter = new PrintWriter(swBuffer);
        e.printStackTrace(prtWriter);
        LOGGER.severe("Exception Details : " + swBuffer.toString() + "\n");
        if (this.conn != null) {
            try {
                this.conn.close();
            } catch (Exception e1) {
                LOGGER.severe("Error closing JMX connection " + swBuffer.toString() + "\n");
            }
            this.conn = null;
        }
    }

    return connection;
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

public void initializeRegistry(String serverAddress, String serverPort)
        throws RemoteException, NotBoundException, NoRouteToHostException, ConnectIOException {

    if (initialized) {
        return;/*  w ww .  ja  v  a  2  s .co m*/
    }

    int port = (new Integer(serverPort)).intValue();

    Registry registry;

    LOG.info("Connecting to MedSavantServerEngine @ " + serverAddress + ":" + serverPort + "...");

    try {
        registry = LocateRegistry.getRegistry(serverAddress, port, new SslRMIClientSocketFactory());
        LOG.debug("Retrieving adapters...");
        setAdaptersFromRegistry(registry);
        setLocalAdapters();
        LOG.info("Connected with SSL/TLS Encryption");
        initialized = true;
    } catch (ConnectIOException ex) {
        if (ex.getCause() instanceof SSLHandshakeException) {
            registry = LocateRegistry.getRegistry(serverAddress, port);
            LOG.info("Retrieving adapters...");
            setAdaptersFromRegistry(registry);
            LOG.info("Connected without SSL/TLS encryption");
        }
    }
    LOG.info("Done");

}

From source file:org.apache.geode.management.internal.ManagementAgent.java

/**
 * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html #gdfvq
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector
 * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using
 * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
 *///  w  w  w.j  a  v  a2  s  .co m
private void configureAndStart() throws IOException {
    // get the port for RMI Registry and RMI Connector Server
    final int port = this.config.getJmxManagerPort();
    final String hostname;
    final InetAddress bindAddr;
    if (StringUtils.isBlank(this.config.getJmxManagerBindAddress())) {
        hostname = SocketCreator.getLocalHost().getHostName();
        bindAddr = null;
    } else {
        hostname = this.config.getJmxManagerBindAddress();
        bindAddr = InetAddress.getByName(hostname);
    }

    String jmxManagerHostnameForClients = this.config.getJmxManagerHostnameForClients();
    if (StringUtils.isNotBlank(jmxManagerHostnameForClients)) {
        System.setProperty("java.rmi.server.hostname", jmxManagerHostnameForClients);
    }

    final SocketCreator socketCreator = SocketCreatorFactory
            .getSocketCreatorForComponent(SecurableCommunicationChannel.JMX);

    final boolean ssl = socketCreator.useSSL();

    if (logger.isDebugEnabled()) {
        logger.debug("Starting jmx manager agent on port {}{}", port,
                (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
    }
    RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null;
    RMIServerSocketFactory rmiServerSocketFactory = new GemFireRMIServerSocketFactory(socketCreator, bindAddr);

    // Following is done to prevent rmi causing stop the world gcs
    System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE - 1));

    // Create the RMI Registry using the SSL socket factories above.
    // In order to use a single port, we must use these factories
    // everywhere, or nowhere. Since we want to use them in the JMX
    // RMI Connector server, we must also use them in the RMI Registry.
    // Otherwise, we wouldn't be able to use a single port.

    // Start an RMI registry on port <port>.
    registry = LocateRegistry.createRegistry(port, rmiClientSocketFactory, rmiServerSocketFactory);

    // Retrieve the PlatformMBeanServer.
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Environment map. why is this declared as HashMap?
    final HashMap<String, Object> env = new HashMap<>();

    // Manually creates and binds a JMX RMI Connector Server stub with the
    // registry created above: the port we pass here is the port that can
    // be specified in "service:jmx:rmi://"+hostname+":"+port - where the
    // RMI server stub and connection objects will be exported.
    // Here we choose to use the same port as was specified for the
    // RMI Registry. We can do so because we're using \*the same\* client
    // and server socket factories, for the registry itself \*and\* for this
    // object.
    final RMIServerImpl stub = new RMIJRMPServerImpl(port, rmiClientSocketFactory, rmiServerSocketFactory, env);

    // Create an RMI connector server.
    //
    // As specified in the JMXServiceURL the RMIServer stub will be
    // registered in the RMI registry running in the local host on
    // port <port> with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    // The port specified in "service:jmx:rmi://"+hostname+":"+port
    // is the second port, where RMI connection objects will be exported.
    // Here we use the same port as that we choose for the RMI registry.
    // The port for the RMI registry is specified in the second part
    // of the URL, in "rmi://"+hostname+":"+port
    //
    // We construct a JMXServiceURL corresponding to what we have done
    // for our stub...
    final JMXServiceURL url = new JMXServiceURL(
            "service:jmx:rmi://" + hostname + ":" + port + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");

    // Create an RMI connector server with the JMXServiceURL
    //
    // JDK 1.5 cannot use JMXConnectorServerFactory because of
    // http://bugs.sun.com/view_bug.do?bug_id=5107423
    // but we're using JDK 1.6
    jmxConnectorServer = new RMIConnectorServer(new JMXServiceURL("rmi", hostname, port), env, stub, mbs) {
        @Override
        public JMXServiceURL getAddress() {
            return url;
        }

        @Override
        public synchronized void start() throws IOException {
            try {
                registry.bind("jmxrmi", stub);
            } catch (AlreadyBoundException x) {
                throw new IOException(x.getMessage(), x);
            }
            super.start();
        }
    };

    if (securityService.isIntegratedSecurity()) {
        shiroAuthenticator = new JMXShiroAuthenticator(this.securityService);
        env.put(JMXConnectorServer.AUTHENTICATOR, shiroAuthenticator);
        jmxConnectorServer.addNotificationListener(shiroAuthenticator, null,
                jmxConnectorServer.getAttributes());
        // always going to assume authorization is needed as well, if no custom AccessControl, then
        // the CustomAuthRealm
        // should take care of that
        MBeanServerWrapper mBeanServerWrapper = new MBeanServerWrapper(this.securityService);
        jmxConnectorServer.setMBeanServerForwarder(mBeanServerWrapper);
        registerAccessControlMBean();
    } else {
        /* Disable the old authenticator mechanism */
        String pwFile = this.config.getJmxManagerPasswordFile();
        if (pwFile != null && pwFile.length() > 0) {
            env.put("jmx.remote.x.password.file", pwFile);
        }

        String accessFile = this.config.getJmxManagerAccessFile();
        if (accessFile != null && accessFile.length() > 0) {
            // Rewire the mbs hierarchy to set accessController
            ReadOpFileAccessController controller = new ReadOpFileAccessController(accessFile);
            controller.setMBeanServer(mbs);
        }
    }

    jmxConnectorServer.start();
    if (logger.isDebugEnabled()) {
        logger.debug("Finished starting jmx manager agent.");
    }
}