下面列出了怎么用javax.management.ObjectInstance的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName) throws ReflectionException,
InstanceAlreadyExistsException, MBeanException, NotCompliantMBeanException,
InstanceNotFoundException {
Throwable error = null;
MBeanServerPlugin delegate = null;
final boolean readOnly = false;
try {
delegate = findDelegateForNewObject(name);
authorizeMBeanOperation(delegate, name, CREATE_MBEAN, null, JmxAction.Impact.WRITE);
return checkNotAReservedDomainRegistrationIfObjectNameWasChanged(name, delegate.createMBean(className, name, loaderName), delegate);
} catch (Exception e) {
error = e;
if (e instanceof ReflectionException) throw (ReflectionException)e;
if (e instanceof InstanceAlreadyExistsException) throw (InstanceAlreadyExistsException)e;
if (e instanceof MBeanException) throw (MBeanException)e;
if (e instanceof NotCompliantMBeanException) throw (NotCompliantMBeanException)e;
if (e instanceof InstanceNotFoundException) throw (InstanceNotFoundException)e;
throw makeRuntimeException(e);
} finally {
if (shouldAuditLog(delegate, readOnly)) {
new MBeanServerAuditLogRecordFormatter(this, error, readOnly).createMBean(className, name, loaderName);
}
}
}
public ObjectInstance registerMBean(Object object, ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException,
NotCompliantMBeanException {
// ------------------------------
// ------------------------------
Class<?> theClass = object.getClass();
Introspector.checkCompliance(theClass);
final String infoClassName = getNewMBeanClassName(object);
checkMBeanPermission(infoClassName, null, name, "registerMBean");
checkMBeanTrustPermission(theClass);
return registerObject(infoClassName, object, name);
}
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
Set<ObjectInstance> instances = newSet();
if (name == null)
name = ObjectName.WILDCARD;
if (query == null)
query = trueQuery;
MBeanServer oldMBS = QueryEval.getMBeanServer();
try {
query.setMBeanServer(this);
for (ObjectName n : mbeans.keySet()) {
if (name.apply(n)) {
try {
if (query.apply(n))
instances.add(getObjectInstance(n));
} catch (Exception e) {
// OK: Ignore this MBean in the result
}
}
}
} finally {
query.setMBeanServer(oldMBS);
}
return instances;
}
/** Before.
* @throws JMException e */
@Before
public void setUp() throws JMException {
Utils.initialize();
mbeans = new MBeans();
mBeanServer = MBeans.getPlatformMBeanServer();
final ObjectInstance mBean1 = mBeanServer.registerMBean(new ThreadPool(),
new ObjectName("Catalina:type=ThreadPool"));
mbeansList.add(mBean1.getObjectName());
final ObjectInstance mBean2 = mBeanServer.registerMBean(new GlobalRequestProcessor(),
new ObjectName("Catalina:type=GlobalRequestProcessor,name=http-8080"));
mbeansList.add(mBean2.getObjectName());
final ObjectInstance mBean3 = mBeanServer.registerMBean(new GlobalRequestProcessor(),
new ObjectName("jboss.deployment:type=Servlet"));
mbeansList.add(mBean3.getObjectName());
}
public ObjectInstance createMBean(String className, ObjectName name,
Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException {
try {
return createMBean(className, name, null, true,
params, signature);
} catch (InstanceNotFoundException e) {
/* Can only happen if loaderName doesn't exist, but we just
passed null, so we shouldn't get this exception. */
throw EnvHelp.initCause(
new IllegalArgumentException("Unexpected exception: " + e), e);
}
}
/**
* @see javax.management.MBeanServerConnection#getObjectInstance(javax.management.ObjectName)
*/
public ObjectInstance getObjectInstance(final ObjectName name) throws InstanceNotFoundException, IOException {
if (this.subject == null) {
return this.mbs.getObjectInstance(name);
}
try {
return (ObjectInstance) Subject.doAsPrivileged(this.subject,
new PrivilegedExceptionAction<ObjectInstance>() {
public final ObjectInstance run() throws Exception {
return mbs.getObjectInstance(name);
}
},
this.context);
} catch (final PrivilegedActionException pe) {
final Exception e = JMXProviderUtils.extractException(pe);
if (e instanceof InstanceNotFoundException)
throw (InstanceNotFoundException) e;
if (e instanceof IOException)
throw (IOException) e;
throw JMXProviderUtils.newIOException("Got unexpected server exception: " + e, e);
}
}
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
Set<ObjectInstance> instances = newSet();
if (name == null)
name = ObjectName.WILDCARD;
if (query == null)
query = trueQuery;
MBeanServer oldMBS = QueryEval.getMBeanServer();
try {
query.setMBeanServer(this);
for (ObjectName n : mbeans.keySet()) {
if (name.apply(n)) {
try {
if (query.apply(n))
instances.add(getObjectInstance(n));
} catch (Exception e) {
// OK: Ignore this MBean in the result
}
}
}
} finally {
query.setMBeanServer(oldMBS);
}
return instances;
}
/**
* Call <code>checkCreate(className)</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance createMBean(String className, ObjectName name)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException {
checkCreate(className);
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
Object object = getMBeanServer().instantiate(className);
checkClassLoader(object);
return getMBeanServer().registerMBean(object, name);
} else {
return getMBeanServer().createMBean(className, name);
}
}
private void checkMemberView(boolean expectedBeans,
MBeanServerConnection mbeanServer, String memberId, String serverGroup)
throws MalformedObjectNameException, IOException, TestException {
Log.getLogWriter().info("Checking GFXDMemberMBean for server group " + serverGroup + " and memberId : " + memberId);
String memberONstr = memberONTemplate.replace("{0}", serverGroup);
memberONstr = memberONstr.replace("{1}", memberId);
ObjectName memberON = new ObjectName(memberONstr);
// check memberMBean
Log.getLogWriter().info("Querying for member instance " + memberON);
try {
ObjectInstance instance = mbeanServer.getObjectInstance(memberON);
Log.getLogWriter().info("Found instance " + memberON + " Expected " + expectedBeans);
if (!expectedBeans && instance != null)
throw new TestException("Found member instance " + memberON + " when not expected ");
} catch (InstanceNotFoundException e) {
if (expectedBeans) {
logMBeans(MessageFormat.format(ManagementConstants.OBJECTNAME__GFXDMEMBER_MXBEAN, new Object[] {"*", "*"}), mbeanServer);
throw new TestException("checkMemberViewFromManager\n" + TestHelper.getStackTrace(e));
}
}
}
public ObjectInstance registerMBean(Object object, ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException,
NotCompliantMBeanException {
// ------------------------------
// ------------------------------
Class<?> theClass = object.getClass();
Introspector.checkCompliance(theClass);
final String infoClassName = getNewMBeanClassName(object);
checkMBeanPermission(infoClassName, null, name, "registerMBean");
checkMBeanTrustPermission(theClass);
return registerObject(infoClassName, object, name);
}
public Set<ObjectInstance> queryMBeans(ObjectName name,
QueryExp query)
throws IOException {
if (logger.debugOn()) logger.debug("queryMBeans",
"name=" + name + ", query=" + query);
final MarshalledObject<QueryExp> sQuery =
new MarshalledObject<QueryExp>(query);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.queryMBeans(name, sQuery, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.queryMBeans(name, sQuery, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
/**
* This test ensures that the queueViewMbean will work.
*
* @throws Exception
*/
public void testQueueViewMbean() throws Exception {
try {
addMessages();
validateCounts(MESSAGE_COUNT, MESSAGE_COUNT, MESSAGE_COUNT * 2);
List<String> tokens = Arrays.asList(new String[]{"*"});
for (String token : tokens) {
List<ObjectInstance> queueList = JmxMBeansUtil.queryMBeans(createJmxConnection(), "type=Broker,brokerName=localbroker,destinationType=Queue,destinationName=" + token);
for (ObjectInstance queue : queueList) {
ObjectName queueName = queue.getObjectName();
QueueViewMBean proxy = MBeanServerInvocationHandler.newProxyInstance(createJmxConnection(), queueName, QueueViewMBean.class, true);
int removed = proxy.removeMatchingMessages(MSG_SEL_WITH_PROPERTY);
LOG.info("Removed: " + removed);
}
}
validateCounts(0, MESSAGE_COUNT, MESSAGE_COUNT);
} finally {
purgeAllMessages();
}
}
/**
* Call <code>checkCreate(className)</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance createMBean(String className, ObjectName name)
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException {
checkCreate(className);
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
Object object = getMBeanServer().instantiate(className);
checkClassLoader(object);
return getMBeanServer().registerMBean(object, name);
} else {
return getMBeanServer().createMBean(className, name);
}
}
/**
* Call <code>checkCreate(className)</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance createMBean(String className, ObjectName name,
Object params[], String signature[])
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException {
checkCreate(className);
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
Object object = getMBeanServer().instantiate(className,
params,
signature);
checkClassLoader(object);
return getMBeanServer().registerMBean(object, name);
} else {
return getMBeanServer().createMBean(className, name,
params, signature);
}
}
public ObjectInstance registerMBean(Object object, ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException,
NotCompliantMBeanException {
// ------------------------------
// ------------------------------
Class<?> theClass = object.getClass();
Introspector.checkCompliance(theClass);
final String infoClassName = getNewMBeanClassName(object);
checkMBeanPermission(infoClassName, null, name, "registerMBean");
checkMBeanTrustPermission(theClass);
return registerObject(infoClassName, object, name);
}
public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
Set<ObjectInstance> instances = newSet();
if (name == null)
name = ObjectName.WILDCARD;
if (query == null)
query = trueQuery;
MBeanServer oldMBS = QueryEval.getMBeanServer();
try {
query.setMBeanServer(this);
for (ObjectName n : mbeans.keySet()) {
if (name.apply(n)) {
try {
if (query.apply(n))
instances.add(getObjectInstance(n));
} catch (Exception e) {
// OK: Ignore this MBean in the result
}
}
}
} finally {
query.setMBeanServer(oldMBS);
}
return instances;
}
public ObjectInstance createMBean(String className, ObjectName name,
Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException {
try {
return createMBean(className, name, null, true,
params, signature);
} catch (InstanceNotFoundException e) {
/* Can only happen if loaderName doesn't exist, but we just
passed null, so we shouldn't get this exception. */
throw EnvHelp.initCause(
new IllegalArgumentException("Unexpected exception: " + e), e);
}
}
/**
* Call <code>checkCreate(className)</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance createMBean(String className, ObjectName name,
Object params[], String signature[])
throws
ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException {
checkCreate(className);
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
Object object = getMBeanServer().instantiate(className,
params,
signature);
checkClassLoader(object);
return getMBeanServer().registerMBean(object, name);
} else {
return getMBeanServer().createMBean(className, name,
params, signature);
}
}
/**
* Call <code>checkWrite()</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance registerMBean(Object object, ObjectName name)
throws
InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
checkWrite();
return getMBeanServer().registerMBean(object, name);
}
@Test
public void testJmxRegistration() throws Exception {
assertTrue("No MBeans found in server", mbeanServer.getMBeanCount() > 0);
Set<ObjectInstance> objects = mbeanServer.queryMBeans(null, null);
assertFalse("No objects found in mbean server", objects
.isEmpty());
int numDynamicMbeans = 0;
for (ObjectInstance o : objects) {
ObjectName name = o.getObjectName();
assertNotNull("Null name on: " + o.toString(), name);
MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(name);
if (name.getDomain().equals("solr")) {
numDynamicMbeans++;
MBeanAttributeInfo[] attrs = mbeanInfo.getAttributes();
if (name.getKeyProperty("name").equals("fetcher")) { // no attributes without active replication
continue;
}
assertTrue("No Attributes found for mbean: " + o.getObjectName() + ", " + mbeanInfo,
0 < attrs.length);
for (MBeanAttributeInfo attr : attrs) {
// ensure every advertised attribute is gettable
try {
Object trash = mbeanServer.getAttribute(o.getObjectName(), attr.getName());
} catch (javax.management.AttributeNotFoundException e) {
throw new RuntimeException("Unable to featch attribute for " + o.getObjectName()
+ ": " + attr.getName(), e);
}
}
}
}
assertTrue("No MBeans found", 0 < numDynamicMbeans);
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName,ObjectName)",
"className=" + className + ", name="
+ name + ", loaderName="
+ loaderName + ")");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
/**
* Applies the specified queries to the set of ObjectInstances.
*/
private Set<ObjectInstance>
filterListOfObjectInstances(Set<ObjectInstance> list,
QueryExp query) {
// Null query.
//
if (query == null) {
return list;
} else {
Set<ObjectInstance> result = new HashSet<ObjectInstance>();
// Access the filter.
//
for (ObjectInstance oi : list) {
boolean res = false;
MBeanServer oldServer = QueryEval.getMBeanServer();
query.setMBeanServer(server);
try {
res = query.apply(oi.getObjectName());
} catch (Exception e) {
res = false;
} finally {
/*
* query.setMBeanServer is probably
* QueryEval.setMBeanServer so put back the old
* value. Since that method uses a ThreadLocal
* variable, this code is only needed for the
* unusual case where the user creates a custom
* QueryExp that calls a nested query on another
* MBeanServer.
*/
query.setMBeanServer(oldServer);
}
if (res) {
result.add(oi);
}
}
return result;
}
}
private void verifyHelixManagerMetrics(InstanceType type, MonitorLevel monitorLevel,
String instanceName) throws MalformedObjectNameException {
// check HelixCallback Monitor
Set<ObjectInstance> objs =
_server.queryMBeans(buildCallbackMonitorObjectName(type, clusterName, instanceName), null);
Assert.assertEquals(objs.size(), 18);
// check HelixZkClient Monitors
objs =
_server.queryMBeans(buildZkClientMonitorObjectName(type, clusterName, instanceName), null);
Assert.assertEquals(objs.size(), 1);
objs = _server.queryMBeans(buildZkClientPathMonitorObjectName(type, clusterName, instanceName),
null);
int expectedZkPathMonitor;
switch (monitorLevel) {
case ALL:
expectedZkPathMonitor = 10;
break;
case AGGREGATED_ONLY:
expectedZkPathMonitor = 1;
break;
default:
expectedZkPathMonitor =
type == InstanceType.CONTROLLER || type == InstanceType.CONTROLLER_PARTICIPANT ? 10 : 1;
}
Assert.assertEquals(objs.size(), expectedZkPathMonitor);
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName,
Object params[],
String signature[])
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
if (logger.debugOn()) logger.debug(
"createMBean(String,ObjectName,ObjectName,Object[],String[])",
"className=" + className + ", name=" + name + ", loaderName="
+ loaderName + ", signature=" + strings(signature));
final MarshalledObject<Object[]> sParams =
new MarshalledObject<Object[]>(params);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
loaderName,
sParams,
signature,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
loaderName,
sParams,
signature,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
@Override
public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException,
InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException {
Boolean originalValue = AUTHORIZING.get();
try {
AUTHORIZING.set(Boolean.TRUE);
return delegate.createMBean(className, name);
} finally {
AUTHORIZING.set(originalValue);
}
}
/**
* Call <code>checkWrite()</code>, then forward this method to the
* wrapped object.
*/
public ObjectInstance registerMBean(Object object, ObjectName name)
throws
InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
checkWrite();
return getMBeanServer().registerMBean(object, name);
}
private void unregisterMBean(ObjectName originalObjectName) throws InstanceNotFoundException, MBeanRegistrationException {
ObjectName objectName = registered.remove(originalObjectName);
if (objectName == null) {
objectName = originalObjectName;
}
Set<ObjectInstance> objects = mBeanServer.queryMBeans(objectName, exp);
for (ObjectInstance o : objects) {
if (log.isDebugEnabled()) {
log.debug("## Unregistered {}, tag={}", o.getObjectName().getCanonicalName(), tag);
}
mBeanServer.unregisterMBean(o.getObjectName());
}
}
public static void main(String[] args) throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
for (Class<?> c : new Class<?>[] {
Spume.class, Thing.class, XSpume.class, XThing.class
}) {
for (ObjectName n : new ObjectName[] {null, new ObjectName("a:b=c")}) {
System.out.println("Class " + c.getName() + " with name " + n +
"...");
ObjectName realName = new ObjectName("a:type=" + c.getName());
Constructor<?> constr = c.getConstructor(ObjectName.class);
Object mbean = constr.newInstance(realName);
ObjectInstance oi;
String what =
"Registering MBean of type " + c.getName() + " under name " +
"<" + n + ">: ";
try {
oi = mbs.registerMBean(mbean, n);
} catch (Exception e) {
e.printStackTrace();
fail(what + " got " + e);
continue;
}
ObjectName registeredName = oi.getObjectName();
if (!registeredName.equals(realName))
fail(what + " registered as " + registeredName);
if (!mbs.isRegistered(realName)) {
fail(what + " not registered as expected");
}
mbs.unregisterMBean(registeredName);
}
}
System.err.flush();
if (failures == 0)
System.out.println("TEST PASSED");
else
throw new Exception("TEST FAILED: " + failure);
}
public ObjectInstance createMBean(String className,
ObjectName name,
ObjectName loaderName)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName,ObjectName)",
"className=" + className + ", name="
+ name + ", loaderName="
+ loaderName + ")");
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
loaderName,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName,
Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException {
return createMBean(className, name, loaderName, false,
params, signature);
}