Java Code Examples for javax.management.remote.JMXConnectorFactory

The following are top voted examples for showing how to use javax.management.remote.JMXConnectorFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: ProviderTest.java   View source code 7 votes vote down vote up
private static void dotest(JMXServiceURL url, MBeanServer mbs)
    throws Exception {
    JMXConnectorServer server = null;
    JMXConnector client = null;

    server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    server.start();
    JMXServiceURL outputAddr = server.getAddress();
    System.out.println("Server started ["+ outputAddr+ "]");

    client = JMXConnectorFactory.newJMXConnector(outputAddr, null);

    client.connect();
    System.out.println("Client connected");

    MBeanServerConnection connection
        = client.getMBeanServerConnection();

    System.out.println(connection.getDefaultDomain());
}
 
Example 2
Project: Pogamut3   File: Test01_Jmx.java   View source code 6 votes vote down vote up
@Test
public void changeExportedFolderRemotely() throws MalformedURLException, IOException, MalformedObjectNameException, IntrospectionException {
    // connect through RMI and get the proxy
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName agentName = ObjectName.getInstance("myDomain:name=Alice,type=tutorial");
    /*DynamicMBean proxy = JMX.newMBeanProxy(mbs, 
            agentName,
            DynamicMBean.class);
    */
    DynamicProxy proxy = new DynamicProxy(agentName, mbsc);
     // convert the proxy to standard Folder
    
    Folder jmxFolder = new DynamicMBeanToFolderAdapter(proxy);
    //jmxFolder.getProperty("name").setValue("Cecil Corn");
    String newName = "Cecil Corn";
    jmxFolder.getFolder("knows").getProperty("name").setValue(newName);
    //mbsc.setAttribute(agentName, new Attribute("name", "Bob"));

   // waitForEnterPressed();
    assertTrue(person.knows.name.equals(newName));
    System.out.println("---/// TEST OK ///---");
}
 
Example 3
Project: Pogamut3   File: AgentJMXProxy.java   View source code 6 votes vote down vote up
public AgentJMXProxy(String agentJmxAddress) {
    // connect through RMI and get the proxy
    String[] strs = agentJmxAddress.split("\\" + AgentJMXComponents.JMX_SERVER_AGENT_NAME_DELIM);
    String jmxService = strs[0];
    String objectName = strs[1];
    try {
     JMXServiceURL url = new JMXServiceURL(jmxService);
     JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
     mbsc = jmxc.getMBeanServerConnection();
     agentName = ObjectName.getInstance(objectName);
     proxy = new DynamicProxy(agentName, mbsc);
     agentFlag = new FlagJMXProxy<IAgentState>(agentName, mbsc, AgentMBeanAdapter.AGENT_STATE_FLAG_NAME);
     agentId = new AgentIdJMXProxy(this);
    } catch (Exception e) {
    	throw new PogamutJMXException("Can't create AgentJMXProxy.", e, this);
    }
}
 
Example 4
Project: newblog   File: JMXClient.java   View source code 6 votes vote down vote up
private static MBeanServerConnection initMBeanServerConnection() {
    try {
        String ip = Config.getProperty("jmx_ip");
        String port = Config.getProperty("jmx_port");
        String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ip + ":" + port + "/jmxrmi";
        JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
        Map map = new HashMap();
        String[] credentials = Config.getProperty("credentials").split(",");
        map.put("jmx.remote.credentials", credentials);
        JMXConnector connector = JMXConnectorFactory.connect(serviceURL, map);
        mbsconnector = connector.getMBeanServerConnection();
    } catch (IOException e) {
        logger.error("get connector error" + e);
    }
    return mbsconnector;
}
 
Example 5
Project: csap-core   File: TestRawJmx.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
		try {
			String host = "localhost"; host = "csseredapp-dev-03";
			String port = "8356"; //port = "8356";
			String mbeanName = "java.lang:type=Memory";
			String attributeName = "HeapMemoryUsage";
			
			
			
			JMXServiceURL jmxUrl = new JMXServiceURL(
					"service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi" );
//			jmxUrl = new JMXServiceURL(
//					"service:jmx:rmi://localhost/jndi/rmi://" + host + ":" + port + "/jmxrmi" );
			
			logger.info("Target: " + jmxUrl ) ;
			
			JMXConnector jmxConnection = JMXConnectorFactory.connect( jmxUrl );
			
			logger.info("Got connections") ;
			
			CompositeData resultData = (CompositeData) jmxConnection.getMBeanServerConnection()
					.getAttribute( new ObjectName(mbeanName), attributeName) ;
			
			logger.log(Level.INFO, "Got mbean: heapUsed: {0}", resultData.get( "used")) ;
			
			Thread.sleep( 5000 );
		} catch ( Exception ex ) {
			logger.log( Level.SEVERE, "Failed connection", ex );
		} 
	}
 
Example 6
Project: tomcat7   File: JMXAccessorTask.java   View source code 6 votes vote down vote up
/**
 * create a new JMX Connection with auth when username and password is set.
 */
public static MBeanServerConnection createJMXConnection(String url,
        String host, String port, String username, String password)
        throws MalformedURLException, IOException {
    String urlForJMX;
    if (url != null)
        urlForJMX = url;
    else
        urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port
                + JMX_SERVICE_SUFFIX;
    Map<String, String[]> environment = null;
    if (username != null && password != null) {
        String[] credentials = new String[2];
        credentials[0] = username;
        credentials[1] = password;
        environment = new HashMap<String, String[]>();
        environment.put(JMXConnector.CREDENTIALS, credentials);
    }
    return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX),
            environment).getMBeanServerConnection();

}
 
Example 7
Project: ats-framework   File: MBeanWrapper.java   View source code 6 votes vote down vote up
MBeanWrapper( int jvmPort ) throws MonitorConfigurationException {

        this.jvmPort = jvmPort;
        try {
            JMXConnector connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:"
                                                                                           + this.jvmPort
                                                                                           + "/jmxrmi"),
                                                                         null);
            connector.connect();

            this.connection = connector.getMBeanServerConnection();
        } catch (Exception e) {
            final String msg = "Error initializing the JMV monitor. Unable to connect to JVM at port "
                               + this.jvmPort;
            log.error(msg, e);
            throw new MonitorConfigurationException(msg, e);
        }
    }
 
Example 8
Project: lams   File: ConnectorDelegate.java   View source code 6 votes vote down vote up
/**
 * Connects to the remote {@code MBeanServer} using the configured {@code JMXServiceURL}:
 * to the specified JMX service, or to a local MBeanServer if no service URL specified.
 * @param serviceUrl the JMX service URL to connect to (may be {@code null})
 * @param environment the JMX environment for the connector (may be {@code null})
 * @param agentId the local JMX MBeanServer's agent id (may be {@code null})
 */
public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map<String, ?> environment, String agentId)
		throws MBeanServerNotFoundException {

	if (serviceUrl != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Connecting to remote MBeanServer at URL [" + serviceUrl + "]");
		}
		try {
			this.connector = JMXConnectorFactory.connect(serviceUrl, environment);
			return this.connector.getMBeanServerConnection();
		}
		catch (IOException ex) {
			throw new MBeanServerNotFoundException("Could not connect to remote MBeanServer [" + serviceUrl + "]", ex);
		}
	}
	else {
		logger.debug("Attempting to locate local MBeanServer");
		return JmxUtils.locateMBeanServer(agentId);
	}
}
 
Example 9
Project: otter-G   File: JmxLoaderIntegration.java   View source code 6 votes vote down vote up
@Test
public void test_simple() {
    MBeanServer mBeanServer = exporter.getServer();

    try {
        ObjectName objectName = new ObjectName("bean:name=otterControllor");
        MBeanInfo nodeInfo = mBeanServer.getMBeanInfo(objectName);
        System.out.println(nodeInfo);
        Object result = mBeanServer.getAttribute(objectName, "HeapMemoryUsage");
        System.out.println(result);

        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi://127.0.0.1/jndi/rmi://127.0.0.1:1099/mbean");
        Map environment = null;

        JMXConnector cntor = JMXConnectorFactory.connect(address, environment);
        MBeanServerConnection mbsc = cntor.getMBeanServerConnection();
        String domain = mbsc.getDefaultDomain();
        System.out.println(domain);

        result = mbsc.getAttribute(objectName, "HeapMemoryUsage");
        System.out.println(result);
    } catch (Exception e) {
        want.fail(e.getMessage());
    }
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: JMXAccessorTask.java   View source code 6 votes vote down vote up
/**
 * create a new JMX Connection with auth when username and password is set.
 */
public static MBeanServerConnection createJMXConnection(String url,
        String host, String port, String username, String password)
        throws MalformedURLException, IOException {
    String urlForJMX;
    if (url != null)
        urlForJMX = url;
    else
        urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port
                + JMX_SERVICE_SUFFIX;
    Map<String, String[]> environment = null;
    if (username != null && password != null) {
        String[] credentials = new String[2];
        credentials[0] = username;
        credentials[1] = password;
        environment = new HashMap<String, String[]>();
        environment.put(JMXConnector.CREDENTIALS, credentials);
    }
    return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX),
            environment).getMBeanServerConnection();

}
 
Example 11
Project: jdk8u-jdk   File: TestManager.java   View source code 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 12
Project: jdk8u-jdk   File: StartManagementAgent.java   View source code 6 votes vote down vote up
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
    String jmxUrlStr =
        String.format(
            "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
            port);
    JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
    HashMap<String, ?> env = new HashMap<>();

    boolean succeeded;
    try {
        JMXConnector c = JMXConnectorFactory.connect(url, env);
        c.getMBeanServerConnection();
        succeeded = true;
    } catch(Exception ex) {
        succeeded = false;
    }
    if (succeeded && !shouldSucceed) {
        throw new Exception("Could connect to agent, but should not have been possible");
    }
    if (!succeeded && shouldSucceed) {
        throw new Exception("Could not connect to agent");
    }
}
 
Example 13
Project: jdk8u-jdk   File: ListenerScaleTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Sender sender = new Sender();
    mbs.registerMBean(sender, testObjectName);
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    try {
        test(mbs, cs, cc);
    } finally {
        cc.close();
        cs.stop();
    }
}
 
Example 14
Project: uavstack   File: BaseJMXMonitorDataCatchWorker.java   View source code 6 votes vote down vote up
@Override
public int start() {

    try {
        this.mbscConnector = JMXConnectorFactory.connect(this.JMXConnectionURL);

        this.mbsc = mbscConnector.getMBeanServerConnection();

        return 1;
    }
    catch (Exception e) {

        log.err(this,
                "Worker[" + this.cName + "] Connect to JMXURL[" + this.JMXConnectionURL.toString() + "] FAIL:", e);

        return -1;
    }
}
 
Example 15
Project: openjdk-jdk10   File: TestManager.java   View source code 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 16
Project: openjdk-jdk10   File: ListenerScaleTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (Platform.isDebugBuild()) {
        System.out.println("Running on a debug build. Performance test not applicable. Skipping.");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Sender sender = new Sender();
    mbs.registerMBean(sender, testObjectName);
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    try {
        test(mbs, cs, cc);
    } finally {
        cc.close();
        cs.stop();
    }
}
 
Example 17
Project: openjdk-jdk10   File: ProviderTest.java   View source code 6 votes vote down vote up
private static void dotest(JMXServiceURL url, MBeanServer mbs)
    throws Exception {
    JMXConnectorServer server = null;
    JMXConnector client = null;

    server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    server.start();
    JMXServiceURL outputAddr = server.getAddress();
    System.out.println("Server started ["+ outputAddr+ "]");

    client = JMXConnectorFactory.newJMXConnector(outputAddr, null);

    client.connect();
    System.out.println("Client connected");

    MBeanServerConnection connection
        = client.getMBeanServerConnection();

    System.out.println(connection.getDefaultDomain());
}
 
Example 18
Project: openjdk-jdk10   File: JMXExecutor.java   View source code 6 votes vote down vote up
/**
 * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX
 * Service URL
 *
 * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM
 */
public JMXExecutor(String target) {
    String urlStr;

    if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) {
        /* Matches "hostname:port" */
        urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target);
    } else if (target.startsWith("service:")) {
        urlStr = target;
    } else {
        throw new IllegalArgumentException("Could not recognize target string: " + target);
    }

    try {
        JMXServiceURL url = new JMXServiceURL(urlStr);
        JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>());
        mbs = c.getMBeanServerConnection();
    } catch (IOException e) {
        throw new CommandExecutorException("Could not initiate connection to target: " + target, e);
    }
}
 
Example 19
Project: doctorkafka   File: MetricsFetcher.java   View source code 6 votes vote down vote up
private static void fetchKafkaMetrics(String host, String jmxPort, String metric)
    throws Exception {

  Map<String, String[]> env = new HashMap<>();
  JMXServiceURL address = new JMXServiceURL(
      "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + jmxPort + "/jmxrmi");
  JMXConnector connector = JMXConnectorFactory.connect(address, env);
  MBeanServerConnection mbs = connector.getMBeanServerConnection();


  ObjectName name = ObjectName.getInstance(metric);
  MBeanInfo beanInfo = mbs.getMBeanInfo(name);
  for (MBeanAttributeInfo attributeInfo : beanInfo.getAttributes()) {
    Object obj = mbs.getAttribute(name, attributeInfo.getName());
    System.out.println(" attributeName = " + attributeInfo.getName() + " " + obj.toString());
  }
}
 
Example 20
Project: Byter   File: JmxConnectionHelper.java   View source code 6 votes vote down vote up
/**
 * Creates the jmxConnector with passed parameters.
 * @param host host address
 * @param port port of the host
 * @param user username (null possible)
 * @param pass password (null possible)
 * @return connected JMXConnector
 * @throws IOException IOException
 */
public static JMXConnector buildJmxMPConnector(final String host, final int port, final String user, final String pass) throws IOException {
    try {
        final JMXServiceURL serviceURL = new JMXServiceURL("jmxmp", host,port);
        if("null".equals(user) || "null".equals(pass) || user == null || pass == null){
            return JMXConnectorFactory.connect(serviceURL);
        }
        final Map<String, Object> environment = new HashMap<>();
        environment.put("jmx.remote.credentials", new String[]{user,pass});
        environment.put(Context.SECURITY_PRINCIPAL, user);
        environment.put(Context.SECURITY_CREDENTIALS, pass);
        return JMXConnectorFactory.connect(serviceURL,environment);
    } catch (MalformedURLException e) {
        log.log(Level.WARNING, "Malformed ServiceURL in buildJmxConnector");
        return null;
    }
}
 
Example 21
Project: lazycat   File: JMXAccessorTask.java   View source code 6 votes vote down vote up
/**
 * create a new JMX Connection with auth when username and password is set.
 */
public static MBeanServerConnection createJMXConnection(String url, String host, String port, String username,
		String password) throws MalformedURLException, IOException {
	String urlForJMX;
	if (url != null)
		urlForJMX = url;
	else
		urlForJMX = JMX_SERVICE_PREFIX + host + ":" + port + JMX_SERVICE_SUFFIX;
	Map<String, String[]> environment = null;
	if (username != null && password != null) {
		String[] credentials = new String[2];
		credentials[0] = username;
		credentials[1] = password;
		environment = new HashMap<String, String[]>();
		environment.put(JMXConnector.CREDENTIALS, credentials);
	}
	return JMXConnectorFactory.connect(new JMXServiceURL(urlForJMX), environment).getMBeanServerConnection();

}
 
Example 22
Project: newrelic-pcf-drain   File: OpsMetrics.java   View source code 6 votes vote down vote up
private <T> T execute(JmxTemplate<T> template) throws OpsMetricsException {
    LOG.debug("Connecting to {}:{}", host, port);
    JMXConnector connector = null;
    try {
        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":"
                + port + "/jmxrmi");
        HashMap<String, String[]> env = getCredentials();
        connector = JMXConnectorFactory.connect(address, env);
        MBeanServerConnection mbs = connector.getMBeanServerConnection();
        return template.execute(mbs);
    } catch (Exception e) {
        LOG.error("Unabled to execute JMX command", e);
        throw new OpsMetricsException(e);
    } finally {
        close(connector);
    }
}
 
Example 23
Project: openjdk9   File: JMXExecutor.java   View source code 6 votes vote down vote up
/**
 * Instantiates a new JMXExecutor targeting the VM indicated by the given host/port combination or a full JMX
 * Service URL
 *
 * @param target a host/port combination on the format "host:port" or a full JMX Service URL of the target VM
 */
public JMXExecutor(String target) {
    String urlStr;

    if (target.matches("^\\w[\\w\\-]*(\\.[\\w\\-]+)*:\\d+$")) {
        /* Matches "hostname:port" */
        urlStr = String.format("service:jmx:rmi:///jndi/rmi://%s/jmxrmi", target);
    } else if (target.startsWith("service:")) {
        urlStr = target;
    } else {
        throw new IllegalArgumentException("Could not recognize target string: " + target);
    }

    try {
        JMXServiceURL url = new JMXServiceURL(urlStr);
        JMXConnector c = JMXConnectorFactory.connect(url, new HashMap<>());
        mbs = c.getMBeanServerConnection();
    } catch (IOException e) {
        throw new CommandExecutorException("Could not initiate connection to target: " + target, e);
    }
}
 
Example 24
Project: openjdk9   File: TestManager.java   View source code 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 25
Project: spring   File: ConnectorDelegate.java   View source code 6 votes vote down vote up
/**
 * Connects to the remote {@code MBeanServer} using the configured {@code JMXServiceURL}:
 * to the specified JMX service, or to a local MBeanServer if no service URL specified.
 * @param serviceUrl the JMX service URL to connect to (may be {@code null})
 * @param environment the JMX environment for the connector (may be {@code null})
 * @param agentId the local JMX MBeanServer's agent id (may be {@code null})
 */
public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map<String, ?> environment, String agentId)
		throws MBeanServerNotFoundException {

	if (serviceUrl != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Connecting to remote MBeanServer at URL [" + serviceUrl + "]");
		}
		try {
			this.connector = JMXConnectorFactory.connect(serviceUrl, environment);
			return this.connector.getMBeanServerConnection();
		}
		catch (IOException ex) {
			throw new MBeanServerNotFoundException("Could not connect to remote MBeanServer [" + serviceUrl + "]", ex);
		}
	}
	else {
		logger.debug("Attempting to locate local MBeanServer");
		return JmxUtils.locateMBeanServer(agentId);
	}
}
 
Example 26
Project: openjdk9   File: ListenerScaleTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (Platform.isDebugBuild()) {
        System.out.println("Running on a debug build. Performance test not applicable. Skipping.");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    Sender sender = new Sender();
    mbs.registerMBean(sender, testObjectName);
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    JMXConnectorServer cs =
        JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    try {
        test(mbs, cs, cc);
    } finally {
        cc.close();
        cs.stop();
    }
}
 
Example 27
Project: ipst   File: RemoteOnlineApplication.java   View source code 6 votes vote down vote up
private void connect() throws IOException, MalformedObjectNameException, InstanceNotFoundException {
    try {
        this.connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
        mbsc = connector.getMBeanServerConnection();

        ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
        application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name, LocalOnlineApplicationMBean.class,
                false);
        mbsc.addNotificationListener(name, this, null, null);
        connected = true;
        for (OnlineApplicationListener l : listeners) {
            l.onConnection();
        }
    } catch (Exception ex) {
        LOGGER.error("Exception connecting JMX to " + serviceURL + ": " + ex.getMessage(), ex);
    }
}
 
Example 28
Project: spring4-understanding   File: ConnectorDelegate.java   View source code 6 votes vote down vote up
/**
 * Connects to the remote {@code MBeanServer} using the configured {@code JMXServiceURL}:
 * to the specified JMX service, or to a local MBeanServer if no service URL specified.
 * @param serviceUrl the JMX service URL to connect to (may be {@code null})
 * @param environment the JMX environment for the connector (may be {@code null})
 * @param agentId the local JMX MBeanServer's agent id (may be {@code null})
 */
public MBeanServerConnection connect(JMXServiceURL serviceUrl, Map<String, ?> environment, String agentId)
		throws MBeanServerNotFoundException {

	if (serviceUrl != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Connecting to remote MBeanServer at URL [" + serviceUrl + "]");
		}
		try {
			this.connector = JMXConnectorFactory.connect(serviceUrl, environment);
			return this.connector.getMBeanServerConnection();
		}
		catch (IOException ex) {
			throw new MBeanServerNotFoundException("Could not connect to remote MBeanServer [" + serviceUrl + "]", ex);
		}
	}
	else {
		logger.debug("Attempting to locate local MBeanServer");
		return JmxUtils.locateMBeanServer(agentId);
	}
}
 
Example 29
Project: ibm-performance-monitor   File: PerformanceLoggerManagerCLI.java   View source code 6 votes vote down vote up
/**
 * JMX Connector helper class
 * 
 * @param host host name
 * @param port port number
 * @param service service name
 * @return the mbean connection
 */
protected static MBeanServerConnection getMBeanServerConnection( String host, String port, String service ) {
    try {
        if ( ( host == null || port == null ) && service == null ) {
            System.out.println( "Using local JMV connection" );
            return ManagementFactory.getPlatformMBeanServer();

        }

        if ( service == null ) {
            service = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        }

        System.out.println( "Connecting to : " + service );
        JMXServiceURL url = new JMXServiceURL( service );
        JMXConnector jmx = JMXConnectorFactory.connect( url );
        return jmx.getMBeanServerConnection();
    } catch ( Throwable e ) {
        System.out.println( "Unable to connect to JMX Server: " + service + " : " + e.getMessage() );
    }
    System.out.println( "Reverting to local jvm connection" );
    return ManagementFactory.getPlatformMBeanServer();

}
 
Example 30
Project: datadog-jmx-collector   File: AttachApiConnector.java   View source code 6 votes vote down vote up
@Override
public JmxConnection connect() {
    try {
        com.sun.tools.attach.VirtualMachine vm = com.sun.tools.attach.VirtualMachine.attach( descriptor );

        Stopwatch sw = Stopwatch.createStarted();
        // TODO - timeout
        // https://community.oracle.com/blogs/emcmanus/2007/05/23/making-jmx-connection-timeout

        JMXServiceURL jmxUrl = JmxUtils.determineServiceUrl( vm );
        logger.info( "Connecting to JVM {} via {}", descriptor, jmxUrl );

        JMXConnector connector = JMXConnectorFactory.connect( jmxUrl );
        final MBeanServerConnection mbeanServerConnection = connector.getMBeanServerConnection();

        sw.stop();
        logger.info( "Connected to '{}' in {}ms", descriptor, sw.elapsed( TimeUnit.MILLISECONDS ) );


        return new JmxConnection( connector, mbeanServerConnection, createConnectionMetaData( vm ) );
    } catch( Exception e ) {
        throw Throwables.propagate( e );
    }
}
 
Example 31
Project: datadog-jmx-collector   File: RmiConnector.java   View source code 6 votes vote down vote up
@Override
public JmxConnection connect() {
    try {
        Stopwatch sw = Stopwatch.createStarted();
        // TODO - timeout
        // https://community.oracle.com/blogs/emcmanus/2007/05/23/making-jmx-connection-timeout

        JMXServiceURL jmxUrl = new JMXServiceURL( String.format( "service:jmx:rmi:///jndi/rmi://:%d/jmxrmi", jmxPort ) );
        logger.info( "Connecting to JVM via {}", jmxUrl );

        JMXConnector connector = JMXConnectorFactory.connect( jmxUrl );
        final MBeanServerConnection mbeanServerConnection = connector.getMBeanServerConnection();

        sw.stop();
        logger.info( "Connected to '{}' in {}ms", jmxUrl, sw.elapsed( TimeUnit.MILLISECONDS ) );

        return new JmxConnection( connector, mbeanServerConnection, createConnectionMetaData( jmxPort ) );
    } catch( Exception e ) {
        throw Throwables.propagate( e );
    }
}
 
Example 32
Project: jdk8u_jdk   File: TestManager.java   View source code 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 33
Project: jdk8u_jdk   File: JMXAgentInterfaceBinding.java   View source code 6 votes vote down vote up
private void connect() throws IOException {
    System.out.println(
            "JMXConnectorThread: Attempting JMX connection on: "
                    + addr + " on port " + jmxPort);
    JMXServiceURL url;
    try {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"
                + addr + ":" + jmxPort + "/jmxrmi");
    } catch (MalformedURLException e) {
        throw new RuntimeException("Test failed.", e);
    }
    Map<String, Object> env = new HashMap<>();
    if (useSSL) {
        SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
        env.put("com.sun.jndi.rmi.factory.socket", csf);
        env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    }
    // connect and immediately close
    JMXConnector c = JMXConnectorFactory.connect(url, env);
    c.close();
    System.out.println("JMXConnectorThread: connection to JMX worked");
    jmxConnectWorked = true;
    checkRmiSocket();
    latch.countDown(); // signal we are done.
}
 
Example 34
Project: jdk8u_jdk   File: StartManagementAgent.java   View source code 6 votes vote down vote up
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
    String jmxUrlStr =
        String.format(
            "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
            port);
    JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
    HashMap<String, ?> env = new HashMap<>();

    boolean succeeded;
    try {
        JMXConnector c = JMXConnectorFactory.connect(url, env);
        c.getMBeanServerConnection();
        succeeded = true;
    } catch(Exception ex) {
        succeeded = false;
    }
    if (succeeded && !shouldSucceed) {
        throw new Exception("Could connect to agent, but should not have been possible");
    }
    if (!succeeded && shouldSucceed) {
        throw new Exception("Could not connect to agent");
    }
}
 
Example 35
Project: HeliosStreams   File: ClientProvider.java   View source code 6 votes vote down vote up
/**
    * {@inheritDoc}
    * @see javax.management.remote.JMXConnectorProvider#newJMXConnector(javax.management.remote.JMXServiceURL, java.util.Map)
    */
   @Override
public JMXConnector newJMXConnector(final JMXServiceURL serviceURL, final Map<String, ?> env) throws IOException {
	if (!serviceURL.getProtocol().equals(PROTOCOL_NAME)) {
		throw new MalformedURLException("Protocol not [" + PROTOCOL_NAME + "]: " +
					    serviceURL.getProtocol());
	}
	final Map<String, ?> environment = env==null ? new HashMap<String, Object>() : env;
	final String remoteHost = serviceURL.getHost();
	final int remotePort = serviceURL.getPort();
	
	final int localPort = SSHTunnelManager.getInstance().getPortForward(remoteHost, remotePort);
	final String format = environment.containsKey(DELEGATE_PROTOCOL_FORMAT_KEY) ? environment.get(DELEGATE_PROTOCOL_FORMAT_KEY).toString() : DEFAULT_DELEGATE_PROTOCOL_FORMAT;
	
	final JMXServiceURL tunneledURL = JMXHelper.serviceUrl(format, "localhost", localPort);
	final JMXConnector connector = JMXConnectorFactory.newJMXConnector(tunneledURL, environment);
	
	final UpdateableJMXConnector ujmx = new UpdateableJMXConnector(connector, serviceURL, environment);
	connector.addConnectionNotificationListener(this, this, ujmx);
	return ujmx;
   }
 
Example 36
Project: lookaside_java-1.8.0-openjdk   File: TestManager.java   View source code 6 votes vote down vote up
private static void connect(String pid, String address) throws Exception {
    if (address == null) {
        throw new RuntimeException("Local connector address for " +
                                   pid + " is null");
    }

    System.out.println("Connect to process " + pid + " via: " + address);

    JMXServiceURL url = new JMXServiceURL(address);
    JMXConnector c = JMXConnectorFactory.connect(url);
    MBeanServerConnection server = c.getMBeanServerConnection();

    System.out.println("Connected.");

    RuntimeMXBean rt = newPlatformMXBeanProxy(server,
        RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
    System.out.println(rt.getName());

    // close the connection
    c.close();
}
 
Example 37
Project: lookaside_java-1.8.0-openjdk   File: JMXAgentInterfaceBinding.java   View source code 6 votes vote down vote up
private void connect() throws IOException {
    System.out.println(
            "JMXConnectorThread: Attempting JMX connection on: "
                    + addr + " on port " + jmxPort);
    JMXServiceURL url;
    try {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"
                + addr + ":" + jmxPort + "/jmxrmi");
    } catch (MalformedURLException e) {
        throw new RuntimeException("Test failed.", e);
    }
    Map<String, Object> env = new HashMap<>();
    if (useSSL) {
        SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
        env.put("com.sun.jndi.rmi.factory.socket", csf);
        env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    }
    // connect and immediately close
    JMXConnector c = JMXConnectorFactory.connect(url, env);
    c.close();
    System.out.println("JMXConnectorThread: connection to JMX worked");
    jmxConnectWorked = true;
    checkRmiSocket();
    latch.countDown(); // signal we are done.
}
 
Example 38
Project: lookaside_java-1.8.0-openjdk   File: StartManagementAgent.java   View source code 6 votes vote down vote up
private static void tryConnect(int port, boolean shouldSucceed) throws Exception {
    String jmxUrlStr =
        String.format(
            "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
            port);
    JMXServiceURL url = new JMXServiceURL(jmxUrlStr);
    HashMap<String, ?> env = new HashMap<>();

    boolean succeeded;
    try {
        JMXConnector c = JMXConnectorFactory.connect(url, env);
        c.getMBeanServerConnection();
        succeeded = true;
    } catch(Exception ex) {
        succeeded = false;
    }
    if (succeeded && !shouldSucceed) {
        throw new Exception("Could connect to agent, but should not have been possible");
    }
    if (!succeeded && shouldSucceed) {
        throw new Exception("Could not connect to agent");
    }
}
 
Example 39
Project: product-ei   File: CARBON15928JMXDisablingTest.java   View source code 6 votes vote down vote up
private MBeanInfo testMBeanForDatasource() throws Exception {
    Map<String, String[]> env = new HashMap<>();
    String[] credentials = { "admin", "admin" };
    env.put(JMXConnector.CREDENTIALS, credentials);
    try {
        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);
    }
}
 
Example 40
Project: Pogamut3   File: DefaultPogamutPlatform.java   View source code 5 votes vote down vote up
/**
 * @return Connection to a remote MBeanServer
 * @throws cz.cuni.amis.utils.exception.PogamutException
 */
public MBeanServerConnection getMBeanServerConnection() throws PogamutException {
    // connect through RMI and get the proxy
    try {
        if (mbsc == null) {
            JMXServiceURL url = getMBeanServerURL();
            JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
            mbsc = jmxc.getMBeanServerConnection();
        }
        return mbsc;
    } catch (IOException iOException) {
        throw new PogamutException("IO exception occured while creating remote MBeanServer connector.",
                iOException);
    }
}