Skip to content

Instantly share code, notes, and snippets.

@mchirico
Created June 26, 2014 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mchirico/f4fc1de33922e1572f49 to your computer and use it in GitHub Desktop.
Save mchirico/f4fc1de33922e1572f49 to your computer and use it in GitHub Desktop.
Java example working with tools
package dev.sysadmin;
import java.lang.management.*;
import java.io.*;
import java.util.*;
import javax.management.*;
import javax.management.remote.*;
import com.sun.tools.attach.*;
import javax.management.openmbean.CompositeData;
public class Mjcon {
public static void main(String[] args) {
// TODO Auto-generated method stub
if (args.length != 1) {
System.err.println("Please provide process id");
System.exit(-1);
}
try {
VirtualMachine vm = VirtualMachine.attach(args[0]);
//VirtualMachine vm = VirtualMachine.attach("18237");
String connectorAddr = vm.getAgentProperties().getProperty(
"com.sun.management.jmxremote.localConnectorAddress");
if (connectorAddr == null) {
String agent = vm.getSystemProperties().getProperty(
"java.home")+File.separator+"lib"+File.separator+
"management-agent.jar";
vm.loadAgent(agent);
connectorAddr = vm.getAgentProperties().getProperty(
"com.sun.management.jmxremote.localConnectorAddress");
}
JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
MBeanServerConnection mbsc = connector.getMBeanServerConnection();
ObjectName simple = new ObjectName("com.example:type=Hello");
String simpleClass = "com.example.HelloMBean";
System.out.println("Here: "+mbsc.getAttribute(simple, "Name"));
mbsc.invoke(simple, "sayHello", null, null);
} catch (Exception e){
System.out.println(e.toString());
}
System.out.println("test");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment