下面列出了怎么用javax.management.DynamicMBean的API类实例代码及写法,或者点击链接到github查看源代码。
private NotificationListener getListener(ObjectName listener)
throws ListenerNotFoundException {
// ----------------
// Get listener object
// ----------------
DynamicMBean instance;
try {
instance = getMBean(listener);
} catch (InstanceNotFoundException e) {
throw EnvHelp.initCause(
new ListenerNotFoundException(e.getMessage()), e);
}
Object resource = getResource(instance);
if (!(resource instanceof NotificationListener)) {
final RuntimeException exc =
new IllegalArgumentException(listener.getCanonicalName());
final String msg =
"MBean " + listener.getCanonicalName() + " does not " +
"implement " + NotificationListener.class.getName();
throw new RuntimeOperationsException(exc, msg);
}
return (NotificationListener) resource;
}
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException {
name = nonDefaultDomain(name);
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, operationName, name, "invoke");
try {
return instance.invoke(operationName, params, signature);
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError();
}
}
/**
* Create, register, and return an MBean for this
* <code>User</code> object.
*
* @param user The User to be managed
* @return a new MBean
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(User user)
throws Exception {
String mname = createManagedName(user);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(user);
ObjectName oname = createObjectName(domain, user);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return mbean;
}
private static void postRegister(
ObjectName logicalName, DynamicMBean mbean,
boolean registrationDone, boolean registerFailed) {
if (registerFailed && mbean instanceof DynamicMBean2)
((DynamicMBean2) mbean).registerFailed();
try {
if (mbean instanceof MBeanRegistration)
((MBeanRegistration) mbean).postRegister(registrationDone);
} catch (RuntimeException e) {
MBEANSERVER_LOGGER.fine("While registering MBean ["+logicalName+
"]: " + "Exception thrown by postRegister: " +
"rethrowing <"+e+">, but keeping the MBean registered");
throw new RuntimeMBeanException(e,
"RuntimeException thrown in postRegister method: "+
"rethrowing <"+e+">, but keeping the MBean registered");
} catch (Error er) {
MBEANSERVER_LOGGER.fine("While registering MBean ["+logicalName+
"]: " + "Error thrown by postRegister: " +
"rethrowing <"+er+">, but keeping the MBean registered");
throw new RuntimeErrorException(er,
"Error thrown in postRegister method: "+
"rethrowing <"+er+">, but keeping the MBean registered");
}
}
private static String getNewMBeanClassName(Object mbeanToRegister)
throws NotCompliantMBeanException {
if (mbeanToRegister instanceof DynamicMBean) {
DynamicMBean mbean = (DynamicMBean) mbeanToRegister;
final String name;
try {
name = mbean.getMBeanInfo().getClassName();
} catch (Exception e) {
// Includes case where getMBeanInfo() returns null
NotCompliantMBeanException ncmbe =
new NotCompliantMBeanException("Bad getMBeanInfo()");
ncmbe.initCause(e);
throw ncmbe;
}
if (name == null) {
final String msg = "MBeanInfo has null class name";
throw new NotCompliantMBeanException(msg);
}
return name;
} else
return mbeanToRegister.getClass().getName();
}
private NotificationListener getListenerWrapper(NotificationListener l,
ObjectName name,
DynamicMBean mbean,
boolean create) {
Object resource = getResource(mbean);
ListenerWrapper wrapper = new ListenerWrapper(l, name, resource);
synchronized (listenerWrappers) {
WeakReference<ListenerWrapper> ref = listenerWrappers.get(wrapper);
if (ref != null) {
NotificationListener existing = ref.get();
if (existing != null)
return existing;
}
if (create) {
ref = new WeakReference<ListenerWrapper>(wrapper);
listenerWrappers.put(wrapper, ref);
return wrapper;
} else
return null;
}
}
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException {
name = nonDefaultDomain(name);
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, operationName, name, "invoke");
try {
return instance.invoke(operationName, params, signature);
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError();
}
}
/**
* Retrieves the MBean of the name specified from the repository. The
* object name must match exactly.
*
* @param name name of the MBean to retrieve.
*
* @return The retrieved MBean if it is contained in the repository,
* null otherwise.
*/
public DynamicMBean retrieve(ObjectName name) {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER, Repository.class.getName(),
"retrieve", "name = " + name);
}
// Calls internal retrieve method to get the named object
lock.readLock().lock();
try {
NamedObject no = retrieveNamedObject(name);
if (no == null) return null;
else return no.getObject();
} finally {
lock.readLock().unlock();
}
}
/**
* Registers a DynamicMBean.
*/
private static void addDynamicMBean(final MBeanServer mbs,
final DynamicMBean dmbean,
final ObjectName on) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
mbs.registerMBean(dmbean, on);
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException {
name = nonDefaultDomain(name);
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, operationName, name, "invoke");
try {
return instance.invoke(operationName, params, signature);
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError();
}
}
/**
* Retrieves the MBean of the name specified from the repository. The
* object name must match exactly.
*
* @param name name of the MBean to retrieve.
*
* @return The retrieved MBean if it is contained in the repository,
* null otherwise.
*/
public DynamicMBean retrieve(ObjectName name) {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER, Repository.class.getName(),
"retrieve", "name = " + name);
}
// Calls internal retrieve method to get the named object
lock.readLock().lock();
try {
NamedObject no = retrieveNamedObject(name);
if (no == null) return null;
else return no.getObject();
} finally {
lock.readLock().unlock();
}
}
/**
* Registers a DynamicMBean.
*/
private static void addDynamicMBean(final MBeanServer mbs,
final DynamicMBean dmbean,
final ObjectName on) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
mbs.registerMBean(dmbean, on);
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException {
name = nonDefaultDomain(name);
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, operationName, name, "invoke");
try {
return instance.invoke(operationName, params, signature);
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError();
}
}
/**
* Gets a specific MBean controlled by the DefaultMBeanServerInterceptor.
* The name must have a non-default domain.
*/
private DynamicMBean getMBean(ObjectName name)
throws InstanceNotFoundException {
if (name == null) {
throw new RuntimeOperationsException(new
IllegalArgumentException("Object name cannot be null"),
"Exception occurred trying to get an MBean");
}
DynamicMBean obj = repository.retrieve(name);
if (obj == null) {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"getMBean", name + " : Found no object");
}
throw new InstanceNotFoundException(name.toString());
}
return obj;
}
/**
* <p>Return the named {@link java.lang.ClassLoader}.
* @param loaderName The ObjectName of the ClassLoader.
* @return The named ClassLoader.
* @exception InstanceNotFoundException if the named ClassLoader
* is not found.
*/
public ClassLoader getClassLoader(ObjectName loaderName)
throws InstanceNotFoundException {
if (loaderName == null) {
checkMBeanPermission((String) null, null, null, "getClassLoader");
return server.getClass().getClassLoader();
}
DynamicMBean instance = getMBean(loaderName);
checkMBeanPermission(instance, null, loaderName, "getClassLoader");
Object resource = getResource(instance);
/* Check if the given MBean is a ClassLoader */
if (!(resource instanceof ClassLoader))
throw new InstanceNotFoundException(loaderName.toString() +
" is not a classloader");
return (ClassLoader) resource;
}
private NotificationListener getListener(ObjectName listener)
throws ListenerNotFoundException {
// ----------------
// Get listener object
// ----------------
DynamicMBean instance;
try {
instance = getMBean(listener);
} catch (InstanceNotFoundException e) {
throw EnvHelp.initCause(
new ListenerNotFoundException(e.getMessage()), e);
}
Object resource = getResource(instance);
if (!(resource instanceof NotificationListener)) {
final RuntimeException exc =
new IllegalArgumentException(listener.getCanonicalName());
final String msg =
"MBean " + listener.getCanonicalName() + " does not " +
"implement " + NotificationListener.class.getName();
throw new RuntimeOperationsException(exc, msg);
}
return (NotificationListener) resource;
}
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws InstanceNotFoundException, MBeanException,
ReflectionException {
name = nonDefaultDomain(name);
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, operationName, name, "invoke");
try {
return instance.invoke(operationName, params, signature);
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError();
}
}
/**
* Registers a DynamicMBean.
*/
private static void addDynamicMBean(final MBeanServer mbs,
final DynamicMBean dmbean,
final ObjectName on) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
mbs.registerMBean(dmbean, on);
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
private static ObjectName preRegister(
DynamicMBean mbean, MBeanServer mbs, ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException {
ObjectName newName = null;
try {
if (mbean instanceof MBeanRegistration)
newName = ((MBeanRegistration) mbean).preRegister(mbs, name);
} catch (Throwable t) {
throwMBeanRegistrationException(t, "in preRegister method");
}
if (newName != null) return newName;
else return name;
}
/**
* Retrieves the MBean of the name specified from the repository. The
* object name must match exactly.
*
* @param name name of the MBean to retrieve.
*
* @return The retrieved MBean if it is contained in the repository,
* null otherwise.
*/
public DynamicMBean retrieve(ObjectName name) {
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER, Repository.class.getName(),
"retrieve", "name = " + name);
}
// Calls internal retrieve method to get the named object
lock.readLock().lock();
try {
NamedObject no = retrieveNamedObject(name);
if (no == null) return null;
else return no.getObject();
} finally {
lock.readLock().unlock();
}
}
/**
* Create, register, and return an MBean for this
* <code>Group</code> object.
*
* @param group The Group to be managed
*
* @exception Exception if an MBean cannot be created or registered
*/
static DynamicMBean createMBean(Group group)
throws Exception {
String mname = createManagedName(group);
ManagedBean managed = registry.findManagedBean(mname);
if (managed == null) {
Exception e = new Exception("ManagedBean is not found with "+mname);
throw new MBeanException(e);
}
String domain = managed.getDomain();
if (domain == null)
domain = mserver.getDefaultDomain();
DynamicMBean mbean = managed.createMBean(group);
ObjectName oname = createObjectName(domain, group);
if( mserver.isRegistered( oname )) {
mserver.unregisterMBean(oname);
}
mserver.registerMBean(mbean, oname);
return (mbean);
}
private DynamicMBean getMBean(ObjectName name)
throws InstanceNotFoundException {
DynamicMBean mbean = mbeans.get(name);
if (mbean == null)
throw new InstanceNotFoundException(name.toString());
return mbean;
}
public boolean isInstanceOf(ObjectName name, String className)
throws InstanceNotFoundException {
final DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, null, name, "isInstanceOf");
try {
Object resource = getResource(instance);
final String resourceClassName =
(resource instanceof DynamicMBean) ?
getClassName((DynamicMBean) resource) :
resource.getClass().getName();
if (resourceClassName.equals(className))
return true;
final ClassLoader cl = resource.getClass().getClassLoader();
final Class<?> classNameClass = Class.forName(className, false, cl);
if (classNameClass.isInstance(resource))
return true;
final Class<?> resourceClass = Class.forName(resourceClassName, false, cl);
return classNameClass.isAssignableFrom(resourceClass);
} catch (Exception x) {
/* Could be SecurityException or ClassNotFoundException */
if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
MBEANSERVER_LOGGER.logp(Level.FINEST,
DefaultMBeanServerInterceptor.class.getName(),
"isInstanceOf", "Exception calling isInstanceOf", x);
}
return false;
}
}
public boolean isInstanceOf(ObjectName name, String className)
throws InstanceNotFoundException {
final DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, null, name, "isInstanceOf");
try {
Object resource = getResource(instance);
final String resourceClassName =
(resource instanceof DynamicMBean) ?
getClassName((DynamicMBean) resource) :
resource.getClass().getName();
if (resourceClassName.equals(className))
return true;
final ClassLoader cl = resource.getClass().getClassLoader();
final Class<?> classNameClass = Class.forName(className, false, cl);
if (classNameClass.isInstance(resource))
return true;
final Class<?> resourceClass = Class.forName(resourceClassName, false, cl);
return classNameClass.isAssignableFrom(resourceClass);
} catch (Exception x) {
/* Could be SecurityException or ClassNotFoundException */
if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
MBEANSERVER_LOGGER.logp(Level.FINEST,
DefaultMBeanServerInterceptor.class.getName(),
"isInstanceOf", "Exception calling isInstanceOf", x);
}
return false;
}
}
public void addNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException {
// ------------------------------
// ------------------------------
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"addNotificationListener", "ObjectName = " + name);
}
DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, null, name, "addNotificationListener");
NotificationBroadcaster broadcaster =
getNotificationBroadcaster(name, instance,
NotificationBroadcaster.class);
// ------------------
// Check listener
// ------------------
if (listener == null) {
throw new RuntimeOperationsException(new
IllegalArgumentException("Null listener"),"Null listener");
}
NotificationListener listenerWrapper =
getListenerWrapper(listener, name, instance, true);
broadcaster.addNotificationListener(listenerWrapper, filter, handback);
}
private void addNewDomMoi(final DynamicMBean object,
final String dom,
final ObjectName name,
final RegistrationContext context) {
final Map<String,NamedObject> moiTb =
new HashMap<String,NamedObject>();
final String key = name.getCanonicalKeyPropertyListString();
addMoiToTb(object,name,key,moiTb,context);
domainTb.put(dom, moiTb);
nbElements++;
}
public Object getAttribute(ObjectName name, String attribute)
throws MBeanException, AttributeNotFoundException,
InstanceNotFoundException, ReflectionException {
if (name == null) {
throw new RuntimeOperationsException(new
IllegalArgumentException("Object name cannot be null"),
"Exception occurred trying to invoke the getter on the MBean");
}
if (attribute == null) {
throw new RuntimeOperationsException(new
IllegalArgumentException("Attribute cannot be null"),
"Exception occurred trying to invoke the getter on the MBean");
}
name = nonDefaultDomain(name);
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"getAttribute",
"Attribute = " + attribute + ", ObjectName = " + name);
}
final DynamicMBean instance = getMBean(name);
checkMBeanPermission(instance, attribute, name, "getAttribute");
try {
return instance.getAttribute(attribute);
} catch (AttributeNotFoundException e) {
throw e;
} catch (Throwable t) {
rethrowMaybeMBeanException(t);
throw new AssertionError(); // not reached
}
}
/**
* Adds a MBean in the repository,
* sends MBeanServerNotification.REGISTRATION_NOTIFICATION,
* returns ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces. For regular MBean this method returns
* ResourceContext.NONE.
* @return a ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces.
*/
private ResourceContext registerWithRepository(
final Object resource,
final DynamicMBean object,
final ObjectName logicalName)
throws InstanceAlreadyExistsException,
MBeanRegistrationException {
// Creates a registration context, if needed.
//
final ResourceContext context =
makeResourceContextFor(resource, logicalName);
repository.addMBean(object, logicalName, context);
// May throw InstanceAlreadyExistsException
// ---------------------
// Send create event
// ---------------------
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"addObject", "Send create notification of object " +
logicalName.getCanonicalName());
}
sendNotification(
MBeanServerNotification.REGISTRATION_NOTIFICATION,
logicalName);
return context;
}
private void exclusiveUnregisterMBean(ObjectName name)
throws InstanceNotFoundException, MBeanRegistrationException {
DynamicMBean instance = getMBean(name);
// may throw InstanceNotFoundException
checkMBeanPermission(instance, null, name, "unregisterMBean");
if (instance instanceof MBeanRegistration)
preDeregisterInvoke((MBeanRegistration) instance);
final Object resource = getResource(instance);
// Unregisters the MBean from the repository.
// Returns the resource context that was used.
// The returned context does nothing for regular MBeans.
// For ClassLoader MBeans and JMXNamespace (and JMXDomain)
// MBeans - the context makes it possible to unregister these
// objects from the appropriate framework artifacts, such as
// the CLR or the dispatcher, from within the repository lock.
// In case of success, we also need to call context.done() at the
// end of this method.
//
final ResourceContext context =
unregisterFromRepository(resource, instance, name);
try {
if (instance instanceof MBeanRegistration)
postDeregisterInvoke(name,(MBeanRegistration) instance);
} finally {
context.done();
}
}
/**
* Adds a MBean in the repository,
* sends MBeanServerNotification.REGISTRATION_NOTIFICATION,
* returns ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces. For regular MBean this method returns
* ResourceContext.NONE.
* @return a ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces.
*/
private ResourceContext registerWithRepository(
final Object resource,
final DynamicMBean object,
final ObjectName logicalName)
throws InstanceAlreadyExistsException,
MBeanRegistrationException {
// Creates a registration context, if needed.
//
final ResourceContext context =
makeResourceContextFor(resource, logicalName);
repository.addMBean(object, logicalName, context);
// May throw InstanceAlreadyExistsException
// ---------------------
// Send create event
// ---------------------
if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) {
MBEANSERVER_LOGGER.log(Level.TRACE,
"Send create notification of object " +
logicalName.getCanonicalName());
}
sendNotification(
MBeanServerNotification.REGISTRATION_NOTIFICATION,
logicalName);
return context;
}