类javax.management.ObjectName源码实例Demo

下面列出了怎么用javax.management.ObjectName的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: scheduling   文件: ROConnection.java
/**
 * @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);
    }
}
 
源代码2 项目: tomcatsrc   文件: NamingResourcesMBean.java
/**
 * 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);
}
 
源代码3 项目: openjdk-jdk8u-backup   文件: MBeanFallbackTest.java
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;
        }
    }
}
 
源代码4 项目: openjdk-8-source   文件: ScanManager.java
/**
 * 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;
    }
}
 
源代码5 项目: jdk8u60   文件: ExceptionDiagnosisTest.java
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);
        }
    }
}
 
源代码6 项目: Tomcat8-Source-Read   文件: MBeanFactory.java
/**
 * 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;
    }

}
 
源代码7 项目: mt-flume   文件: TestMonitoredCounterGroup.java
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);
}
 
源代码8 项目: lams   文件: MBeanExporter.java
@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;
}
 
源代码9 项目: openjdk-jdk8u-backup   文件: MLetCommand.java
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!");
}
 
源代码10 项目: jdk8u_jdk   文件: JVM_MANAGEMENT_MIB.java
/**
 * 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;
}
 
源代码11 项目: hottub   文件: Repository.java
/**
 * 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();
    }
}
 
源代码12 项目: openjdk-8-source   文件: JVM_MANAGEMENT_MIB.java
/**
 * 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;
    }
}
 
源代码14 项目: galeb   文件: JmxClientService.java
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;
}
 
源代码15 项目: openjdk-jdk8u-backup   文件: ScanManager.java
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;
    }
}
 
源代码17 项目: cosmic   文件: JmxUtil.java
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);
    }
 
源代码18 项目: gemfirexd-oss   文件: DistributedSystemBridge.java
/**
 * 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;
  }

}
 
源代码19 项目: jdk8u60   文件: RMIConnector.java
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);
    }
}
 
源代码20 项目: openjdk-jdk9   文件: WSEndpointImpl.java
@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;
}
 
源代码23 项目: jdk8u60   文件: ClientNotifForwarder.java
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();
    }
}
 
源代码25 项目: extended-objects   文件: TraceDatastore.java
@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);
}
 
源代码26 项目: jdk8u60   文件: Role.java
/**
 * 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();
}
 
源代码27 项目: jdk8u-jdk   文件: Util.java
public static ObjectName newObjectName(String string) {
    try {
        return new ObjectName(string);
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException(e);
    }
}
 
源代码28 项目: incubator-iotdb   文件: JMXService.java
/**
 * 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);
  }
}
 
源代码29 项目: lams   文件: MBeanExporter.java
/**
 * 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;
}
 
源代码30 项目: jdk8u-jdk   文件: JmxMBeanServer.java
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);
    }
}
 
 类所在包
 同包方法