Example usage for javax.management.remote JMXConnectorServerFactory newJMXConnectorServer

List of usage examples for javax.management.remote JMXConnectorServerFactory newJMXConnectorServer

Introduction

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

Prototype

public static JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL, Map<String, ?> environment,
        MBeanServer mbeanServer) throws IOException 

Source Link

Document

Creates a connector server at the given address.

Usage

From source file:org.ff4j.jmx.FF4JMBeanTest.java

private void openJmxConnection() throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Make a connector server...
    JMXServiceURL jmxUrl = new JMXServiceURL("service:jmx:rmi://");
    jmxConnectionServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxUrl, null, mbs);
    jmxConnectionServer.start();//w  w  w. ja  va 2 s. com
    JMXServiceURL jmxAddress = jmxConnectionServer.getAddress();

    // Now make a connector client using the server's address
    jmxConnectionFactory = JMXConnectorFactory.connect(jmxAddress);
    mbServConn = jmxConnectionFactory.getMBeanServerConnection();
}

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;/*ww w .  j  av  a 2  s .co  m*/
    try {
        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);
}

From source file:org.ngrinder.monitor.agent.MonitorServer.java

/**
 * Initialize the monitor server./*from   w  w  w.j a v a2 s  .c o m*/
 *
 * @param agentConfig agentConfig
 * @throws IOException IO error
 */
public void init(AgentConfig agentConfig) throws IOException {
    this.agentConfig = agentConfig;
    Set<String> systemDataCollector = new HashSet<String>();
    systemDataCollector.add(SYSTEM);
    MonitorContext.getInstance().setDataCollectors(systemDataCollector);
    int port = agentConfig.getMonitorProperties().getPropertyInt(PROP_MONITOR_BINDING_PORT);
    this.rmiRegistry = LocateRegistry.createRegistry(port);
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    String hostname = agentConfig.getMonitorBindingIP();
    if (StringUtils.isBlank(hostname)) {
        hostname = NetworkUtils.getAllPBindingAddress();
    }
    final String jmxUrlString = String.format("service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/jmxrmi", hostname, port,
            hostname, port);
    JMXServiceURL jmxUrl = new JMXServiceURL(jmxUrlString);
    this.jmxServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxUrl, null, mBeanServer);
    RegisterMXBean.getInstance().addDefaultMXBean(mBeanServer);
    LOG.info("Service URL:{} is initiated.", jmxUrl);
}

From source file:org.skfiy.typhon.jmx.BuiltinJmxListener.java

@Override
public void execute(LifecycleEvent event) {
    if (Lifecycle.BEFORE_INIT_EVENT.equals(event.getEvent())) {

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        Registry.getRegistry(null, null).setMBeanServer(mbs);
    } else if (Lifecycle.AFTER_INIT_EVENT.equals(event.getEvent())) {
        // Ensure cryptographically strong random number generator used
        // to choose the object number - see java.rmi.server.ObjID
        ///*w  w  w.j  a  v a  2s  .co m*/
        System.setProperty("java.rmi.server.randomIDs", "true");

        // Start an RMI registry on port.
        try {
            LocateRegistry.createRegistry(port);
            LOG.info("Create RMI registry on port {}", port);
        } catch (RemoteException ex) {
            LOG.error("Create RMI registry error", ex);
            throw new TyphonException(ex);
        }

        Map<String, Object> env = new HashMap<>();

        // Provide the password file used by the connector server to
        // perform user authentication. The password file is a properties
        // based text file specifying username/password pairs.
        //
        // File file = new File(System.getProperty("typhon.home"), "bin/jmxremote.password");
        // env.put("com.sun.management.jmxremote.password.file", file.getAbsolutePath());

        try {
            jcs = JMXConnectorServerFactory.newJMXConnectorServer(newUrl(), env,
                    ManagementFactory.getPlatformMBeanServer());
            jcs.start();
        } catch (IOException ex) {
            LOG.error("start JMXConnectorServer...", ex);
            throw new TyphonException(ex);
        }
    } else if (Lifecycle.AFTER_DESTROY_EVENT.equals(event.getEvent())) {
        if (jcs != null) {
            try {
                jcs.stop();
            } catch (IOException ex) {
                LOG.error("stop JMXConnectorServer...", ex);
                throw new TyphonException(ex);
            }
        }
    }
}

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");
    }/*from  ww  w  .  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 ww  . j av a 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:org.apache.cassandra.utils.JMXServerUtils.java

/**
 * Creates a server programmatically. This allows us to set parameters which normally are
 * inaccessable.// w w  w .  java  2s .c o 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.nuxeo.dmk.DmkComponent.java

protected JDMKServerConnector newConnector(DmkProtocol config) {
    try {//from  w w w. j a  v  a  2  s  .  c o m
        String protocol = "jdmk-".concat(config.name);
        JMXServiceURL httpURL = new JMXServiceURL(protocol, null, config.port);
        JDMKServerConnector connector = (JDMKServerConnector) JMXConnectorServerFactory
                .newJMXConnectorServer(httpURL, null, mbs);
        GenericHttpConnectorServer server = (GenericHttpConnectorServer) connector.getWrapped();
        server.addUserAuthenticationInfo(new AuthInfo(config.user, config.password));
        ObjectName name = new ObjectName("org.nuxeo:type=jmx-connector,protocol=".concat(protocol));
        mbs.registerMBean(connector, name);
        return connector;
    } catch (JMException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.james.modules.server.JMXServer.java

private void doStart() {
    try {/*from  w ww .  j  av a  2s  . c  o  m*/
        PropertiesConfiguration configuration = new PropertiesConfiguration(
                fileSystem.getFile(FileSystem.FILE_PROTOCOL_AND_CONF + "jmx.properties"));
        String address = configuration.getString("jmx.address");
        int port = configuration.getInt("jmx.port");
        String serviceURL = "service:jmx:rmi://" + address + "/jndi/rmi://" + address + ":" + port + "/jmxrmi";
        RestrictingRMISocketFactory restrictingRMISocketFactory = new RestrictingRMISocketFactory(address);
        LocateRegistry.createRegistry(port, restrictingRMISocketFactory, restrictingRMISocketFactory);

        Map<String, ?> environment = ImmutableMap.of();
        jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL(serviceURL),
                environment, ManagementFactory.getPlatformMBeanServer());

        jmxConnectorServer.start();
    } catch (Exception e) {
        throw Throwables.propagate(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.
 *///from ww w.j av a  2 s. c o m
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);
    }
}