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.apache.hadoop.hdfs.tools.DataNodeAdmin.java

/**
 * Creates the mbean server connection// w  ww. j a v a2  s. c o  m
 * @throws MalformedObjectNameException
 * @throws IOException
 */
private MBeanServerConnection mBeanServerConnection() throws MalformedObjectNameException, IOException {
    return JMXConnectorFactory.connect(new JMXServiceURL(SERVER_URL), null).getMBeanServerConnection();
}

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  ww . ja  va  2s  .co m*/
 * @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.mule.management.agents.JmxAgent.java

public void initialise() throws InitialisationException {
    if (initialized) {
        return;//from   w w  w  .ja  va  2 s  . co  m
    }
    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:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Connect to JMX interface on the given host and port.
 *
 * @param handler  Implementation of {@link RepairStatusHandler} to process incoming
 *                 notifications//from w w w.  j  ava 2s.  co m
 *                 of repair events.
 * @param host     hostname or ip address of Cassandra node
 * @param port     port number to use for JMX connection
 * @param username username to use for JMX authentication
 * @param password password to use for JMX authentication
 */
static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username,
        String password) throws ReaperException {
    ObjectName ssMbeanName;
    ObjectName cmMbeanName;
    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port));
        ssMbeanName = new ObjectName(SS_OBJECT_NAME);
        cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
    } catch (MalformedURLException | MalformedObjectNameException e) {
        LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port));
        throw new ReaperException("Failure during preparations for JMX connection", e);
    }
    try {
        Map<String, Object> env = new HashMap<String, Object>();
        if (username != null && password != null) {
            String[] creds = { username, password };
            env.put(JMXConnector.CREDENTIALS, creds);
        }
        JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection();
        Object ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class);
        String cassandraVersion = ((StorageServiceMBean) ssProxy).getReleaseVersion();
        if (cassandraVersion.startsWith("2.0") || cassandraVersion.startsWith("1.")) {
            ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean20.class);
        }

        CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName,
                CompactionManagerMBean.class);
        JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn,
                cmProxy);
        // registering a listener throws bunch of exceptions, so we do it here rather than in the
        // constructor
        mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null);
        LOG.debug("JMX connection to {} properly connected: {}", host, jmxUrl.toString());
        return proxy;
    } catch (IOException | InstanceNotFoundException e) {
        LOG.error("Failed to establish JMX connection to {}:{}", host, port);
        throw new ReaperException("Failure when establishing JMX connection", e);
    }
}

From source file:org.wso2.dss.integration.test.datasource.DataSourceInitializationAtStartUpTestCase.java

@Test(dependsOnMethods = { "isServiceExistAfterRestarting" }, enabled = false)
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public void testMBeanForDatasource() throws AxisFault {
    Map<String, String[]> env = new HashMap<String, String[]>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {//from  w  w  w .  ja v  a 2s  . c o  m
        String url = "service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/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);
        Assert.assertNotNull(mBeanInfo, "Data Source is registered in the MBean server");
    } catch (MalformedURLException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IOException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (MalformedObjectNameException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IntrospectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }

}

From source file:org.wso2.ei.dataservice.integration.test.datasource.DataSourceInitializationAtStartUpTestCase.java

@Test(dependsOnMethods = { "isServiceExistAfterRestarting" }, enabled = false)
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
public void testMBeanForDatasource() throws AxisFault {
    Map<String, String[]> env = new HashMap<String, String[]>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {//from  w  w w.j ava  2  s .  co  m
        String url = "service:jmx:rmi://localhost:11111/jndi/rmi://localhost:9999/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);
        Assert.assertNotNull(mBeanInfo, "Datasource is registered in the MBean server");
    } catch (MalformedURLException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IOException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (MalformedObjectNameException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (IntrospectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new AxisFault("Error while connecting to MBean Server " + e.getMessage(), e);
    }

}

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

public static <T, R> R invokeRemoteMBeanOperation(String remoteURL, String jmxName, Class<T> klass,
        Function<T, R> function) throws MalformedObjectNameException, IOException {
    JMXServiceURL jmxURL = new JMXServiceURL(remoteURL);
    try (JMXConnector jmxc = JMXConnectorFactory.connect(jmxURL, null)) {
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        T remoteMBean = getMBean(jmxName, klass, mbsc);
        return function.apply(remoteMBean);
    }//from ww w. j  a v a  2 s. com
}

From source file:org.apache.hadoop.hdfs.tools.JMXGet.java

/**
 * @throws Exception//w  w  w .  ja  va  2 s .  c  o  m
 *     initializes MBeanServer
 */
public void init() throws Exception {

    err("init: server=" + server + ";port=" + port + ";service=" + service + ";localVMUrl=" + localVMUrl);

    String url_string = null;
    // build connection url
    if (localVMUrl != null) {
        // use
        // jstat -snap <vmpid> | grep sun.management.JMXConnectorServer.address
        // to get url
        url_string = localVMUrl;
        err("url string for local pid = " + localVMUrl + " = " + url_string);

    } else if (!port.isEmpty() && !server.isEmpty()) {
        // using server and port
        url_string = "service:jmx:rmi:///jndi/rmi://" + server + ":" + port + "/jmxrmi";
    } // else url stays null

    // Create an RMI connector client and
    // connect it to the RMI connector server

    if (url_string == null) { // assume local vm (for example for Testing)
        mbsc = ManagementFactory.getPlatformMBeanServer();
    } else {
        JMXServiceURL url = new JMXServiceURL(url_string);

        err("Create RMI connector and connect to the RMI connector server" + url);

        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        // Get an MBeanServerConnection
        //
        err("\nGet an MBeanServerConnection");
        mbsc = jmxc.getMBeanServerConnection();
    }

    // Get domains from MBeanServer
    //
    err("\nDomains:");

    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
        err("\tDomain = " + domain);
    }

    // Get MBeanServer's default domain
    //
    err("\nMBeanServer default domain = " + mbsc.getDefaultDomain());

    // Get MBean count
    //
    err("\nMBean count = " + mbsc.getMBeanCount());

    // Query MBean names for specific domain "hadoop" and service
    ObjectName query = new ObjectName("Hadoop:service=" + service + ",*");
    hadoopObjectNames = new ArrayList<>(5);
    err("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<>(mbsc.queryNames(query, null));

    for (ObjectName name : names) {
        hadoopObjectNames.add(name);
        err("Hadoop service: " + name);
    }

}

From source file:org.opennms.features.jmxconfiggenerator.Starter.java

public void doMain(String[] args) {

    CmdLineParser parser = new CmdLineParser(this);

    parser.setUsageWidth(80);//www.  j  av a2s .c om

    try {
        parser.parseArgument(args);
        if (jmx && graph) {
            throw new CmdLineException(parser, "jmx and graph is set. Just use one at a time.");
        } else if (!jmx && !graph) {
            throw new CmdLineException(parser, "set jmx or graph.");
        }

        Map<String, String> dictionary = loadInternalDictionary();
        if (dictionaryFile != null) {
            dictionary = loadExternalDictionary(dictionaryFile);
        }

        if (jmx) {
            JMXConnector jmxConnector = null;
            JmxDatacollectionConfiggenerator jmxConfigGenerator = new JmxDatacollectionConfiggenerator();

            JMXServiceURL jmxServiceURL = null;
            if (hostName != null && port != null && outFile != null) {
                jmxServiceURL = jmxConfigGenerator.getJmxServiceURL(jmxmp, hostName, port);
            } else if (url != null && outFile != null) {
                jmxServiceURL = new JMXServiceURL(url);
            } else {
                throw new CmdLineException(parser, "no valid call found.");
            }

            jmxConnector = jmxConfigGenerator.getJmxConnector(username, password, jmxServiceURL);
            MBeanServerConnection mBeanServerConnection = jmxConfigGenerator
                    .createMBeanServerConnection(jmxConnector);
            JmxDatacollectionConfig generateJmxConfigModel = jmxConfigGenerator.generateJmxConfigModel(
                    mBeanServerConnection, serviceName, !skipDefaultVM, runWritableMBeans, dictionary);
            jmxConfigGenerator.writeJmxConfigFile(generateJmxConfigModel, outFile);

            if (jmxConnector != null) {
                logger.debug("closing connection");
                jmxConnector.close();
                logger.debug("connection closed");
            }

            return;

        } else if (graph) {
            if (inputFile != null && outFile != null) {

                JmxConfigReader jmxToSnmpGraphConfigGen = new JmxConfigReader();
                Collection<Report> reports = jmxToSnmpGraphConfigGen
                        .generateReportsByJmxDatacollectionConfig(inputFile);

                GraphConfigGenerator graphConfigGenerator = new GraphConfigGenerator();

                String snmpGraphConfig;
                if (templateFile != null) {
                    snmpGraphConfig = graphConfigGenerator.generateSnmpGraph(reports, templateFile);
                } else {
                    snmpGraphConfig = graphConfigGenerator.generateSnmpGraph(reports);
                }

                System.out.println(snmpGraphConfig);
                FileUtils.writeStringToFile(new File(outFile), snmpGraphConfig, "UTF-8");
                return;
            } else {
                throw new CmdLineException(parser, "no valid call found.");
            }
        } else {
            throw new CmdLineException(parser, "no valid call found.");
        }
    } catch (Exception e) {
        logger.error("An exception occured", e);
        System.err.println("JmxConfigGenerator [options...] arguments...");
        parser.printUsage(System.err);
        System.err.println();
        // System.err.println("  Example: java -jar JmxConfigGenerator" +
        // parser.printExample(ALL));
        System.err.println("Examples:");
        System.err.println(
                " Generation of jmx-datacollection.xml: java -jar JmxConfigGenerator.jar -jmx -host localhost -port 7199 -out JMX-DatacollectionDummy.xml [-service cassandra] [-skipDefaultVM] [-runWritableMBeans] [-dictionary dictionary.properties]");
        System.err.println(
                " Generation of snmp-graph.properties: java -jar JmxConfigGenerator.jar -graph -input test.xml -out test.properies [-template graphTemplate.vm] [-service cassandra]");
    }
}

From source file:org.springframework.jmx.access.MBeanClientInterceptor.java

/**
 * Set the service URL of the remote {@code MBeanServer}.
 *//*from   w w w  .  j  a  v  a  2 s.  c  o m*/
public void setServiceUrl(String url) throws MalformedURLException {
    this.serviceUrl = new JMXServiceURL(url);
}