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:uk.co.gidley.jmxmonitor.services.InternalJmx.java

private void startJmxConnector(Configuration configuration) throws InitialisationException {
    try {/*from ww  w .  ja  va2 s.  c o  m*/
        String url = configuration.getString(PROPERTY_PREFIX + "localJmx");
        logger.debug("Initialising local JMX server on URL {}", url);
        JMXServiceURL address = new JMXServiceURL(url);
        jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(address, null, MBEAN_SERVER);

        MBEAN_SERVER.registerMBean(jmxConnectorServer, connectorServerName);
        jmxConnectorServer.start();
    } catch (IOException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (InstanceAlreadyExistsException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (MBeanRegistrationException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    } catch (NotCompliantMBeanException e) {
        logger.error("{}", e);
        throw new InitialisationException(e);
    }
}

From source file:org.openadaptor.util.JVMNeutralMBeanServerFactory.java

/**
 * Use reflection to get an MBeanServer. Avoids compile issue where 1.4 jdk doesn't
 * have java.lang.management.ManagementFactory
 *
 * <pre>//  w  w  w  .j a v a  2  s.  c om
 *
 * Note: For 1.4, an RMI registry may have to be manually started.
 * This may be achieved by something similar to ...
 * RJMX_LIB=<i>oa3_lib</i>
 * JMX_LIB=<i>oa3_lib</i>
 * CP=${RJMXLIB}/jmxremote.jar:${JMXLIB}/jmxri.jar
 * export CLASSPATH=.:$CP ; rmiregistry 51410 &
 *
 * Does <b>not</b> apply to 1.5+
 * </pre>
 * @return MBeanServer instance.
 */
public static MBeanServer getMBeanServer() {
    String jvmVersion = System.getProperties().getProperty("java.version");
    log.info("Getting MBeanServer [for jvm " + jvmVersion + "]");
    boolean isjvm1_4 = jvmVersion.startsWith("1.4.");
    String factory = isjvm1_4 ? FACTORY_1_4 : FACTORY_1_5;
    String method = isjvm1_4 ? METHOD_1_4 : METHOD_1_5;
    if (server == null) {
        server = getMBeanServer(factory, method);
        if (isjvm1_4) {
            //Todo: Add some kind of access mechanism to change the port!
            int port = DEFAULT_RMI_PORT;

            String serviceURLString = "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/server";
            try {
                log.info("starting rmi registry on " + port);
                rmiRegistry = LocateRegistry.createRegistry(port);
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    public void run() {
                    }
                });
            } catch (RemoteException e) {
                log.warn(e);
            }
            JMXServiceURL url;
            try {
                url = new JMXServiceURL(serviceURLString);
                //url = new JMXServiceURL("jmxmp", null, 5555);
                jmxConnectorServer_1_4 = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

                // Start the RMI connector server
                log.info("Starting the RMI connector server");
                jmxConnectorServer_1_4.start();
                //Add a shutdownHook to make sure it stops also.
                addJMXShutdownHook();
                //ToDo: Remember to shut this baby down also!
                log.info("RMI connector server successfully started.");
                log.info("JMX clients may use the serviceURL: " + serviceURLString);

                //Start a Html Connection server - disabled for now.
                //It's just being explored.
                //startHtmlConnectorServer();
            } catch (Exception e) {
                log.warn("Failed to get RMI connector server started - " + e);
                e.printStackTrace();
            }
        }
    }
    return server;
}

From source file:net.timewalker.ffmq4.jmx.rmi.JMXOverRMIAgent.java

private void init() throws JMSException {
    try {//from   www . j a va  2 s  . co m
        log.info("Starting JMX agent");

        // Get or create an RMI registry
        if (rmiListenAddr == null || rmiListenAddr.equals("auto"))
            rmiListenAddr = InetAddress.getLocalHost().getHostName();

        // Connector JNDI name
        String jndiName = "jmxconnector-" + agentName;

        try {
            registry = LocateRegistry.getRegistry(rmiListenAddr, jndiRmiPort);
            registry.lookup(jndiName);

            // Remove the old registered connector
            registry.unbind(jndiName);

            log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort
                    + " with connector already registered");
        } catch (NotBoundException e) {
            // Registry already exists
            log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort);
        } catch (RemoteException e) {
            log.debug("Creating RMI registry at " + rmiListenAddr + ":" + jndiRmiPort);
            RMIServerSocketFactory ssf = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, false);
            registry = LocateRegistry.createRegistry(jndiRmiPort, null, ssf);
        }

        // Get the JVM MBean server
        mBeanServer = ManagementFactory.getPlatformMBeanServer();

        // Service URL
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + rmiListenAddr + "/jndi/rmi://"
                + rmiListenAddr + ":" + jndiRmiPort + "/" + jndiName);
        log.info("JMX Service URL : " + url);

        // Create and start the RMIConnectorServer
        Map<String, Object> env = new HashMap<>();
        mBeanServerSocketFactory = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, true);
        env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true");
        //env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new JMXRMIClientSocketFactory(rmiListenAddr));
        env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, mBeanServerSocketFactory);
        connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);
        connectorServer.start();
    } catch (Exception e) {
        throw new FFMQException("Could not initialize JMX agent", "JMX_ERROR", e);
    }
}

From source file:org.wso2.carbon.core.init.JMXServerManager.java

/**
 * The method to start JMX service.//w  w w .  j  a  v a 2s  . c  o m
 *
 * @throws ServerException If an error occurs while starting the RMI server
 */
public void startJMXService() throws ServerException {

    //File path for the jmx config file.
    String filePath = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "jmx.xml";
    boolean startJMXServer = false;

    File jmxConfigFile = new File(filePath);

    //Check whether jmx.xml file exists
    if (jmxConfigFile.exists()) {
        //Read jmx.xml file.
        parseJMXConfigXML(filePath);
        startJMXServer = jmxProperties.isStartServer();
        if (!startJMXServer) {
            return;
        }
    }

    int rmiRegistryPort = jmxProperties.getRmiRegistryPort();
    if (rmiRegistryPort == -1) {
        throw new RuntimeException(
                "RMIRegistry port has not been properly defined in the " + "jmx.xml or carbon.xml files");
    }
    MBeanServer mbs = ManagementFactory.getMBeanServer();
    String jmxURL;
    try {
        try {
            rmiRegistry = LocateRegistry.createRegistry(rmiRegistryPort);
        } catch (Throwable ignored) {
            log.error("Could not create the RMI local registry", ignored);
        }

        String hostName;
        //If 'startRMIServer' element in jmx.xml file set to true and 'HostName' element
        // value that file is not null.
        if (startJMXServer && jmxProperties.getHostName() != null) {
            hostName = jmxProperties.getHostName();//Set hostname value from jmx.xml file.
        } else { //Else
            hostName = NetworkUtils.getLocalHostname();
        }
        // Create an RMI connector and start it
        int rmiServerPort = jmxProperties.getRmiServerPort();
        if (rmiServerPort != -1) {
            jmxURL = "service:jmx:rmi://" + hostName + ":" + rmiServerPort + "/jndi/rmi://" + hostName + ":"
                    + rmiRegistryPort + "/jmxrmi";

        } else {
            jmxURL = "service:jmx:rmi:///jndi/rmi://" + hostName + ":" + rmiRegistryPort + "/jmxrmi";
        }
        JMXServiceURL url = new JMXServiceURL(jmxURL);

        // Security credentials are included in the env Map
        HashMap<String, CarbonJMXAuthenticator> env = new HashMap<String, CarbonJMXAuthenticator>();
        env.put(JMXConnectorServer.AUTHENTICATOR, new CarbonJMXAuthenticator());
        jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        jmxConnectorServer.start();
        log.info("JMX Service URL  : " + jmxURL);
    } catch (Exception e) {
        String msg = "Could not initialize RMI server";
        log.error(msg, e);
    }
}

From source file:org.apache.synapse.JmxAdapter.java

/**
 * Lazily creates the RMI registry and starts the JMX connector server based on the 
 *
 * @throws  SynapseException  if the JMX configuration is erroneous and/or the connector server
 *                            cannot be started
 *///w  w w.j a v  a  2 s.  c om
public void start() {
    initConfiguration();

    try {
        boolean registryCreated = false;
        int jndiPort = jmxInformation.getJndiPort();

        // automatic detection starting at base port
        if (jndiPort == 0) {
            jndiPort = JNDI_AUTO_PORT_OFFSET;
            for (int retries = 0; !registryCreated && (retries < 100); retries++) {
                try {
                    RMIRegistryController.getInstance().createLocalRegistry(jndiPort);
                    registryCreated = true;
                } catch (Exception ignored) {
                    jndiPort++;
                    log.warn("Trying alternate port " + jndiPort);
                }
            }
            jmxInformation.setJndiPort(jndiPort);
        } else {
            RMIRegistryController.getInstance().createLocalRegistry(jndiPort);
            registryCreated = true;
        }

        if (registryCreated) {
            jmxInformation.updateJMXUrl();
            JMXServiceURL url = new JMXServiceURL(jmxInformation.getJmxUrl());
            Map<String, Object> env = createContextMap();
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            try {
                connectorServer.start();
            } catch (IOException ex) {
                log.warn("Cannot start JMXConnectorServer on " + jmxInformation.getJmxUrl(), ex);
            }
        }
    } catch (Exception ex) {
        log.error("Error while setting up remote JMX connector", ex);
    }
}

From source file:org.springframework.jmx.support.ConnectorServerFactoryBean.java

/**
 * Start the connector server. If the <code>threaded</code> flag is set to <code>true</code>,
 * the <code>JMXConnectorServer</code> will be started in a separate thread.
 * If the <code>daemon</code> flag is set to <code>true</code>, that thread will be
 * started as a daemon thread./*from   w  w w.j  av  a2s . c om*/
 * @throws JMException if a problem occured when registering the connector server
 * with the <code>MBeanServer</code>
 * @throws IOException if there is a problem starting the connector server
 */
public void afterPropertiesSet() throws JMException, IOException {
    if (this.server == null) {
        this.server = JmxUtils.locateMBeanServer();
    }

    // Create the JMX service URL.
    JMXServiceURL url = new JMXServiceURL(this.serviceUrl);

    // Create the connector server now.
    this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, this.environment, this.server);

    // Do we want to register the connector with the MBean server?
    if (this.objectName != null) {
        this.server.registerMBean(this.connectorServer, this.objectName);
    }

    try {
        if (this.threaded) {
            // Start the connector server asynchronously (in a separate thread).
            Thread connectorThread = new Thread() {
                public void run() {
                    try {
                        connectorServer.start();
                    } catch (IOException ex) {
                        throw new DelayedConnectorStartException(ex);
                    }
                }
            };

            connectorThread.setName("JMX Connector Thread [" + this.serviceUrl + "]");
            connectorThread.setDaemon(this.daemon);
            connectorThread.start();
        } else {
            // Start the connector server in the same thread.
            this.connectorServer.start();
        }

        if (logger.isInfoEnabled()) {
            logger.info("JMX connector server started: " + this.connectorServer);
        }
    }

    catch (IOException ex) {
        // Unregister the connector server if startup failed.
        unregisterConnectorServer();
        throw ex;
    }
}

From source file:org.apache.hadoop.hbase.JMXListener.java

public void startConnectorServer(int rmiRegistryPort, int rmiConnectorPort) throws IOException {
    boolean rmiSSL = false;
    boolean authenticate = true;
    String passwordFile = null;// w  w  w .  ja v a2 s. com
    String accessFile = null;

    System.setProperty("java.rmi.server.randomIDs", "true");

    String rmiSSLValue = System.getProperty("com.sun.management.jmxremote.ssl", "false");
    rmiSSL = Boolean.parseBoolean(rmiSSLValue);

    String authenticateValue = System.getProperty("com.sun.management.jmxremote.authenticate", "false");
    authenticate = Boolean.parseBoolean(authenticateValue);

    passwordFile = System.getProperty("com.sun.management.jmxremote.password.file");
    accessFile = System.getProperty("com.sun.management.jmxremote.access.file");

    LOG.info("rmiSSL:" + rmiSSLValue + ",authenticate:" + authenticateValue + ",passwordFile:" + passwordFile
            + ",accessFile:" + accessFile);

    // Environment map
    HashMap<String, Object> jmxEnv = new HashMap<String, Object>();

    RMIClientSocketFactory csf = null;
    RMIServerSocketFactory ssf = null;

    if (rmiSSL) {
        if (rmiRegistryPort == rmiConnectorPort) {
            throw new IOException(
                    "SSL is enabled. " + "rmiConnectorPort cannot share with the rmiRegistryPort!");
        }
        csf = new SslRMIClientSocketFactory();
        ssf = new SslRMIServerSocketFactory();
    }

    if (csf != null) {
        jmxEnv.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    }
    if (ssf != null) {
        jmxEnv.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
    }

    // Configure authentication
    if (authenticate) {
        jmxEnv.put("jmx.remote.x.password.file", passwordFile);
        jmxEnv.put("jmx.remote.x.access.file", accessFile);
    }

    // Create the RMI registry
    LocateRegistry.createRegistry(rmiRegistryPort);
    // Retrieve the PlatformMBeanServer.
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Build jmxURL
    JMXServiceURL serviceUrl = buildJMXServiceURL(rmiRegistryPort, rmiConnectorPort);

    try {
        // Start the JMXListener with the connection string
        jmxCS = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, jmxEnv, mbs);
        jmxCS.start();
        LOG.info("ConnectorServer started!");
    } catch (IOException e) {
        LOG.error("fail to start connector server!", e);
    }

}

From source file:org.mule.management.agents.JmxAgent.java

public void initialise() throws InitialisationException {
    if (initialized) {
        return;/*from   ww  w.  j a va2  s .  c  om*/
    }
    if (!locateServer && !createServer) {
        throw new InitialisationException(new Message(Messages.JMX_CREATE_OR_LOCATE_SHOULD_BE_SET), this);
    }
    if (mBeanServer == null && locateServer) {
        List l = MBeanServerFactory.findMBeanServer(null);
        if (l != null && l.size() > 0) {
            mBeanServer = (MBeanServer) l.get(0);
        }
    }
    if (mBeanServer == null && createServer) {
        mBeanServer = MBeanServerFactory.createMBeanServer();
        serverCreated = true;
    }
    if (mBeanServer == null) {
        throw new InitialisationException(new Message(Messages.JMX_CANT_LOCATE_CREATE_SERVER), this);
    }
    if (connectorServerUrl != null) {
        try {
            JMXServiceURL url = new JMXServiceURL(connectorServerUrl);

            if (!credentials.isEmpty()) {
                JMXAuthenticator jmxAuthenticator = new SimplePasswordJmxAuthenticator();
                ((SimplePasswordJmxAuthenticator) jmxAuthenticator).setCredentials(credentials);
                connectorServerProperties.put(JMXConnectorServer.AUTHENTICATOR, jmxAuthenticator);
            }

            connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, connectorServerProperties,
                    mBeanServer);
        } catch (Exception e) {
            throw new InitialisationException(new Message(Messages.FAILED_TO_CREATE_X, "Jmx Connector"), e,
                    this);
        }
    }

    // We need to register all the services once the server has initialised
    MuleManager.getInstance().registerListener(new ModelEventListener() {
        public void onEvent(UMOServerEvent event) {
            if (event.getAction() == ModelEvent.MODEL_STARTED) {
                try {
                    registerStatisticsService();
                    registerMuleService();
                    registerConfigurationService();
                    registerModelService();

                    registerComponentServices();
                    registerEndpointServices();
                    registerConnectorServices();
                } catch (Exception e) {
                    throw new MuleRuntimeException(new Message(Messages.X_FAILED_TO_INITIALISE, "MBeans"), e);
                }
            }
        }
    });
    initialized = true;
}

From source file:org.chorusbdd.chorus.tools.webagent.JmxManagementServerExporter.java

public void startServer() throws Exception {

    // Ensure cryptographically strong random number generator used
    // to choose the object number - see java.rmi.server.ObjID
    ///*  ww w . j  ava2 s  . c o m*/
    //System.setProperty("java.rmi.server.randomIDs", "true");

    // Start an RMI registry on port 3000.
    //
    if (!registriesCreated.contains(port)) {
        log.info("Creating RMI registry on port " + port);
        LocateRegistry.createRegistry(port);
        registriesCreated.add(port);
    } else {
        //there's no way to shut it dnwn? So if we run a sequence of tests we clean up by unexporting the
        //listener object, and have to reuse the registry instance
        log.info("RMI registry was already running on port " + port);
    }

    // Retrieve the PlatformMBeanServer.
    //
    log.info(usePlatformMBeanServer ? "Using Platform MBean Server" : "Creating the MBean server");
    mBeanServer = usePlatformMBeanServer ? ManagementFactory.getPlatformMBeanServer()
            : MBeanServerFactory.createMBeanServer();

    // Environment map.
    //
    log.info("Initialize the environment map");
    HashMap<String, Object> env = new HashMap<String, Object>();

    // Provide SSL-based RMI socket factories.
    //
    // The protocol and cipher suites to be enabled will be the ones
    // defined by the default JSSE implementation and only server
    // authentication will be required.
    //
    //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);

    // 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.
    //
    //env.put("jmx.remote.x.password.file", "password.properties");

    // Provide the access level file used by the connector server to
    // perform user authorization. The access level file is a properties
    // based text file specifying username/access level pairs where
    // access level is either "readonly" or "readwrite" access to the
    // MBeanServer operations.
    //
    //env.put("jmx.remote.x.access.file", "access.properties");

    // 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 3000 with the name "jmxrmi". This is the same name the
    // out-of-the-box management agent uses to register the RMIServer
    // stub too.
    //
    log.info("Create an RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
    jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer);

    // Start the RMI connector server.
    //
    log.info("Start the JMX connector server on port " + port);
    jmxConnectorServer.start();
}

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

/**
 * Starts the RMI server and JMX connector server
 *///from w  w  w .  j av  a2  s  .c om
public void startServer() {
    if (!System.getProperties().containsKey(JMX_ENABLED_PROPERTY)) {
        this.logger.info("System Property '" + JMX_ENABLED_PROPERTY + "' is not set, skipping initialization.");
        return;
    }

    try {
        //Get the base rmi port
        final int portOne = this.getPortOne();

        //Get the second rmi port or calculate it
        final int portTwo = this.calculatePortTwo(portOne);

        //Create the RMI registry on the base port
        try {
            LocateRegistry.createRegistry(portOne);

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Started RMI Registry on port " + portOne);
            }
        } catch (RemoteException re) {
            throw new IllegalStateException("Could not create RMI Registry on port " + portOne, re);
        }

        //Generate the JMX Service URL
        final JMXServiceURL jmxServiceUrl = this.getServiceUrl(portOne, portTwo);

        //Map for the JMX environment configuration
        final Map<String, Object> jmxEnv = this.getJmxServerEnvironment();

        //Create the MBean Server
        final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

        //Create the JMX Connector
        try {
            this.jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(jmxServiceUrl, jmxEnv,
                    mbeanServer);

            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Created JMXConnectorServer for JMXServiceURL='" + jmxServiceUrl
                        + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'");
            }
        } catch (IOException ioe) {
            throw new IllegalStateException("Failed to create a new JMXConnectorServer for JMXServiceURL='"
                    + jmxServiceUrl + "', jmxEnv='" + jmxEnv + "' MBeanServer='" + mbeanServer + "'", ioe);
        }

        //Start the JMX Connector
        try {
            this.jmxConnectorServer.start();
            this.logger.info("Started JMXConnectorServer. Listening on '" + jmxServiceUrl + "'");
        } catch (IOException ioe) {
            throw new IllegalStateException("Failed to start the JMXConnectorServer", ioe);
        }
    } catch (RuntimeException re) {
        if (this.failOnException) {
            throw re;
        }

        this.logger.error("Failed to initialize the JMX Server", re);
    }
}