Example usage for javax.management.remote JMXConnectorServer start

List of usage examples for javax.management.remote JMXConnectorServer start

Introduction

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

Prototype

public void start() throws IOException;

Source Link

Document

Activates the connector server, that is, starts listening for client connections.

Usage

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.
 *///ww w.  jav a2 s  .c  om
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.espertech.esper.example.servershell.ServerShellMain.java

public ServerShellMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }// www  . j a v a 2  s.c o  m
    properties.load(propertiesIS);

    // Start RMI registry
    log.info("Starting RMI registry");
    int port = Integer.parseInt(properties.getProperty(ServerShellConstants.MGMT_RMI_PORT));
    LocateRegistry.createRegistry(port);

    // Obtain MBean servera
    log.info("Obtaining JMX server and connector");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    String jmxServiceURL = properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL);
    JMXServiceURL jmxURL = new JMXServiceURL(jmxServiceURL);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(jmxURL, null, mbs);
    cs.start();

    // Initialize engine
    log.info("Getting Esper engine instance");
    Configuration configuration = new Configuration();
    configuration.addEventType("SampleEvent", SampleEvent.class.getName());
    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);

    // Initialize engine
    log.info("Creating sample statement");
    SampleStatement.createStatement(engine.getEPAdministrator());

    // Register MBean
    log.info("Registering MBean");
    ObjectName name = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMX mbean = new EPServiceProviderJMX(engine);
    mbs.registerMBean(mbean, name);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    int numListeners = Integer.parseInt(properties.getProperty(ServerShellConstants.JMS_NUM_LISTENERS));
    log.info("Creating " + numListeners + " listeners to destination '" + destination + "'");

    SampleJMSMessageListener listeners[] = new SampleJMSMessageListener[numListeners];
    for (int i = 0; i < numListeners; i++) {
        listeners[i] = new SampleJMSMessageListener(engine.getEPRuntime());
        MessageConsumer consumer = jmsCtx.getSession().createConsumer(jmsCtx.getDestination());
        consumer.setMessageListener(listeners[i]);
    }

    // Start processing
    log.info("Starting JMS connection");
    jmsCtx.getConnection().start();

    // Register shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            isShutdown = true;
        }
    });

    // Report statistics
    long startTime = System.currentTimeMillis();
    long currTime;
    double deltaSeconds;
    int lastTotalEvents = 0;
    AccumulatingStat avgLast5 = new AccumulatingStat(5);
    AccumulatingStat avgLast10 = new AccumulatingStat(10);
    AccumulatingStat avgLast20 = new AccumulatingStat(20);
    do {
        // sleep
        Thread.sleep(1000);
        currTime = System.currentTimeMillis();
        deltaSeconds = (currTime - startTime) / 1000.0;

        // compute stats
        int totalEvents = 0;
        for (int i = 0; i < listeners.length; i++) {
            totalEvents += listeners[i].getCount();
        }

        double totalLastBatch = totalEvents - lastTotalEvents;

        avgLast5.add(totalLastBatch);
        avgLast10.add(totalLastBatch);
        avgLast20.add(totalLastBatch);

        log.info("total=" + totalEvents + " last=" + totalLastBatch + " last5Avg=" + avgLast5.getAvg()
                + " last10Avg=" + avgLast10.getAvg() + " last20Avg=" + avgLast20.getAvg() + " time="
                + deltaSeconds);
        lastTotalEvents = totalEvents;
    } while (!isShutdown);

    log.info("Shutting down server");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:com.taobao.tddl.common.util.TDDLMBeanServer.java

private TDDLMBeanServer() {
    // MBServer/*from   w w  w.  j  a va 2  s  .  c o  m*/
    String hostName = null;
    try {
        InetAddress addr = InetAddress.getLocalHost();

        hostName = addr.getHostName();
    } catch (IOException e) {
        log.error(LogPrefix + "Get HostName Error", e);
        hostName = "localhost";
    }
    String host = System.getProperty("hostName", hostName);
    try {
        boolean useJmx = Boolean.parseBoolean(System.getProperty("tddl.useJMX", "true"));
        if (useJmx) {
            mbs = ManagementFactory.getPlatformMBeanServer();
            int port = Integer.parseInt(System.getProperty("tddl.rmi.port", "6679"));
            String rmiName = System.getProperty("tddl.rmi.name", "tddlJmxServer");
            Registry reg = null;
            try {
                reg = LocateRegistry.getRegistry(port);
                reg.list();
            } catch (Exception e) {
                reg = null;
            }
            if (null == reg) {
                reg = LocateRegistry.createRegistry(port);
            }
            reg.list();
            String serverURL = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/" + rmiName;
            JMXServiceURL url = new JMXServiceURL(serverURL);
            final JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url,
                    null, mbs);
            connectorServer.start();
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        System.err.println("JMXConnector stop");
                        connectorServer.stop();
                    } catch (IOException e) {
                        log.error(LogPrefix + e);
                    }
                }
            });
            log.warn(LogPrefix + "jmx url: " + serverURL);
        }
    } catch (Exception e) {
        log.error(LogPrefix + "create MBServer error", e);
    }
}

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all.//w  w  w  .j  a va 2  s  .  c o  m
 *
 * Note that this test creates a Registry which will keep running until the JVM Exists. There
 * is no way to stop it but it should do no harm.
 *
 *
 */
public void testJMXConnectorServer() throws Exception {

    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);

    LocateRegistry.createRegistry(55000);
    String serverUrl = "service:jmx:rmi:///jndi/rmi://localhost:55000/server";
    JMXServiceURL url = new JMXServiceURL(serverUrl);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
    cs.start();
    JMXConnector connector = cs.toJMXConnector(null);
    connector.connect(null);
    MBeanServerConnection connection = connector.getMBeanServerConnection();
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            connection.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

    Ehcache ehcache = manager.getCache("sampleCache1");

    ehcache.put(new Element("key1", "value1"));
    ehcache.put(new Element("key2", "value1"));
    assertNotNull(ehcache.get("key1"));
    assertNotNull(ehcache.get("key2"));

    //Test CacheManager
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "CacheManager");

    //Test Cache
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "Cache");

    //Test CacheStatistics
    traverseMBeanAttributes(connection, "CacheStatistics");

    //Test CacheConfiguration
    traverseMBeanAttributes(connection, "CacheConfiguration");

    cs.stop();
}

From source file:com.webobjects.monitor.wotaskd.Application.java

/**
 * ============================================================================================
 *                  Methods Added for Enabling JMX in Wotaskd
 * ============================================================================================
 * This methods sets up this application for remote monitoring. This method creates a new 
 * connector server and associates it with the MBean Server. The server is started by calling
 * the start() method. The connector server listens for the client connection requests and
 * creates a connection for each one./*w  w  w. j av  a  2  s  .c  om*/
 */
public void setupRemoteMonitoring() {
    if (_jmxPort != null) {
        // Create an RMI connector and start it
        try {
            // Get the port difference to use when creating our new jmx listener
            int intWotaskdJmxPort = Integer.parseInt(_jmxPort);

            // Set up the Password and Access file
            HashMap<String, String> envPwd = new HashMap<String, String>();
            envPwd.put("jmx.remote.x.password.file", _jmxPasswordFile);
            envPwd.put("jmx.remote.x.access.file", _jmxAccessFile);

            // setup our listener
            java.rmi.registry.LocateRegistry.createRegistry(intWotaskdJmxPort);
            JMXServiceURL jsUrl = new JMXServiceURL(
                    "service:jmx:rmi:///jndi/rmi://" + host() + ":" + intWotaskdJmxPort + "/jmxrmi");
            NSLog.debug.appendln("Setting up monitoring on url : " + jsUrl);

            // Create an RMI Connector Server
            JMXConnectorServer jmxCS = JMXConnectorServerFactory.newJMXConnectorServer(jsUrl, envPwd,
                    getMBeanServer());

            jmxCS.start();
        } catch (Exception anException) {
            NSLog.err.appendln("Error starting remote monitoring: " + anException);
        }
    }
}

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

/**
 * Starts the JMX connector for the server.
 *//*from  w  w  w .  ja  va  2s . com*/
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:org.apache.cassandra.utils.JMXServerUtils.java

/**
 * Creates a server programmatically. This allows us to set parameters which normally are
 * inaccessable./* w  w w .j a  v  a2s.co m*/
 */
public static JMXConnectorServer createJMXServer(int port, boolean local) throws IOException {
    Map<String, Object> env = new HashMap<>();

    String urlTemplate = "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi";
    InetAddress serverAddress = null;
    if (local) {
        serverAddress = InetAddress.getLoopbackAddress();
        System.setProperty("java.rmi.server.hostname", serverAddress.getHostAddress());
    }

    // Configure the RMI client & server socket factories, including SSL config.
    env.putAll(configureJmxSocketFactories(serverAddress, local));

    // Configure authn, using a JMXAuthenticator which either wraps a set log LoginModules configured
    // via a JAAS configuration entry, or one which delegates to the standard file based authenticator.
    // Authn is disabled if com.sun.management.jmxremote.authenticate=false
    env.putAll(configureJmxAuthentication());

    // Configure authz - if a custom proxy class is specified an instance will be returned.
    // If not, but a location for the standard access file is set in system properties, the
    // return value is null, and an entry is added to the env map detailing that location
    // If neither method is specified, no access control is applied
    MBeanServerForwarder authzProxy = configureJmxAuthorization(env);

    // Make sure we use our custom exporter so a full GC doesn't get scheduled every
    // sun.rmi.dgc.server.gcInterval millis (default is 3600000ms/1 hour)
    env.put(RMIExporter.EXPORTER_ATTRIBUTE, new Exporter());

    String url = String.format(urlTemplate,
            (serverAddress != null ? serverAddress.getHostAddress() : "0.0.0.0"), port);

    int rmiPort = Integer.getInteger("com.sun.management.jmxremote.rmi.port", 0);
    JMXConnectorServer jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(
            new JMXServiceURL("rmi", null, rmiPort), env, ManagementFactory.getPlatformMBeanServer());

    // If a custom authz proxy was created, attach it to the server now.
    if (authzProxy != null)
        jmxServer.setMBeanServerForwarder(authzProxy);

    jmxServer.start();

    // use a custom Registry to avoid having to interact with it internally using the remoting interface
    configureRMIRegistry(port, env);

    logger.info("Configured JMX server at: {}", url);
    return jmxServer;
}

From source file:org.opendaylight.infrautils.diagstatus.MBeanUtils.java

public static Pair<JMXConnectorServer, Registry> startRMIConnectorServer(MBeanServer mbeanServer,
        String selfAddress) throws IOException {
    JMXServiceURL url = getJMXUrl(requireNonNull(selfAddress, "selfAddress"));
    Registry registry = LocateRegistry.createRegistry(RMI_REGISTRY_PORT);
    JMXConnectorServer cs;
    try {/*from  w  w w.jav  a2  s .co  m*/
        cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null,
                requireNonNull(mbeanServer, "mbeanServer"));
        cs.start();
    } catch (IOException e) {
        LOG.error("Error while trying to create new JMX Connector for url {}", url, e);
        throw e;
    }
    LOG.info("JMX Connector Server started for url {}", url);
    return Pair.of(cs, registry);
}