下面列出了怎么用javax.management.ObjectName的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* @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);
}
}
/**
* Remove any resource link reference with the specified name.
*
* @param resourceLinkName Name of the resource link reference to remove
*/
public void removeResourceLink(String resourceLinkName) {
resourceLinkName = ObjectName.unquote(resourceLinkName);
NamingResources nresources = (NamingResources) this.resource;
if (nresources == null) {
return;
}
ContextResourceLink resourceLink =
nresources.findResourceLink(resourceLinkName);
if (resourceLink == null) {
throw new IllegalArgumentException
("Invalid resource Link name '" + resourceLinkName + "'");
}
nresources.removeResourceLink(resourceLinkName);
}
private static void testPrivate(Class<?> iface, Object bean) throws Exception {
try {
System.out.println("Registering a private MBean " +
iface.getName() + " ...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("test:type=Compliant");
mbs.registerMBean(bean, on);
success("Registered a private MBean - " + iface.getName());
} catch (Exception e) {
Throwable t = e;
while (t != null && !(t instanceof NotCompliantMBeanException)) {
t = t.getCause();
}
if (t != null) {
fail("MBean not registered");
} else {
throw e;
}
}
}
/**
* Creates a default singleton ObjectName for a given class.
* @param clazz The interface class of the MBean for which we want to obtain
* a default singleton name, or its implementation class.
* Give one or the other depending on what you wish to see in
* the value of the key {@code type=}.
* @return A default singleton name for a singleton MBean class.
* @throws IllegalArgumentException if the name can't be created
* for some unfathomable reason (e.g. an unexpected
* exception was raised).
**/
public final static ObjectName makeSingletonName(Class clazz) {
try {
final Package p = clazz.getPackage();
final String packageName = (p==null)?null:p.getName();
final String className = clazz.getSimpleName();
final String domain;
if (packageName == null || packageName.length()==0) {
// We use a reference to ScanDirAgent.class to ease
// to keep track of possible class renaming.
domain = ScanDirAgent.class.getSimpleName();
} else {
domain = packageName;
}
final ObjectName name = new ObjectName(domain,"type",className);
return name;
} catch (Exception x) {
final IllegalArgumentException iae =
new IllegalArgumentException(String.valueOf(clazz),x);
throw iae;
}
}
private static void testCaseProb() throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName name = new ObjectName("a:b=c");
mbs.registerMBean(new CaseProbImpl(), name);
CaseProbMXBean proxy = JMX.newMXBeanProxy(mbs, name, CaseProbMXBean.class);
try {
CaseProb prob = proxy.getCaseProb();
fail("No exception from proxy method getCaseProb");
} catch (IllegalArgumentException e) {
String messageChain = messageChain(e);
if (messageChain.contains("URLPath")) {
System.out.println("Message chain contains URLPath as required: "
+ messageChain);
} else {
fail("Exception chain for CaseProb does not mention property" +
" URLPath differing only in case");
System.out.println("Full stack trace:");
e.printStackTrace(System.out);
}
}
}
/**
* Create a new UserDatabaseRealm.
*
* @param parent MBean Name of the associated parent component
* @param resourceName Global JNDI resource name of the associated
* UserDatabase
* @return the object name of the created realm
*
* @exception Exception if an MBean cannot be created or registered
*/
public String createUserDatabaseRealm(String parent, String resourceName)
throws Exception {
// Create a new UserDatabaseRealm instance
UserDatabaseRealm realm = new UserDatabaseRealm();
realm.setResourceName(resourceName);
// Add the new instance to its parent component
ObjectName pname = new ObjectName(parent);
Container container = getParentContainerFromParent(pname);
// Add the new instance to its parent component
container.setRealm(realm);
// Return the corresponding MBean name
ObjectName oname = realm.getObjectName();
// FIXME getObjectName() returns null
//ObjectName oname =
// MBeanUtils.createObjectName(pname.getDomain(), realm);
if (oname != null) {
return (oname.toString());
} else {
return null;
}
}
private void assertSrcCounterState(ObjectName on, long eventReceivedCount,
long eventAcceptedCount, long appendReceivedCount,
long appendAcceptedCount, long appendBatchReceivedCount,
long appendBatchAcceptedCount) throws Exception {
Assert.assertEquals("SrcEventReceived",
getSrcEventReceivedCount(on),
eventReceivedCount);
Assert.assertEquals("SrcEventAccepted",
getSrcEventAcceptedCount(on),
eventAcceptedCount);
Assert.assertEquals("SrcAppendReceived",
getSrcAppendReceivedCount(on),
appendReceivedCount);
Assert.assertEquals("SrcAppendAccepted",
getSrcAppendAcceptedCount(on),
appendAcceptedCount);
Assert.assertEquals("SrcAppendBatchReceived",
getSrcAppendBatchReceivedCount(on),
appendBatchReceivedCount);
Assert.assertEquals("SrcAppendBatchAccepted",
getSrcAppendBatchAcceptedCount(on),
appendBatchAcceptedCount);
}
@Override
public ObjectName registerManagedResource(Object managedResource) throws MBeanExportException {
Assert.notNull(managedResource, "Managed resource must not be null");
ObjectName objectName;
try {
objectName = getObjectName(managedResource, null);
if (this.ensureUniqueRuntimeObjectNames) {
objectName = JmxUtils.appendIdentityToObjectName(objectName, managedResource);
}
}
catch (Throwable ex) {
throw new MBeanExportException("Unable to generate ObjectName for MBean [" + managedResource + "]", ex);
}
registerManagedResource(managedResource, objectName);
return objectName;
}
public static void main(String[] args) throws Exception {
if (System.getSecurityManager() == null)
throw new IllegalStateException("No security manager installed!");
System.out.println("java.security.policy=" +
System.getProperty("java.security.policy"));
// Instantiate the MBean server
//
System.out.println("Create the MBean server");
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
// Register the MLetMBean
//
System.out.println("Create MLet MBean");
ObjectName mlet = new ObjectName("MLetTest:name=MLetMBean");
mbs.createMBean("javax.management.loading.MLet", mlet);
// Test OK!
//
System.out.println("Bye! Bye!");
}
/**
* Initialization of the MIB with AUTOMATIC REGISTRATION in Java DMK.
*/
public ObjectName preRegister(MBeanServer server, ObjectName name)
throws Exception {
// Allow only one initialization of the MIB.
//
if (isInitialized == true) {
throw new InstanceAlreadyExistsException();
}
// Initialize MBeanServer information.
//
this.server = server;
populate(server, name);
isInitialized = true;
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();
}
}
/**
* Initialization of the "JvmRuntime" group.
*
* To disable support of this group, redefine the
* "createJvmRuntimeMetaNode()" factory method, and make it return "null"
*
* @param server MBeanServer for this group (may be null)
*
**/
protected void initJvmRuntime(MBeanServer server)
throws Exception {
final String oid = getGroupOid("JvmRuntime", "1.3.6.1.4.1.42.2.145.3.163.1.1.4");
ObjectName objname = null;
if (server != null) {
objname = getGroupObjectName("JvmRuntime", oid, mibName + ":name=sun.management.snmp.jvmmib.JvmRuntime");
}
final JvmRuntimeMeta meta = createJvmRuntimeMetaNode("JvmRuntime", oid, objname, server);
if (meta != null) {
meta.registerTableNodes( this, server );
// Note that when using standard metadata,
// the returned object must implement the "JvmRuntimeMBean"
// interface.
//
final JvmRuntimeMBean group = (JvmRuntimeMBean) createJvmRuntimeMBean("JvmRuntime", oid, objname, server);
meta.setInstance( group );
registerGroupNode("JvmRuntime", oid, objname, meta, group, server);
}
}
private static boolean test(Object mbean, boolean expectImmutable)
throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
ObjectName on = new ObjectName("a:b=c");
mbs.registerMBean(mbean, on);
MBeanInfo mbi = mbs.getMBeanInfo(on);
Descriptor d = mbi.getDescriptor();
String immutableValue = (String) d.getFieldValue("immutableInfo");
boolean immutable = ("true".equals(immutableValue));
if (immutable != expectImmutable) {
System.out.println("FAILED: " + mbean.getClass().getName() +
" -> " + immutableValue);
return false;
} else {
System.out.println("OK: " + mbean.getClass().getName());
return true;
}
}
public Long getValue(String name) {
try {
final ObjectName mBeanObject = new ObjectName(JmxReporterService.MBEAN_DOMAIN + ":name=" + name);
return client != null ? (Long)client.getAttribute(mBeanObject, "Value") : 0L;
} catch (MalformedObjectNameException |IOException | ReflectionException | AttributeNotFoundException | InstanceNotFoundException | MBeanException e) {
logger.error(e.getMessage());
}
return -1L;
}
private void unregisterMBeans(Map<ObjectName,?> map) throws JMException {
for (ObjectName key : map.keySet()) {
if (mbeanServer.isRegistered(key))
mbeanServer.unregisterMBean(key);
map.remove(key);
}
}
public void removeNotificationListener(ObjectName name,
Integer[] listenerIDs)
throws Exception {
if (logger.traceOn()) {
logger.trace("removeNotificationListener",
"Remove some listeners from " + name);
}
checkState();
// Explicitly check MBeanPermission for removeNotificationListener
//
checkMBeanPermission(name, "removeNotificationListener");
if (notificationAccessController != null) {
notificationAccessController.removeNotificationListener(
connectionId, name, getSubject());
}
Exception re = null;
for (int i = 0 ; i < listenerIDs.length ; i++) {
try {
removeNotificationListener(name, listenerIDs[i]);
} catch (Exception e) {
// Give back the first exception
//
if (re != null) {
re = e;
}
}
}
if (re != null) {
throw re;
}
}
private static ObjectName composeMBeanName(final String objTypeName, final String objInstanceName) throws MalformedObjectNameException {
String name = "com.cloud:type=" + objTypeName;
if (objInstanceName != null && !objInstanceName.isEmpty()) {
name += ", name=" + objInstanceName;
}
return new ObjectName(name);
}
/**
* Helper method to get a member bean reference given a member name or id
*
* @param member
* name or id of the member
* @return the proxy reference
*/
protected MemberMXBean getProxyByMemberNameOrId(String member) {
try{
ObjectName objectName = MBeanJMXAdapter.getMemberMBeanName(member);
return mapOfMembers.get(objectName);
}catch(ManagementException mx){
return null;
}
}
public ObjectInstance createMBean(String className,
ObjectName name)
throws ReflectionException,
InstanceAlreadyExistsException,
MBeanRegistrationException,
MBeanException,
NotCompliantMBeanException,
IOException {
if (logger.debugOn())
logger.debug("createMBean(String,ObjectName)",
"className=" + className + ", name=" +
name);
final ClassLoader old = pushDefaultClassLoader();
try {
return connection.createMBean(className,
name,
delegationSubject);
} catch (IOException ioe) {
communicatorAdmin.gotIOException(ioe);
return connection.createMBean(className,
name,
delegationSubject);
} finally {
popDefaultClassLoader(old);
}
}
@Override
public void closeManagedObjectManager() {
synchronized (managedObjectManagerLock) {
if (managedObjectManagerClosed == true) {
return;
}
if (managedObjectManager != null) {
boolean close = true;
// ManagedObjectManager doesn't need to be closed because it exists only as a proxy
if (managedObjectManager instanceof WSEndpointMOMProxy
&& !((WSEndpointMOMProxy)managedObjectManager).isInitialized()) {
close = false;
}
if (close) {
try {
final ObjectName name = managedObjectManager.getObjectName(managedObjectManager.getRoot());
// The name is null when the MOM is a NOOP.
if (name != null) {
monitoringLogger.log(Level.INFO, "Closing Metro monitoring root: {0}", name);
}
managedObjectManager.close();
} catch (java.io.IOException e) {
monitoringLogger.log(Level.WARNING, "Ignoring error when closing Managed Object Manager", e);
}
}
}
managedObjectManagerClosed = true;
}
}
@Test
public void testOperationInvocation() throws Exception{
ObjectName objectName = ObjectNameManager.getInstance(getObjectName());
Object result = getServer().invoke(objectName, "add",
new Object[] {new Integer(20), new Integer(30)}, new String[] {"int", "int"});
assertEquals("Incorrect result", new Integer(50), result);
}
/**
* Removes a MBean in the repository,
* sends MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
* returns ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces, or null. For regular MBean this method returns
* ResourceContext.NONE.
*
* @return a ResourceContext for special resources such as ClassLoaders
* or JMXNamespaces.
*/
private ResourceContext unregisterFromRepository(
final Object resource,
final DynamicMBean object,
final ObjectName logicalName)
throws InstanceNotFoundException {
// Creates a registration context, if needed.
//
final ResourceContext context =
makeResourceContextFor(resource, logicalName);
repository.remove(logicalName, context);
// ---------------------
// Send deletion event
// ---------------------
if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
MBEANSERVER_LOGGER.logp(Level.FINER,
DefaultMBeanServerInterceptor.class.getName(),
"unregisterMBean", "Send delete notification of object " +
logicalName.getCanonicalName());
}
sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
logicalName);
return context;
}
public synchronized Integer[]
removeNotificationListener(ObjectName name,
NotificationListener listener)
throws ListenerNotFoundException, IOException {
beforeRemove();
if (logger.traceOn()) {
logger.trace("removeNotificationListener",
"Remove the listener "+listener+" from "+name);
}
List<Integer> ids = new ArrayList<Integer>();
List<ClientListenerInfo> values =
new ArrayList<ClientListenerInfo>(infoList.values());
for (int i=values.size()-1; i>=0; i--) {
ClientListenerInfo li = values.get(i);
if (li.sameAs(name, listener)) {
ids.add(li.getListenerID());
infoList.remove(li.getListenerID());
}
}
if (ids.isEmpty())
throw new ListenerNotFoundException("Listener not found");
return ids.toArray(new Integer[0]);
}
public String[] getDomains() {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Check if the caller has the right to invoke 'getDomains'
//
checkMBeanPermission((String) null, null, null, "getDomains");
// Return domains
//
String[] domains = repository.getDomains();
// Check if the caller has the right to invoke 'getDomains'
// on each specific domain in the list.
//
List<String> result = new ArrayList<String>(domains.length);
for (int i = 0; i < domains.length; i++) {
try {
ObjectName dom = Util.newObjectName(domains[i] + ":x=x");
checkMBeanPermission((String) null, null, dom, "getDomains");
result.add(domains[i]);
} catch (SecurityException e) {
// OK: Do not add this domain to the list
}
}
// Make an array from result.
//
return result.toArray(new String[result.size()]);
} else {
return repository.getDomains();
}
}
@Override
public void init(Map<Class<?>, TypeMetadata> registeredMetadata) {
ObjectName objectName = getObjectName();
try {
getMBeanServer().registerMBean(traceMonitor, objectName);
} catch (JMException e) {
throw new XOException("Cannot register trace monitor MBean for object name " + objectName, e);
}
delegate.init(registeredMetadata);
}
/**
* Returns a string describing the role.
*
* @return the description of the role.
*/
public String toString() {
StringBuilder result = new StringBuilder();
result.append("role name: " + name + "; role value: ");
for (Iterator<ObjectName> objNameIter = objectNameList.iterator();
objNameIter.hasNext();) {
ObjectName currObjName = objNameIter.next();
result.append(currObjName.toString());
if (objNameIter.hasNext()) {
result.append(", ");
}
}
return result.toString();
}
public static ObjectName newObjectName(String string) {
try {
return new ObjectName(string);
} catch (MalformedObjectNameException e) {
throw new IllegalArgumentException(e);
}
}
/**
* function for deregistering MBean.
*/
public static void deregisterMBean(String name) {
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName(name);
if (mbs.isRegistered(objectName)) {
mbs.unregisterMBean(objectName);
}
} catch (MalformedObjectNameException | MBeanRegistrationException
| InstanceNotFoundException e) {
logger.error("Failed to unregisterMBean {}", name, e);
}
}
/**
* Registers an existing MBean or an MBean adapter for a plain bean
* with the {@code MBeanServer}.
* @param bean the bean to register, either an MBean or a plain bean
* @param beanKey the key associated with this bean in the beans map
* @return the {@code ObjectName} under which the bean was registered
* with the {@code MBeanServer}
*/
private ObjectName registerBeanInstance(Object bean, String beanKey) throws JMException {
ObjectName objectName = getObjectName(bean, beanKey);
Object mbeanToExpose = null;
if (isMBean(bean.getClass())) {
mbeanToExpose = bean;
}
else {
DynamicMBean adaptedBean = adaptMBeanIfPossible(bean);
if (adaptedBean != null) {
mbeanToExpose = adaptedBean;
}
}
if (mbeanToExpose != null) {
if (logger.isInfoEnabled()) {
logger.info("Located MBean '" + beanKey + "': registering with JMX server as MBean [" +
objectName + "]");
}
doRegister(mbeanToExpose, objectName);
}
else {
if (logger.isInfoEnabled()) {
logger.info("Located managed bean '" + beanKey + "': registering with JMX server as MBean [" +
objectName + "]");
}
ModelMBean mbean = createAndConfigureMBean(bean, beanKey);
doRegister(mbean, objectName);
injectNotificationPublisherIfNecessary(bean, mbean, objectName);
}
return objectName;
}
private static void checkMBeanPermission(String classname,
String member,
ObjectName objectName,
String actions)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanPermission(classname,
member,
objectName,
actions);
sm.checkPermission(perm);
}
}