Example usage for javax.management.remote JMXServiceURL JMXServiceURL

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

Introduction

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

Prototype

public JMXServiceURL(String serviceURL) throws MalformedURLException 

Source Link

Document

Constructs a JMXServiceURL by parsing a Service URL string.

Usage

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

/**
 * Initialize the monitor server.//from  w  w w.j  av  a 2 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:com.zenoss.jmx.JmxClient.java

/**
 * Creates a JmxClient that will interrogate the JMX Agent at the URL
 * provided./*from   w w w  . java2s  .c  o  m*/
 * 
 * @param url
 *            an Abstract Service URL for SLP, as defined in RFC 2609 and
 *            amended by RFC3111 (e.g. service:jmx:protocol:sap)
 * @throws IllegalArgumentException
 *             if the URL provided is malformed
 */
public JmxClient(String url) throws IllegalArgumentException {

    try {
        _url = new JMXServiceURL(url);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException(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");
    }//from  w w w  .  j  a  v a2s . 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: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  w w  w.  j a  v  a  2s.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.taobao.tddl.common.util.TDDLMBeanServer.java

private TDDLMBeanServer() {
    // MBServer/*from  w ww  .ja  va  2s  .com*/
    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:fr.openfarm.jmx.service.JMXQuery.java

@Override
public void connect(String username, String password, String url) throws IOException {
    Map<String, Object> environment = null;
    if ("".equals(username)) {
        username = null;/*from   www  .  ja  va 2s.  c o m*/
    }
    if ("".equals(password)) {
        username = null;
    }
    if (username != null && password != null) {
        environment = new HashMap<String, Object>();
        environment.put(JMXConnector.CREDENTIALS, new String[] { username, password });
        environment.put(USERNAME_KEY, username);
        environment.put(PASSWORD_KEY, password);
    }

    JMXServiceURL jmxUrl = new JMXServiceURL(url);
    if (environment != null) {
        log.info("connect with user/pass");
        connector = JMXConnectorFactory.connect(jmxUrl, environment);
    } else {
        log.info("connect without user/pass");
        connector = JMXConnectorFactory.connect(jmxUrl);
    }
    connection = connector.getMBeanServerConnection();
}

From source file:org.nuxeo.runtime.management.ServerLocatorService.java

protected JMXServiceURL doFormatServerURL(ServerLocatorDescriptor descriptor) {
    try {/*w  w  w  .  j  a va  2s.  co  m*/
        return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + descriptor.rmiPort + "/"
                + descriptor.domainName + "/jmxrmi");
    } catch (MalformedURLException e) {
        throw new ManagementRuntimeException("Cannot format url for " + descriptor.domainName);
    }
}

From source file:org.wso2.dss.integration.test.jira.issues.CARBON15928JMXDisablingTest.java

private MBeanInfo testMBeanForDatasource() throws Exception {
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {/*from ww w. j  a  v a 2 s.c o m*/
        String url = "service:jmx:rmi://localhost:12311/jndi/rmi://localhost:11199/jmxrmi";
        JMXServiceURL jmxUrl = new JMXServiceURL(url);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mBeanServer = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanObject = new ObjectName(dataSourceName + ",-1234:type=DataSource");
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(mbeanObject);
        return mBeanInfo;
    } catch (MalformedURLException | MalformedObjectNameException | IntrospectionException
            | ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }
}

From source file:com.heliosapm.streams.collector.ds.pool.impls.JMXClientPoolBuilder.java

/**
 * Creates a new JMXClientPoolBuilder//from  ww w . ja  va  2 s.c  om
 * @param config The configuration properties
 */
public JMXClientPoolBuilder(final Properties config) {
    final String jmxUrl = config.getProperty(JMX_URL_KEY, "").trim();
    if (jmxUrl.isEmpty())
        throw new IllegalArgumentException("The passed JMXServiceURL was null or empty");
    try {
        url = new JMXServiceURL(jmxUrl);
    } catch (Exception ex) {
        throw new IllegalArgumentException("The passed JMXServiceURL was invalid", ex);
    }
    final String user = config.getProperty(JMX_USER_KEY, "").trim();
    final String password = config.getProperty(JMX_PW_KEY, "").trim();
    if (!user.isEmpty() && !password.isEmpty()) {
        credentials = new String[] { user, password };
        env.put(JMXConnector.CREDENTIALS, credentials);
    } else {
        credentials = null;
    }
    if (config.size() > 1) {
        for (final String key : config.stringPropertyNames()) {
            final String _key = key.trim();
            if (_key.startsWith(JMX_ENVMAP_PREFIX)) {
                final String _envKey = _key.replace(JMX_ENVMAP_PREFIX, "");
                if (_envKey.isEmpty())
                    continue;
                final String _rawValue = config.getProperty(key, "").trim();
                if (_rawValue.isEmpty())
                    continue;
                final Object _convertedValue = StringHelper.convertTyped(_rawValue);
                env.put(_envKey, _convertedValue);
            }
        }
    }
}

From source file:org.pssframework.jmx.MBeanServerConnectionInterceptor.java

public Object getObject() throws Exception {
    JMXConnector connector = JMXConnectorFactory.connect(new JMXServiceURL(serviceUrl), null);
    this.connection = connector.getMBeanServerConnection();

    ProxyFactory connectionProxy = new ProxyFactory(this.connection);
    connectionProxy.addAdvice(this);
    return connectionProxy.getProxy();
}