Last active
September 4, 2015 17:11
-
-
Save bassemZohdy/e1dbeb1e6125ba71c33c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import javax.management.AttributeNotFoundException; | |
import javax.management.InstanceNotFoundException; | |
import javax.management.MBeanException; | |
import javax.management.MBeanServerConnection; | |
import javax.management.MalformedObjectNameException; | |
import javax.management.ObjectName; | |
import javax.management.ReflectionException; | |
import javax.management.remote.JMXConnector; | |
import javax.management.remote.JMXConnectorFactory; | |
import javax.management.remote.JMXServiceURL; | |
import com.sun.tools.attach.AgentInitializationException; | |
import com.sun.tools.attach.AgentLoadException; | |
import com.sun.tools.attach.AttachNotSupportedException; | |
import com.sun.tools.attach.VirtualMachine; | |
import com.sun.tools.attach.VirtualMachineDescriptor; | |
import com.sun.tools.attach.spi.AttachProvider; | |
public class CallJMXByProcessId { | |
public static void main(String[] args) throws AttachNotSupportedException, | |
IOException, AgentLoadException, AgentInitializationException, | |
MalformedObjectNameException, AttributeNotFoundException, | |
InstanceNotFoundException, MBeanException, ReflectionException { | |
final AttachProvider attachProvider = AttachProvider.providers().get(0); | |
VirtualMachineDescriptor descriptor = null; | |
for (VirtualMachineDescriptor virtualMachineDescriptor : attachProvider | |
.listVirtualMachines()) { | |
if (virtualMachineDescriptor.id().equals("12858")) // process Id | |
descriptor = virtualMachineDescriptor; | |
} | |
final VirtualMachine virtualMachine = attachProvider | |
.attachVirtualMachine(descriptor); | |
virtualMachine.loadAgent( | |
"/usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar", | |
"com.sun.management.jmxremote"); | |
final Object portObject = virtualMachine.getAgentProperties().get( | |
"com.sun.management.jmxremote.localConnectorAddress"); | |
final JMXServiceURL target = new JMXServiceURL(portObject + ""); | |
final JMXConnector connector = JMXConnectorFactory.connect(target); | |
final MBeanServerConnection remote = connector | |
.getMBeanServerConnection(); | |
final ObjectName objectName = new ObjectName( | |
"spring:name=MyManagedBean"); | |
String value = (String) remote.getAttribute(objectName, "Name"); | |
System.out.println(value); | |
remote.invoke(objectName, "setName", new Object[] { "new new new" }, | |
new String[] { "java.lang.String" }); | |
value = (String) remote.getAttribute(objectName, "Name"); | |
System.out.println(value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment