Java Code Examples for javax.management.remote.JMXConnector

The following examples show how to use javax.management.remote.JMXConnector. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Jpom   Source File: JvmUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 获取指定程序的jvm 信息
 *
 * @param jpomTag jpomTag
 * @return null 没有运行或者获取数据
 * @throws Exception 异常
 */
public static MemoryMXBean getMemoryMXBean(String jpomTag) throws Exception {
    VirtualMachine virtualMachine = JvmUtil.getVirtualMachine(jpomTag);
    if (virtualMachine == null) {
        return null;
    }
    try {
        JMXServiceURL url = getJMXServiceURL(virtualMachine);
        if (url == null) {
            return null;
        }
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
        return ManagementFactory.newPlatformMXBeanProxy(mBeanServerConnection, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
    } finally {
        virtualMachine.detach();
    }
}
 
Example 2
Source Project: jdk8u60   Source File: TestManager.java    License: GNU General Public License v2.0 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 3
Source Project: cassandra-opstools   Source File: DynamicSnitchDumper.java    License: Apache License 2.0 6 votes vote down vote up
private static DynamicEndpointSnitchMBean getDSnitchMbean(JMXServiceURL jmxUrl, Map<String, Object> env) throws IOException, MalformedObjectNameException {
  JMXConnector jmxc = JMXConnectorFactory.connect(jmxUrl, env);
  MBeanServerConnection mbeanServerConn = jmxc.getMBeanServerConnection();
  Set<ObjectName> objs = mbeanServerConn.queryNames(null, null);
  ObjectName realName = null;

  // in cassandra 1.1, the mbean has a "random" instance number, listing mbeans and finding the real one.
  for (ObjectName ob : objs) {
    if (ob.getCanonicalName().contains("DynamicEndpointSnitch"))
      realName = ob;
  }
  if (realName != null)
    return JMX.newMBeanProxy(mbeanServerConn, realName, DynamicEndpointSnitchMBean.class);
  else
    throw new RuntimeException("Could not find the DynamicEndpointSnitch mbean!");
}
 
Example 4
Source Project: product-ei   Source File: CARBON15928JMXDisablingTest.java    License: Apache License 2.0 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 5
private MBeanServerCollector buildMBeanServerCollector(JmxServerConfiguration config)
		throws JmxMBeanServerConnectionException {

	JMXConnector connection = null;

	try {
		JMXServiceURL url = new JMXServiceURL(config.getServiceUrl());
		connection = JMXConnectorFactory.connect(url);
		MBeanServerConnection server = connection.getMBeanServerConnection();
		return new MBeanServerCollector(config, server, connection);
	} catch (IOException e) {
		if (connection != null) {
			ResourceUtils.close(connection);
		}
		throw new JmxMBeanServerConnectionException(
				"Faild to connect to JMX Server " + config.getServiceUrl() + ".", e);
	}
}
 
Example 6
Source Project: tomcatsrc   Source File: JMXAccessorTask.java    License: Apache License 2.0 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
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 8
Source Project: dragonwell8_jdk   Source File: JMXExecutor.java    License: GNU General Public License v2.0 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 9
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 10
Source Project: helix   Source File: JmxDumper.java    License: Apache License 2.0 6 votes vote down vote up
public JmxDumper(String jmxService, String domain, String beanClassName, String namePattern,
    int samplePeriod, List<String> fields, List<String> operations, String outputfile,
    int sampleCount) throws Exception {
  _jmxUrl = jmxService;
  _domain = domain;
  _beanClassName = beanClassName;
  _samplePeriod = samplePeriod;
  _outputFields.addAll(fields);
  _operations.addAll(operations);
  _outputFileName = outputfile;
  _namePattern = namePattern;
  _targetSamples = sampleCount;

  JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + _jmxUrl + "/jmxrmi");
  JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

  _mbeanServer = jmxc.getMBeanServerConnection();
  MBeanServerNotificationFilter filter = new MBeanServerNotificationFilter();
  filter.enableAllObjectNames();
  _mbeanServer.addNotificationListener(MBeanServerDelegate.DELEGATE_NAME, this, filter, null);
  init();
  _timer = new Timer(true);
  _timer.scheduleAtFixedRate(new SampleTask(), _samplePeriod, _samplePeriod);
}
 
Example 11
Source Project: TencentKona-8   Source File: JMXExecutor.java    License: GNU General Public License v2.0 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 12
Source Project: kafka-eagle   Source File: KafkaMetricsServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/** Get topic size from kafka jmx. */
public JSONObject topicSize(String clusterAlias, String topic) {
	String jmx = "";
	JMXConnector connector = null;
	List<MetadataInfo> leaders = kafkaService.findKafkaLeader(clusterAlias, topic);
	long tpSize = 0L;
	for (MetadataInfo leader : leaders) {
		String jni = kafkaService.getBrokerJMXFromIds(clusterAlias, leader.getLeader());
		jmx = String.format(JMX, jni);
		try {
			JMXServiceURL jmxSeriverUrl = new JMXServiceURL(jmx);
			connector = JMXFactoryUtils.connectWithTimeout(jmxSeriverUrl, 30, TimeUnit.SECONDS);
			MBeanServerConnection mbeanConnection = connector.getMBeanServerConnection();
			String objectName = String.format(KafkaLog.SIZE.getValue(), topic, leader.getPartitionId());
			Object size = mbeanConnection.getAttribute(new ObjectName(objectName), KafkaLog.VALUE.getValue());
			tpSize += Long.parseLong(size.toString());
		} catch (Exception ex) {
			LOG.error("Get topic size from jmx has error, msg is " + ex.getMessage());
			ex.printStackTrace();
		} finally {
			if (connector != null) {
				try {
					connector.close();
				} catch (IOException e) {
					LOG.error("Close jmx connector has error, msg is " + e.getMessage());
				}
			}
		}
	}

	return StrUtils.stringifyByObject(tpSize);
}
 
Example 13
@Override
public Map<String, DatabaseVersion> getClusterDatabaseVersions() throws SQLException{
    final Map<String, DatabaseVersion> dbVersions=new HashMap<>();
    operate(new JMXServerOperation(){
        @Override
        public void operate(List<Pair<String, JMXConnector>> connections) throws MalformedObjectNameException, IOException, SQLException{
            List<DatabaseVersion> databaseVersions=JMXUtils.getSpliceMachineVersion(connections);
            int i=0;
            for(DatabaseVersion databaseVersion : databaseVersions){
                dbVersions.put(connections.get(i).getFirst(),databaseVersion);
            }
        }
    });
    return dbVersions;
}
 
Example 14
public JMXConnector newJMXConnector(JMXServiceURL url,
                                    Map<String,?> map)
    throws IOException {
    final String protocol = url.getProtocol();
    called = true;
    System.out.println("JMXConnectorProviderImpl called");

    if(protocol.equals("rmi"))
        return new RMIConnector(url, map);
    if(protocol.equals("throw-provider-exception"))
        throw new JMXProviderException("I have been asked to throw");

    throw new IllegalArgumentException("UNKNOWN PROTOCOL");
}
 
Example 15
Source Project: netbeans   Source File: WebLogicRemote.java    License: Apache License 2.0 5 votes vote down vote up
public <T> T executeAction(@NonNull final JmxAction<T> action, @NullAllowed Callable<String> nonProxy) throws Exception {
    return executeAction(new Callable<T>() {

        @Override
        public T call() throws Exception {
            JMXServiceURL url = new JMXServiceURL(config.isSecured() ? "t3s" : "t3", // NOI18N
                    config.getHost(), config.getPort(), "/jndi/weblogic.management.mbeanservers.domainruntime"); // NOI18N

            String username = config.getUsername();
            String password = config.getPassword();

            Map<String, Object> env = new HashMap<String, Object>();
            env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
                    "weblogic.management.remote"); // NOI18N
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, username);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS, password);
            env.put("jmx.remote.credentials", // NOI18N
                    new String[]{username, password});
            env.put("jmx.remote.protocol.provider.class.loader", //NOI18N
                    config.getLayout().getClassLoader());

            JMXConnector jmxConnector = JMXConnectorFactory.newJMXConnector(url, env);
            jmxConnector.connect();
            try {
                return action.execute(jmxConnector.getMBeanServerConnection());
            } finally {
                jmxConnector.close();
            }
        }
    }, nonProxy);
}
 
Example 16
Source Project: newrelic-plugins   Source File: JMXHelper.java    License: MIT License 5 votes vote down vote up
private static void close(JMXConnector connector) {
	if (connector != null) {
		try {
			connector.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example 17
public JMXConnector newJMXConnector(JMXServiceURL url,
                                    Map<String,?> map)
    throws IOException {
    final String protocol = url.getProtocol();
    called = true;
    System.out.println("JMXConnectorProviderImpl called");

    if(protocol.equals("rmi"))
        return new RMIConnector(url, map);
    if(protocol.equals("throw-provider-exception"))
        throw new JMXProviderException("I have been asked to throw");

    throw new IllegalArgumentException("UNKNOWN PROTOCOL");
}
 
Example 18
Source Project: jdk8u-jdk   Source File: ClientProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
public JMXConnector newJMXConnector(JMXServiceURL serviceURL,
                                    Map<String,?> environment)
        throws IOException {
    if (!serviceURL.getProtocol().equals("rmi")) {
        throw new MalformedURLException("Protocol not rmi: " +
                                        serviceURL.getProtocol());
    }
    return new RMIConnector(serviceURL, environment);
}
 
Example 19
Source Project: peer-os   Source File: KarafManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@RolesAllowed( {
        "Karaf-Server-Administration|Write", "Karaf-Server-Administration|Read", "System-Management|Write",
        "System-Management|Update"
} )
@Override
public String executeJMXCommand( final String commandStr )
{
    String result = "No Result";

    JMXConnector connector = null;
    try
    {
        HashMap<String, String[]> environment = new HashMap<>();
        String[] credentials = new String[] { IdentityManager.ADMIN_USERNAME, IdentityManager.ADMIN_DEFAULT_PWD };
        environment.put( JMXConnector.CREDENTIALS, credentials );

        JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi:///jndi/rmi://localhost:1099/karaf-root" );
        connector = JMXConnectorFactory.connect( url, environment );
        MBeanServerConnection mbeanServer = connector.getMBeanServerConnection();
        ObjectName systemMBean = new ObjectName( "org.apache.karaf:type=bundle,name=root" );
        mbeanServer.invoke( systemMBean, commandStr, null, null );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
    }
    finally
    {
        SafeCloseUtil.close( connector );
    }

    return result;
}
 
Example 20
Source Project: spliceengine   Source File: JMXUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<ThreadPoolStatus> getMonitoredThreadPools(List<Pair<String,JMXConnector>> mbscArray) throws MalformedObjectNameException, IOException {
	List<ThreadPoolStatus> monitoredThreadPools =new ArrayList<>();
	for (Pair<String,JMXConnector> mbsc: mbscArray) {
		monitoredThreadPools.add(getNewMBeanProxy(mbsc.getSecond(),MONITORED_THREAD_POOL,ThreadPoolStatus.class));
	}
	return monitoredThreadPools;
}
 
Example 21
Source Project: java-svc   Source File: ThreadDump.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws IOException, AttachException, InstanceNotFoundException,
		MalformedObjectNameException, MBeanException, ReflectionException {
	AttachUtils.printJVMVersion();
	String pid = AttachUtils.checkPid(args);
	JMXConnector connector = JMXConnectorFactory.connect(AttachUtils.startLocalAgent(pid));

	MBeanServerConnection connection = connector.getMBeanServerConnection();
	String result = (String) connection.invoke(new ObjectName(DC_OBJECT_NAME), "threadPrint",
			new Object[] { new String[0] }, new String[] { String[].class.getName() });
	System.out.println(result);
}
 
Example 22
Source Project: hottub   Source File: RMIDownloadTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void testWithException(boolean send)
throws Exception {
    ClassLoader zoobyCL = new ZoobyClassLoader();
    Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
    Object zooby = zoobyClass.newInstance();

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector cc = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = cc.getMBeanServerConnection();

    Object rzooby;
    if (send) {
        System.out.println("Sending object...");
        mbsc.setAttribute(getSetName, new Attribute("It", zooby));
        rzooby = getSetInstance.getIt();
    } else {
        System.out.println("Receiving object...");
        getSetInstance.setIt(zooby);
        rzooby = mbsc.getAttribute(getSetName, "It");
    }

    if (!rzooby.getClass().getName().equals("Zooby")) {
        throw new Exception("FAILED: remote object is not a Zooby");
    }
    if (rzooby.getClass().getClassLoader() ==
            zooby.getClass().getClassLoader()) {
        throw new Exception("FAILED: same class loader: " +
                zooby.getClass().getClassLoader());
    }

    cc.close();
    cs.stop();
}
 
Example 23
Source Project: cougar   Source File: CougarHelpers.java    License: Apache License 2.0 5 votes vote down vote up
public JMXConnector createJMXConnector(String id) throws IOException,AgentLoadException,
								AgentInitializationException, AttachNotSupportedException {

	// attach to the target application
	VirtualMachine vm = VirtualMachine.attach(id);

	// get the connector address
	String connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);

	// no connector address, so we start the JMX agent
	if (connectorAddress == null) {
		String agent = vm.getSystemProperties()
				.getProperty("java.home")
				+ File.separator
				+ "lib"
				+ File.separator
				+ "management-agent.jar";
		vm.loadAgent(agent);

		// agent is started, get the connector address
		connectorAddress = vm.getAgentProperties().getProperty(CONNECTOR_ADDRESS);
	}

	// establish connection to connector server
	JMXServiceURL url = new JMXServiceURL(connectorAddress);
	return JMXConnectorFactory.connect(url);
}
 
Example 24
Source Project: digdag   Source File: ServerJmxIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyHikariCP()
        throws Exception
{
    assumeThat(server.isRemoteDatabase(), is(true));
    try (JMXConnector con = connectJmx(server)) {
        MBeanServerConnection beans = con.getMBeanServerConnection();

        Object leakDetectionThreshold = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "PoolConfig (HikariPool-1)"), "LeakDetectionThreshold");
        assertThat(leakDetectionThreshold, is(60000L));

        Object numConnection = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "Pool (HikariPool-1)"), "TotalConnections");
        assertTrue((int)numConnection >= 0);
    }
}
 
Example 25
Source Project: SuitAgent   Source File: JMXConnectWithTimeout.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * JMX连接
 * @param url
 * JMX连接地址
 * @param jmxUser
 * JMX授权用户 null为无授权用户
 * @param jmxPassword
 * JMX授权密码 null为无授权密码
 * @param timeout
 * 超时时间
 * @param unit
 * 超时单位
 * @return
 * @throws IOException
 */
public static JMXConnector connectWithTimeout( final JMXServiceURL url,String jmxUser,String jmxPassword, long timeout, TimeUnit unit) throws Exception {
    final BlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(1);
    ExecuteThreadUtil.execute(() -> {
        try {
            JMXConnector connector;
            if(jmxUser != null && jmxPassword != null){
                Map<String,Object> env = new HashMap<>();
                String[] credentials = new String[] { jmxUser, jmxPassword };
                env.put(JMXConnector.CREDENTIALS, credentials);
                connector = JMXConnectorFactory.connect(url,env);
            }else{
                connector = JMXConnectorFactory.connect(url,null);
            }
            if (!blockingQueue.offer(connector))
                connector.close();
        } catch (Throwable t) {
            blockingQueue.offer(t);
        }
    });

    Object result = BlockingQueueUtil.getResult(blockingQueue,timeout,unit);
    blockingQueue.clear();


    if (result instanceof JMXConnector){
        return (JMXConnector) result;
    }else if (result == null){
        throw new SocketTimeoutException("Connect timed out: " + url);
    }else if(result instanceof Throwable){
        throw new IOException("JMX Connect Failed : " + url,((Throwable) result));
    }
    return null;
}
 
Example 26
Source Project: JCoz   Source File: JCozServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public int attachToProcess(int localProcessId) throws RemoteException {
    logger.info("Attaching to process {}", localProcessId);
    try {
        for (VirtualMachineDescriptor desc : VirtualMachine.list()) {
            if (Integer.parseInt(desc.id()) == localProcessId) {
                VirtualMachine vm = VirtualMachine.attach(desc);
                vm.startLocalManagementAgent();
                Properties props = vm.getAgentProperties();
                String connectorAddress = props
                    .getProperty(CONNECTOR_ADDRESS_PROPERTY_KEY);
                JMXServiceURL url = new JMXServiceURL(connectorAddress);
                JMXConnector connector = JMXConnectorFactory.connect(url);
                MBeanServerConnection mbeanConn = connector
                    .getMBeanServerConnection();
                attachedVMs.put(localProcessId, JMX.newMXBeanProxy(mbeanConn,
                            JCozProfiler.getMBeanName(),
                            JCozProfilerMBean.class));
                return JCozProfilingErrorCodes.NORMAL_RETURN;
            }
        }
    } catch (IOException | NumberFormatException
            | AttachNotSupportedException e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        logger.error("Got an exception during attachToProcess, stacktrace: {}", stringWriter);
        throw new RemoteException("", e);

            }
    return JCozProfilingErrorCodes.INVALID_JAVA_PROCESS;
}
 
Example 27
public static void main(String[] args) throws Exception {
    JMXServiceURL inputAddr =
        new JMXServiceURL("service:jmx:iiop://");
    JMXConnectorServer s;
    try {
        s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
    } catch (java.net.MalformedURLException x) {
        try {
            Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
            throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
        } catch (ClassNotFoundException expected) { }
        System.out.println("IIOP protocol not supported, test skipped");
        return;
    }
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    mbs.registerMBean(s, new ObjectName("a:b=c"));
    s.start();
    JMXServiceURL outputAddr = s.getAddress();
    if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
        throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
                                   outputAddr);
    }
    System.out.println("IIOP URL path looks OK: " + outputAddr);
    JMXConnector c = JMXConnectorFactory.connect(outputAddr);
    System.out.println("Successfully got default domain: " +
                       c.getMBeanServerConnection().getDefaultDomain());
    c.close();
    s.stop();
}
 
Example 28
public JMXConnector newJMXConnector(JMXServiceURL url,
                                    Map<String,?> map)
    throws IOException {
    final String protocol = url.getProtocol();
    called = true;
    System.out.println("JMXConnectorProviderImpl called");

    if(protocol.equals("rmi"))
        return new RMIConnector(url, map);
    if(protocol.equals("throw-provider-exception"))
        throw new JMXProviderException("I have been asked to throw");

    throw new IllegalArgumentException("UNKNOWN PROTOCOL");
}
 
Example 29
public static void main(String[] args) throws Exception {
	AttachUtils.printJVMVersion();
	String pid = AttachUtils.checkPid(args);
	JMXConnector connector = JMXConnectorFactory.connect(AttachUtils.startLocalAgent(pid));
	MBeanServerConnection connection = connector.getMBeanServerConnection();
	List<GarbageCollectorMXBean> mBeans = getGarbageCollectorMBeans(connection, getGCNames(connection));

	registerNotifications(connection, mBeans);
	printInitGCStats(mBeans);

	System.out.println("Waiting for GC notifications!");
	System.out.println("Press <enter> to exit!");
	System.in.read();
}
 
Example 30
Source Project: kafka-eagle   Source File: KafkaServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get kafka os memory.
 */
public long getOSMemory(String host, int port, String property) {
	JMXConnector connector = null;
	long memory = 0L;
	String JMX = "service:jmx:rmi:///jndi/rmi://%s/jmxrmi";
	try {
		JMXServiceURL jmxSeriverUrl = new JMXServiceURL(String.format(JMX, host + ":" + port));
		connector = JMXFactoryUtils.connectWithTimeout(jmxSeriverUrl, 30, TimeUnit.SECONDS);
		MBeanServerConnection mbeanConnection = connector.getMBeanServerConnection();
		MemoryMXBean memBean = ManagementFactory.newPlatformMXBeanProxy(mbeanConnection, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
		long max = memBean.getHeapMemoryUsage().getMax();
		long used = memBean.getHeapMemoryUsage().getUsed();
		if (BrokerServer.TOTAL_PHYSICAL_MEMORY_SIZE.getValue().equals(property)) {
			memory = max;
		} else if (BrokerServer.FREE_PHYSICAL_MEMORY_SIZE.getValue().equals(property)) {
			memory = max - used;
		}
	} catch (Exception ex) {
		LOG.error("Get kafka os memory from jmx has error, msg is " + ex.getMessage());
	} finally {
		if (connector != null) {
			try {
				connector.close();
			} catch (IOException e) {
				LOG.error("Close kafka os memory jmx connector has error, msg is " + e.getMessage());
			}
		}
	}
	return memory;
}