下面列出了怎么用javax.management.MBeanOperationInfo的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Routes a method invocation (not a property get/set) to the corresponding
* operation on the managed resource.
* @param method the method corresponding to operation on the managed resource.
* @param args the invocation arguments
* @return the value returned by the method invocation.
*/
private Object invokeOperation(Method method, Object[] args) throws JMException, IOException {
MethodCacheKey key = new MethodCacheKey(method.getName(), method.getParameterTypes());
MBeanOperationInfo info = this.allowedOperations.get(key);
if (info == null) {
throw new InvalidInvocationException("Operation '" + method.getName() +
"' is not exposed on the management interface");
}
String[] signature = null;
synchronized (this.signatureCache) {
signature = this.signatureCache.get(method);
if (signature == null) {
signature = JmxUtils.getMethodSignature(method);
this.signatureCache.put(method, signature);
}
}
return this.serverToUse.invoke(this.objectName, method.getName(), args, signature);
}
/**
* adds a new address setting for a specific address
*/
@Operation(desc = "Add address settings for addresses matching the addressMatch", impact = MBeanOperationInfo.ACTION)
void addAddressSettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch,
@Parameter(desc = "the dead letter address setting", name = "DLA") String DLA,
@Parameter(desc = "the expiry address setting", name = "expiryAddress") String expiryAddress,
@Parameter(desc = "the expiry delay setting", name = "expiryDelay") long expiryDelay,
@Parameter(desc = "are any queues created for this address a last value queue", name = "lastValueQueue") boolean lastValueQueue,
@Parameter(desc = "the delivery attempts", name = "deliveryAttempts") int deliveryAttempts,
@Parameter(desc = "the max size in bytes", name = "maxSizeBytes") long maxSizeBytes,
@Parameter(desc = "the page size in bytes", name = "pageSizeBytes") int pageSizeBytes,
@Parameter(desc = "the max number of pages in the soft memory cache", name = "pageMaxCacheSize") int pageMaxCacheSize,
@Parameter(desc = "the redelivery delay", name = "redeliveryDelay") long redeliveryDelay,
@Parameter(desc = "the redelivery delay multiplier", name = "redeliveryMultiplier") double redeliveryMultiplier,
@Parameter(desc = "the maximum redelivery delay", name = "maxRedeliveryDelay") long maxRedeliveryDelay,
@Parameter(desc = "the redistribution delay", name = "redistributionDelay") long redistributionDelay,
@Parameter(desc = "do we send to the DLA when there is no where to route the message", name = "sendToDLAOnNoRoute") boolean sendToDLAOnNoRoute,
@Parameter(desc = "the policy to use when the address is full", name = "addressFullMessagePolicy") String addressFullMessagePolicy,
@Parameter(desc = "when a consumer falls below this threshold in terms of messages consumed per second it will be considered 'slow'", name = "slowConsumerThreshold") long slowConsumerThreshold,
@Parameter(desc = "how often (in seconds) to check for slow consumers", name = "slowConsumerCheckPeriod") long slowConsumerCheckPeriod,
@Parameter(desc = "the policy to use when a slow consumer is detected", name = "slowConsumerPolicy") String slowConsumerPolicy,
@Parameter(desc = "allow queues to be created automatically", name = "autoCreateJmsQueues") boolean autoCreateJmsQueues,
@Parameter(desc = "allow auto-created queues to be deleted automatically", name = "autoDeleteJmsQueues") boolean autoDeleteJmsQueues,
@Parameter(desc = "allow topics to be created automatically", name = "autoCreateJmsTopics") boolean autoCreateJmsTopics,
@Parameter(desc = "allow auto-created topics to be deleted automatically", name = "autoDeleteJmsTopics") boolean autoDeleteJmsTopics) throws Exception;
@Override
public MBeanInfo getMBeanInfo() {
MBeanParameterInfo[] withoutParamInfo = new MBeanParameterInfo[0];
MBeanAttributeInfo attributs[] = new MBeanAttributeInfo[value.size()];
int i = 0;
for (Entry<String, Long> entry : value.entrySet()) {
attributs[i] = new MBeanAttributeInfo(entry.getKey(), "long", "Timed of " + entry.getKey(), true, true, false);
i++;
}
MBeanConstructorInfo[] constructeurs = new MBeanConstructorInfo[1];
constructeurs[0] = new MBeanConstructorInfo("TimedJmxDynamicMBean", "Constructor by default", withoutParamInfo);
MBeanOperationInfo[] operations = new MBeanOperationInfo[1];
operations[0] = new MBeanOperationInfo("refresh", "Refresh data", withoutParamInfo, void.class.getName(), MBeanOperationInfo.ACTION);
return new MBeanInfo(getClass().getName(), "TimedJmxDynamicMBean", attributs, constructeurs, operations, null);
}
/** Find the operation info for a method
*
* @param oname
* @param opName
* @return the operation info for the specified operation
*/
public MBeanOperationInfo getMethodInfo( ObjectName oname, String opName )
{
MBeanInfo info=null;
try {
info=server.getMBeanInfo(oname);
} catch (Exception e) {
log.info( "Can't find metadata " + oname );
return null;
}
MBeanOperationInfo attInfo[]=info.getOperations();
for( int i=0; i<attInfo.length; i++ ) {
if( opName.equals(attInfo[i].getName())) {
return attInfo[i];
}
}
return null;
}
/** Find the operation info for a method
*
* @param oname
* @param opName
* @return the operation info for the specified operation
*/
public MBeanOperationInfo getMethodInfo( ObjectName oname, String opName )
{
MBeanInfo info=null;
try {
info=server.getMBeanInfo(oname);
} catch (Exception e) {
log.info( "Can't find metadata " + oname );
return null;
}
MBeanOperationInfo attInfo[]=info.getOperations();
for( int i=0; i<attInfo.length; i++ ) {
if( opName.equals(attInfo[i].getName())) {
return attInfo[i];
}
}
return null;
}
@Test
public void testHappyPath() throws MalformedObjectNameException, JMException {
TestMbean testMbean = new TestMbean();
ModelMBean mbean = defaultManagementMBeanAssembler.assemble(testMbean, new ObjectName("org.flowable.jmx.Mbeans:type=something"));
assertNotNull(mbean);
assertNotNull(mbean.getMBeanInfo());
assertNotNull(mbean.getMBeanInfo().getAttributes());
MBeanAttributeInfo[] attributes = mbean.getMBeanInfo().getAttributes();
assertEquals(2, attributes.length);
assertTrue((attributes[0].getName().equals("TestAttributeString") && attributes[1].getName().equals("TestAttributeBoolean") || (attributes[1].getName().equals("TestAttributeString") && attributes[0]
.getName().equals("TestAttributeBoolean"))));
assertNotNull(mbean.getMBeanInfo().getOperations());
MBeanOperationInfo[] operations = mbean.getMBeanInfo().getOperations();
assertNotNull(operations);
assertEquals(3, operations.length);
}
private void printMBeanInfo(MBeanInfo mbInfo) {
System.out.println("Description " + mbInfo.getDescription());
for (MBeanConstructorInfo ctor : mbInfo.getConstructors()) {
System.out.println("Constructor " + ctor.getName());
}
for (MBeanAttributeInfo att : mbInfo.getAttributes()) {
System.out.println("Attribute " + att.getName()
+ " [" + att.getType() + "]");
}
for (MBeanOperationInfo oper : mbInfo.getOperations()) {
System.out.println("Operation " + oper.getName());
}
for (MBeanNotificationInfo notif : mbInfo.getNotifications()) {
System.out.println("Notification " + notif.getName());
}
}
/**
* Description of the operation.
*
* @param operation the operation to describe
* @return pretty-printed description
*/
protected String describeOperation(MBeanOperationInfo operation) {
StringBuilder buf = new StringBuilder();
buf.append(operation.getReturnType())
.append(" ")
.append(operation.getName())
.append("(");
MBeanParameterInfo[] params = operation.getSignature();
for (int j = 0; j < params.length; j++) {
MBeanParameterInfo param = params[j];
if (j != 0) {
buf.append(", ");
}
buf.append(param.getType())
.append(" ")
.append(param.getName());
}
buf.append(")");
return buf.toString();
}
/** {@inheritDoc} */
@Override protected String getDescription(MBeanOperationInfo info) {
String str = super.getDescription(info);
try {
Method m = getMethod(info);
MXBeanDescription desc = m.getAnnotation(MXBeanDescription.class);
if (desc != null) {
str = desc.value();
assert str != null;
assert !str.trim().isEmpty();
// Enforce proper English.
assert Character.isUpperCase(str.charAt(0)) : DESC_MUST_START_WITH_UPP_CASE + str;
assert str.charAt(str.length() - 1) == '.' : DESC_MUST_END_WITH_PERIOD + str;
}
}
catch (SecurityException | ClassNotFoundException ignored) {
// No-op. Default value will be returned.
}
return str;
}
@Operation(desc = "Add security settings for addresses matching the addressMatch", impact = MBeanOperationInfo.ACTION)
void addSecuritySettings(@Parameter(desc = "an address match", name = "addressMatch") String addressMatch,
@Parameter(desc = "a comma-separated list of roles allowed to send messages", name = "send") String sendRoles,
@Parameter(desc = "a comma-separated list of roles allowed to consume messages", name = "consume") String consumeRoles,
@Parameter(desc = "a comma-separated list of roles allowed to create durable queues", name = "createDurableQueueRoles") String createDurableQueueRoles,
@Parameter(desc = "a comma-separated list of roles allowed to delete durable queues", name = "deleteDurableQueueRoles") String deleteDurableQueueRoles,
@Parameter(desc = "a comma-separated list of roles allowed to create non durable queues", name = "createNonDurableQueueRoles") String createNonDurableQueueRoles,
@Parameter(desc = "a comma-separated list of roles allowed to delete non durable queues", name = "deleteNonDurableQueueRoles") String deleteNonDurableQueueRoles,
@Parameter(desc = "a comma-separated list of roles allowed to send management messages messages", name = "manage") String manageRoles) throws Exception;
static private MBeanOperationInfo[] makeOpInfos(String[][] spec) {
final MBeanOperationInfo[] result =
new MBeanOperationInfo[spec.length];
final MBeanParameterInfo[] pars = makeParInfos(parameters);
for (int i=0;i<result.length;i++) {
System.out.println("\tCreate an MBeanOperationInfo: " +
spec[i][0]);
final MBeanOperationInfo item =
new MBeanOperationInfo(spec[i][2],spec[i][0],pars,spec[i][1],
MBeanOperationInfo.ACTION_INFO);
result[i]=item;
}
return result;
}
@Test
public void testSetNameParameterIsNamed() throws Exception {
ModelMBeanInfo info = getMBeanInfoFromAssembler();
MBeanOperationInfo operationSetAge = info.getOperation("setName");
assertEquals("name", operationSetAge.getSignature()[0].getName());
}
@Override
public MBeanInfo getMBeanInfo() {
MBeanAttributeInfo attr = new MBeanAttributeInfo("name", "java.lang.String", "", true, false, false);
return new MBeanInfo(
TestDynamicMBean.class.getName(), "",
new MBeanAttributeInfo[]{attr},
new MBeanConstructorInfo[0],
new MBeanOperationInfo[0],
new MBeanNotificationInfo[0]);
}
public static ObjectName getRequiredObjectName(ObjectName origName, ObjectName confName, String operationName, MBeanServerConnection in_conn){
ObjectName oName = null;
try{
if(origName != null){
MBeanInfo bnInfo = in_conn.getMBeanInfo(origName);
MBeanOperationInfo[] operInfo = bnInfo.getOperations();
String[] operNames = new String[operInfo.length];
for(int i=0; i<operInfo.length; i++){
operNames[i] = operInfo[i].getName();
}
Set operList = new HashSet(Arrays.asList(operNames));
if(operList.contains(operationName)){
oName = origName;
return oName;
}
}
MBeanInfo beanInfo = in_conn.getMBeanInfo(confName);
MBeanOperationInfo[] operationInfo = beanInfo.getOperations();
String[] operationNames = new String[operationInfo.length];
for(int i=0; i<operationInfo.length; i++){
operationNames[i] = operationInfo[i].getName();
}
Set newOperList = new HashSet(Arrays.asList(operationNames));
if(newOperList.contains(operationName)){
oName = confName;
}
}catch(Exception ex){
//System.out.println("Error in getRequiredObjectName " + ex.getLocalizedMessage());
return oName;
}
return oName;
}
public ModelMBeanOperationInfo getOperation(String inName)
throws MBeanException, RuntimeOperationsException {
ModelMBeanOperationInfo retInfo = null;
if (MODELMBEAN_LOGGER.isLoggable(Level.TRACE)) {
MODELMBEAN_LOGGER.log(Level.TRACE, "Entry");
}
if (inName == null) {
throw new RuntimeOperationsException(
new IllegalArgumentException("inName is null"),
"Exception occurred trying to get the " +
"ModelMBeanOperationInfo of the MBean");
}
MBeanOperationInfo[] operList = modelMBeanOperations; //this.getOperations();
int numOpers = 0;
if (operList != null) numOpers = operList.length;
for (int i=0; (i < numOpers) && (retInfo == null); i++) {
if (inName.equals(operList[i].getName())) {
retInfo = ((ModelMBeanOperationInfo) operList[i].clone());
}
}
if (MODELMBEAN_LOGGER.isLoggable(Level.TRACE)) {
MODELMBEAN_LOGGER.log(Level.TRACE, "Exit");
}
return retInfo;
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
/**
* Deserializes a {@link ModelMBeanInfoSupport} from an {@link ObjectInputStream}.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
if (compat) {
// Read an object serialized in the old serial form
//
ObjectInputStream.GetField fields = in.readFields();
modelMBeanDescriptor =
(Descriptor) fields.get("modelMBeanDescriptor", null);
if (fields.defaulted("modelMBeanDescriptor")) {
throw new NullPointerException("modelMBeanDescriptor");
}
modelMBeanAttributes =
(MBeanAttributeInfo[]) fields.get("mmbAttributes", null);
if (fields.defaulted("mmbAttributes")) {
throw new NullPointerException("mmbAttributes");
}
modelMBeanConstructors =
(MBeanConstructorInfo[]) fields.get("mmbConstructors", null);
if (fields.defaulted("mmbConstructors")) {
throw new NullPointerException("mmbConstructors");
}
modelMBeanNotifications =
(MBeanNotificationInfo[]) fields.get("mmbNotifications", null);
if (fields.defaulted("mmbNotifications")) {
throw new NullPointerException("mmbNotifications");
}
modelMBeanOperations =
(MBeanOperationInfo[]) fields.get("mmbOperations", null);
if (fields.defaulted("mmbOperations")) {
throw new NullPointerException("mmbOperations");
}
} else {
// Read an object serialized in the new serial form
//
in.defaultReadObject();
}
}
private static MBeanOperationInfo[]
operationArray(OpenMBeanOperationInfo[] src) {
if (src == null)
return null;
MBeanOperationInfo[] dst = new MBeanOperationInfo[src.length];
System.arraycopy(src, 0, dst, 0, src.length);
return dst;
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
protected static Object doBeanOperation(MBeanServerConnection mbsc, ObjectInstance instance, String command,
MBeanOperationInfo[] infos) throws Exception {
// Parse command line.
CommandParse parse = new CommandParse(command);
// Get first method of name 'cmd'. Assumption is no method
// overrides. Then, look at the method and use its signature
// to make sure client sends over parameters of the correct type.
MBeanOperationInfo op = (MBeanOperationInfo) getFeatureInfo(infos, parse.getCmd());
Object result = null;
if (op == null) {
result = "Operation " + parse.getCmd() + " not found.";
} else {
MBeanParameterInfo[] paraminfos = op.getSignature();
int paraminfosLength = (paraminfos == null) ? 0 : paraminfos.length;
int objsLength = (parse.getArgs() == null) ? 0 : parse.getArgs().length;
if (paraminfosLength != objsLength) {
result = "Passed param count does not match signature count";
} else {
String[] signature = new String[paraminfosLength];
Object[] params = (paraminfosLength == 0) ? null : new Object[paraminfosLength];
for (int i = 0; i < paraminfosLength; i++) {
MBeanParameterInfo paraminfo = paraminfos[i];
java.lang.reflect.Constructor c = Class.forName(paraminfo.getType())
.getConstructor(new Class[] { String.class });
params[i] = c.newInstance(new Object[] { parse.getArgs()[i] });
signature[i] = paraminfo.getType();
}
result = mbsc.invoke(instance.getObjectName(), parse.getCmd(), params, signature);
}
}
return result;
}
static private MBeanOperationInfo[] makeOpInfos(String[][] spec) {
final MBeanOperationInfo[] result =
new MBeanOperationInfo[spec.length];
final MBeanParameterInfo[] pars = makeParInfos(parameters);
for (int i=0;i<result.length;i++) {
System.out.println("\tCreate an MBeanOperationInfo: " +
spec[i][0]);
final MBeanOperationInfo item =
new MBeanOperationInfo(spec[i][2],spec[i][0],pars,spec[i][1],
MBeanOperationInfo.ACTION_INFO);
result[i]=item;
}
return result;
}
/** Make an MBeanInfo based on the attributes and operations
* found in the interface. */
MBeanInfo makeMBeanInfo(Class<?> mbeanInterface,
String description) {
final MBeanAttributeInfo[] attrArray =
attrs.toArray(new MBeanAttributeInfo[0]);
final MBeanOperationInfo[] opArray =
ops.toArray(new MBeanOperationInfo[0]);
final String interfaceClassName =
"interfaceClassName=" + mbeanInterface.getName();
final Descriptor classNameDescriptor =
new ImmutableDescriptor(interfaceClassName);
final Descriptor mbeanDescriptor = getBasicMBeanDescriptor();
final Descriptor annotatedDescriptor =
Introspector.descriptorForElement(mbeanInterface);
final Descriptor descriptor =
DescriptorCache.getInstance().union(
classNameDescriptor,
mbeanDescriptor,
annotatedDescriptor);
return new MBeanInfo(mbeanInterface.getName(),
description,
attrArray,
null,
opArray,
null,
descriptor);
}
static void printOperation(MBeanOperationInfo info) {
System.out.println("Name: "+info.getName());
System.out.println("Description: "+info.getDescription());
System.out.println("Return Type: "+info.getReturnType());
System.out.println("Impact: "+info.getImpact());
Descriptor desc = info.getDescriptor();
System.out.println("Descriptor");
for(int i=0; i<desc.getFieldNames().length; i++) {
if(desc.getFieldNames()[i].compareTo("dcmd.arguments") == 0) {
System.out.println("\t"+desc.getFieldNames()[i]+":");
Descriptor desc2 =
(Descriptor)desc.getFieldValue(desc.getFieldNames()[i]);
for(int j=0; j<desc2.getFieldNames().length; j++) {
System.out.println("\t\t"+desc2.getFieldNames()[j]+"=");
Descriptor desc3 =
(Descriptor)desc2.getFieldValue(desc2.getFieldNames()[j]);
for(int k=0; k<desc3.getFieldNames().length; k++) {
System.out.println("\t\t\t"+desc3.getFieldNames()[k]+"="
+desc3.getFieldValue(desc3.getFieldNames()[k]));
}
}
} else {
System.out.println("\t"+desc.getFieldNames()[i]+"="
+desc.getFieldValue(desc.getFieldNames()[i]));
}
}
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
/**
* Creates an instance of {@code ModelMBeanOperationInfo} for the
* given method. Populates the parameter info for the operation.
* @param method the {@code Method} to create a {@code ModelMBeanOperationInfo} for
* @param name the logical name for the operation (method name or property name);
* not used by the default implementation but possibly by subclasses
* @param beanKey the key associated with the MBean in the beans map
* of the {@code MBeanExporter}
* @return the {@code ModelMBeanOperationInfo}
*/
protected ModelMBeanOperationInfo createModelMBeanOperationInfo(Method method, String name, String beanKey) {
MBeanParameterInfo[] params = getOperationParameters(method, beanKey);
if (params.length == 0) {
return new ModelMBeanOperationInfo(getOperationDescription(method, beanKey), method);
}
else {
return new ModelMBeanOperationInfo(method.getName(),
getOperationDescription(method, beanKey),
getOperationParameters(method, beanKey),
method.getReturnType().getName(),
MBeanOperationInfo.UNKNOWN);
}
}
private static void check(MBeanServer mbs, ObjectName on) throws Exception {
MBeanInfo mbi = mbs.getMBeanInfo(on);
// check the MBean itself
check(mbi);
// check attributes
MBeanAttributeInfo[] attrs = mbi.getAttributes();
for (MBeanAttributeInfo attr : attrs) {
check(attr);
if (attr.getName().equals("ReadOnly"))
check("@Full", attr.getDescriptor(), expectedFullDescriptor);
}
// check operations
MBeanOperationInfo[] ops = mbi.getOperations();
for (MBeanOperationInfo op : ops) {
check(op);
check(op.getSignature());
}
MBeanConstructorInfo[] constrs = mbi.getConstructors();
for (MBeanConstructorInfo constr : constrs) {
check(constr);
check(constr.getSignature());
}
}
public static void main(String[] args) throws Exception {
System.out.println("--->JRCMD MBean Test: invocation on \"operation info\"...");
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
JMXConnectorServer cs = null;
JMXConnector cc = null;
try {
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
ObjectName name = new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME);
MBeanInfo info = mbsc.getMBeanInfo(name);
// the test should check that the MBean doesn't have any
// Attribute, notification or constructor. Current version only
// check operations
System.out.println("Class Name:" + info.getClassName());
System.out.println("Description:" + info.getDescription());
MBeanOperationInfo[] opInfo = info.getOperations();
System.out.println("Operations:");
for (int i = 0; i < opInfo.length; i++) {
printOperation(opInfo[i]);
System.out.println("\[email protected]@@@@@\n");
}
} finally {
try {
cc.close();
cs.stop();
} catch (Exception e) {
}
}
System.out.println("Test passed");
}
private static void doExploit ( final Object payloadObject, MBeanServerConnection mbc )
throws IOException, InstanceNotFoundException, IntrospectionException, ReflectionException {
Object[] params = new Object[1];
params[ 0 ] = payloadObject;
System.err.println("Querying MBeans");
Set<ObjectInstance> testMBeans = mbc.queryMBeans(null, null);
System.err.println("Found " + testMBeans.size() + " MBeans");
for ( ObjectInstance oi : testMBeans ) {
MBeanInfo mBeanInfo = mbc.getMBeanInfo(oi.getObjectName());
for ( MBeanOperationInfo opInfo : mBeanInfo.getOperations() ) {
try {
mbc.invoke(oi.getObjectName(), opInfo.getName(), params, new String[] {});
System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> SUCCESS");
return;
}
catch ( Throwable e ) {
String msg = e.getMessage();
if ( msg.startsWith("java.lang.ClassNotFoundException:") ) {
int start = msg.indexOf('"');
int stop = msg.indexOf('"', start + 1);
String module = ( start >= 0 && stop > 0 ) ? msg.substring(start + 1, stop) : "<unknown>";
if ( !"<unknown>".equals(module) && !"org.jboss.as.jmx:main".equals(module) ) {
int cstart = msg.indexOf(':');
int cend = msg.indexOf(' ', cstart + 2);
String cls = msg.substring(cstart + 2, cend);
System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> FAIL CNFE " + cls + " (" + module + ")");
}
}
else {
System.err.println(oi.getObjectName() + ":" + opInfo.getName() + " -> SUCCESS|ERROR " + msg);
return;
}
}
}
}
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
public static void main(String[] args) throws Exception {
System.out.println("--->JRCMD MBean Test: invocation on \"operation info\"...");
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
JMXConnectorServer cs = null;
JMXConnector cc = null;
try {
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
ObjectName name = new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME);
MBeanInfo info = mbsc.getMBeanInfo(name);
// the test should check that the MBean doesn't have any
// Attribute, notification or constructor. Current version only
// check operations
System.out.println("Class Name:" + info.getClassName());
System.out.println("Description:" + info.getDescription());
MBeanOperationInfo[] opInfo = info.getOperations();
System.out.println("Operations:");
for (int i = 0; i < opInfo.length; i++) {
printOperation(opInfo[i]);
System.out.println("\[email protected]@@@@@\n");
}
} finally {
try {
cc.close();
cs.stop();
} catch (Exception e) {
}
}
System.out.println("Test passed");
}