下面列出了怎么用javax.management.InstanceNotFoundException的API类实例代码及写法,或者点击链接到github查看源代码。
public ObjectInstance getObjectInstance(ObjectName name)
throws InstanceNotFoundException,
IOException {
if (logger.debugOn())
logger.debug("getObjectInstance", "name=" + name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getObjectInstance(name, delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getObjectInstance(name, delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
public Object getAttribute(ObjectName name,
String attribute)
throws MBeanException,
AttributeNotFoundException,
InstanceNotFoundException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("getAttribute",
"name=" + name + ", attribute="
+ attribute);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.getAttribute(name,
attribute,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.getAttribute(name,
attribute,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
protected void removeListenerForMBeanRemovedNotif(Integer id)
throws IOException, InstanceNotFoundException,
ListenerNotFoundException {
try {
connection.removeNotificationListeners(
MBeanServerDelegate.DELEGATE_NAME,
new Integer[] {id},
null);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
connection.removeNotificationListeners(
MBeanServerDelegate.DELEGATE_NAME,
new Integer[] {id},
null);
}
}
@Test
public void noRegisterWithMBeanServer() throws Exception {
ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean();
bean.afterPropertiesSet();
try {
// Try to get the connector bean.
getServer().getObjectInstance(ObjectName.getInstance(OBJECT_NAME));
fail("Instance should not be found");
}
catch (InstanceNotFoundException ex) {
// expected
}
finally {
bean.destroy();
}
}
public void addNotificationListener(ObjectName name,
NotificationListener listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException,
IOException {
final boolean debug = logger.debugOn();
if (debug)
logger.debug("addNotificationListener" +
"(ObjectName,NotificationListener,"+
"NotificationFilter,Object)",
"name=" + name
+ ", listener=" + listener
+ ", filter=" + filter
+ ", handback=" + handback);
final Integer listenerID =
addListenerWithSubject(name,
new MarshalledObject<NotificationFilter>(filter),
delegationSubject,true);
rmiNotifClient.addNotificationListener(listenerID, name, listener,
filter, handback,
delegationSubject);
}
private void doTest(JMXConnector connector) throws IOException,
MalformedObjectNameException, ReflectionException,
InstanceAlreadyExistsException, MBeanRegistrationException,
MBeanException, NotCompliantMBeanException, InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException {
MBeanServerConnection mbsc = connector.getMBeanServerConnection();
ObjectName objName = new ObjectName("com.redhat.test.jmx:type=NameMBean");
System.out.println("DEBUG: Calling createMBean");
mbsc.createMBean(Name.class.getName(), objName);
System.out.println("DEBUG: Calling setAttributes");
AttributeList attList = new AttributeList();
attList.add(new Attribute("FirstName", ANY_NAME));
attList.add(new Attribute("LastName", ANY_NAME));
mbsc.setAttributes(objName, attList);
}
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);
}
}
private static boolean isInstanceOf(final MBeanServer mbs,
final ObjectName name,
final String className) {
PrivilegedExceptionAction<Boolean> act =
new PrivilegedExceptionAction<Boolean>() {
public Boolean run() throws InstanceNotFoundException {
return mbs.isInstanceOf(name, className);
}
};
try {
return AccessController.doPrivileged(act);
} catch (Exception e) {
logger.fine("isInstanceOf", "failed: " + e);
logger.debug("isInstanceOf", e);
return false;
}
}
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();
}
}
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 void addNotificationListener(
ObjectName name, NotificationListener listener,
NotificationFilter filter, Object handback)
throws InstanceNotFoundException {
NotificationBroadcaster userMBean =
(NotificationBroadcaster) getUserMBean(name);
NotificationListener wrappedListener =
wrappedListener(name, userMBean, listener);
userMBean.addNotificationListener(wrappedListener, filter, handback);
}
public Object instantiate(
String className, Object[] params, String[] signature)
throws ReflectionException, MBeanException {
try {
return instantiate(className, clrName, params, signature);
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e); // can't happen
}
}
public boolean isInstanceOf(ObjectName name, String className)
throws InstanceNotFoundException {
DynamicMBean mbean = getMBean(name);
String mbeanClassName = mbean.getMBeanInfo().getClassName();
if (className.equals(mbeanClassName))
return true;
ClassLoader loader = getUserMBean(mbean).getClass().getClassLoader();
try {
Class<?> mbeanClass = Class.forName(mbeanClassName, false, loader);
Class<?> isInstClass = Class.forName(className, false, loader);
return isInstClass.isAssignableFrom(mbeanClass);
} catch (ClassNotFoundException e) {
return false;
}
}
/**
* Call <code>checkRead()</code>, then forward this method to the
* wrapped object.
*/
@Deprecated
public ObjectInputStream deserialize(ObjectName name, byte[] data)
throws InstanceNotFoundException, OperationsException {
checkRead();
return getMBeanServer().deserialize(name, data);
}
public Object invoke(ObjectName name,
String operationName,
Object params[],
String signature[])
throws InstanceNotFoundException,
MBeanException,
ReflectionException,
IOException {
if (logger.debugOn()) logger.debug("invoke",
"name=" + name
+ ", operationName=" + operationName
+ ", signature=" + strings(signature));
final MarshalledObject<Object[]> sParams =
new MarshalledObject<Object[]>(params);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.invoke(name,
operationName,
sParams,
signature,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.invoke(name,
operationName,
sParams,
signature,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
private void unregisterMBean(ObjectName originalObjectName) throws InstanceNotFoundException, MBeanRegistrationException {
ObjectName storedObjectName = registered.remove(originalObjectName);
if (storedObjectName != null) {
mBeanServer.unregisterMBean(storedObjectName);
} else {
mBeanServer.unregisterMBean(originalObjectName);
}
}
public void removeNotificationListener(
ObjectName name, NotificationListener listener,
NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException {
NotificationEmitter userMBean =
(NotificationEmitter) getMBean(name);
NotificationListener wrappedListener =
wrappedListener(name, userMBean, listener);
userMBean.removeNotificationListener(wrappedListener, filter, handback);
}
/**
* Sets the instance handle of the object against which to
* execute all methods in this ModelMBean management interface
* (MBeanInfo and Descriptors).
*
* @param mr Object that is the managed resource
* @param mr_type The type of reference for the managed resource.
* <br>Can be: "ObjectReference", "Handle", "IOR", "EJBHandle",
* or "RMIReference".
* <br>In this implementation only "ObjectReference" is supported.
*
* @exception MBeanException The initializer of the object has
* thrown an exception.
* @exception InstanceNotFoundException The managed resource
* object could not be found
* @exception InvalidTargetObjectTypeException The managed
* resource type should be "ObjectReference".
* @exception RuntimeOperationsException Wraps a {@link
* RuntimeException} when setting the resource.
**/
public void setManagedResource(Object mr, String mr_type)
throws MBeanException, RuntimeOperationsException,
InstanceNotFoundException, InvalidTargetObjectTypeException {
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"setManagedResource(Object,String)","Entry");
}
// check that the mr_type is supported by this JMXAgent
// only "objectReference" is supported
if ((mr_type == null) ||
(! mr_type.equalsIgnoreCase("objectReference"))) {
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"setManagedResource(Object,String)",
"Managed Resource Type is not supported: " + mr_type);
}
throw new InvalidTargetObjectTypeException(mr_type);
}
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"setManagedResource(Object,String)",
"Managed Resource is valid");
}
managedResource = mr;
if (MODELMBEAN_LOGGER.isLoggable(Level.FINER)) {
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"setManagedResource(Object, String)", "Exit");
}
}
public ObjectInstance createMBean(
String className, ObjectName name, ObjectName loaderName,
Object[] params, String[] signature)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException {
Object mbean = instantiate(className, loaderName, params, signature);
return registerMBean(mbean, name);
}
static void checkMBeanPermission(
final MBeanServer mbs, final ObjectName name, final String actions)
throws InstanceNotFoundException, SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
AccessControlContext acc = AccessController.getContext();
ObjectInstance oi;
try {
oi = AccessController.doPrivileged(
new PrivilegedExceptionAction<ObjectInstance>() {
public ObjectInstance run()
throws InstanceNotFoundException {
return mbs.getObjectInstance(name);
}
});
} catch (PrivilegedActionException e) {
throw (InstanceNotFoundException) extractException(e);
}
String classname = oi.getClassName();
MBeanPermission perm = new MBeanPermission(
classname,
null,
name,
actions);
sm.checkPermission(perm, acc);
}
}
/**
* Set the value of an SNMP variable.
*
* <p><b><i>
* You should never need to use this method directly.
* </i></b></p>
*
* @param meta The impacted metadata object
* @param name The ObjectName of the impacted MBean
* @param x The new requested SnmpValue
* @param id The OID arc identifying the variable we're trying to set.
* @param data User contextual data allocated through the
* {@link com.sun.jmx.snmp.agent.SnmpUserDataFactory}
*
* @return The new value of the variable after the operation.
*
* @exception SnmpStatusException whenever an SNMP exception must be
* raised. Raising an exception will abort the request. <br>
* Exceptions should never be raised directly, but only by means of
* <code>
* req.registerSetException(<i>VariableId</i>,<i>SnmpStatusException</i>)
* </code>
**/
public SnmpValue set(SnmpGenericMetaServer meta, ObjectName name,
SnmpValue x, long id, Object data)
throws SnmpStatusException {
final String attname = meta.getAttributeName(id);
final Object attvalue=
meta.buildAttributeValue(id,x);
final Attribute att = new Attribute(attname,attvalue);
Object result = null;
try {
server.setAttribute(name,att);
result = server.getAttribute(name,attname);
} catch(InvalidAttributeValueException iv) {
throw new
SnmpStatusException(SnmpStatusException.snmpRspWrongValue);
} catch (InstanceNotFoundException f) {
throw new
SnmpStatusException(SnmpStatusException.snmpRspInconsistentName);
} catch (ReflectionException r) {
throw new
SnmpStatusException(SnmpStatusException.snmpRspInconsistentName);
} catch (MBeanException m) {
Exception t = m.getTargetException();
if (t instanceof SnmpStatusException)
throw (SnmpStatusException) t;
throw new
SnmpStatusException(SnmpStatusException.noAccess);
} catch (Exception e) {
throw new
SnmpStatusException(SnmpStatusException.noAccess);
}
return meta.buildSnmpValue(id,result);
}
public ObjectInstance createMBean(String className, ObjectName name,
ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException,
MBeanRegistrationException, MBeanException,
NotCompliantMBeanException, InstanceNotFoundException {
return createMBean(className, name, loaderName, (Object[]) null,
(String[]) null);
}
@Test
public void cleansUpAfterItselfWhenStopped() throws Exception {
reporter.stop();
try {
getAttributes("gauge", "Value");
Assertions.failBecauseExceptionWasNotThrown(InstanceNotFoundException.class);
} catch (InstanceNotFoundException e) {
}
}
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();
}
}
public void removeNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException, ListenerNotFoundException {
mbsInterceptor.removeNotificationListener(cloneObjectName(name),
listener, filter, handback);
}
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);
}
public void addNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException {
// ------------------------------
// ------------------------------
// ----------------
// Get listener object
// ----------------
DynamicMBean instance = getMBean(listener);
Object resource = getResource(instance);
if (!(resource instanceof NotificationListener)) {
throw new RuntimeOperationsException(new
IllegalArgumentException(listener.getCanonicalName()),
"The MBean " + listener.getCanonicalName() +
"does not implement the NotificationListener interface") ;
}
// ----------------
// Add a listener on an MBean
// ----------------
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"addNotificationListener",
"ObjectName = " + name + ", Listener = " + listener);
}
server.addNotificationListener(name,(NotificationListener) resource,
filter, handback) ;
}
/**
* Call <code>checkWrite()</code>, then forward this method to the
* wrapped object.
*/
public Object invoke(ObjectName name, String operationName,
Object params[], String signature[])
throws
InstanceNotFoundException,
MBeanException,
ReflectionException {
checkWrite();
checkMLetMethods(name, operationName);
return getMBeanServer().invoke(name, operationName, params, signature);
}
public void removeNotificationListener(ObjectName name,
ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException {
NotificationListener instance = getListener(listener);
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"removeNotificationListener",
"ObjectName = " + name + ", Listener = " + listener);
}
server.removeNotificationListener(name, instance);
}
/**
* Call <code>checkRead()</code>, then forward this method to the
* wrapped object.
*/
public void addNotificationListener(ObjectName name,
ObjectName listener,
NotificationFilter filter,
Object handback)
throws InstanceNotFoundException {
checkRead();
getMBeanServer().addNotificationListener(name, listener,
filter, handback);
}