Skip to content

Instantly share code, notes, and snippets.

@andy722
Last active September 8, 2020 10:50
Show Gist options
  • Save andy722/6ad77505b868326a389b2b56d6bdad8f to your computer and use it in GitHub Desktop.
Save andy722/6ad77505b868326a389b2b56d6bdad8f to your computer and use it in GitHub Desktop.
Simple script to call JMX methods
import javax.management.MBeanServerConnection
import javax.management.ObjectName
import javax.management.remote.JMXConnector
import javax.management.remote.JMXConnectorFactory
import javax.management.remote.JMXServiceURL
final findBean = { MBeanServerConnection server,
String beanName ->
server.queryMBeans(null, null).find { it.name.serializedNameString.contains beanName }
}
final asObjectName = { MBeanServerConnection server,
String beanName ->
try {
final _ = ObjectName.getInstance(beanName)
server.getMBeanInfo _
return _
} catch (ignored) {
final _ = findBean server, beanName
println "Discovered bean name = [$_.objectName]"
return _.objectName
}
}
final call = { String serverUrl,
String beanName,
String methodName,
Object[] args = null,
String[] signature = null ->
JMXConnectorFactory.connect(new JMXServiceURL(serverUrl)).withCloseable { connector ->
final server = (connector as JMXConnector).MBeanServerConnection
final objName = asObjectName server, beanName
println server.invoke(objName, methodName, args, signature)
}
}
final getProperty = { String serverUrl, String beanName, String propertyName ->
JMXConnectorFactory.connect(new JMXServiceURL(serverUrl)).withCloseable { connector ->
final server = (connector as JMXConnector).MBeanServerConnection
final bean = new GroovyMBean(server, beanName)
println bean.getProperty(propertyName)
}
}
// TODO: replace with correct service URL.
final RMI_SERVER = 'service:jmx:rmi:///jndi/rmi://40.30.20.10:11997/jmxrmi'
// Example 1: call method with parameters.
call(
RMI_SERVER,
'com.example:name=SmtpSender',
'testSend',
['[email protected]', 'test', 'test'] as Object[],
[String.class.name, String.class.name, String.class.name] as String[]
)
// Example 2: lookup bean by type, not name.
call RMI_SERVER, 'com.example:type=DataSourceMBean', 'getRemainingConnections'
// Example 3: get bean property.
getProperty RMI_SERVER, 'com.example:name=MyBean', 'nErrors'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment