Java Code Examples for javax.management.ObjectName

The following examples show how to use javax.management.ObjectName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * @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);
    }
}
 
Example 2
Source Project: tomcatsrc   Source File: NamingResourcesMBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 3
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;
        }
    }
}
 
Example 4
Source Project: openjdk-8-source   Source File: ScanManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 5
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);
        }
    }
}
 
Example 6
Source Project: Tomcat8-Source-Read   Source File: MBeanFactory.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
    }

}
 
Example 7
Source Project: mt-flume   Source File: TestMonitoredCounterGroup.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 8
Source Project: lams   Source File: MBeanExporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
@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;
}
 
Example 9
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!");
}
 
Example 10
Source Project: jdk8u_jdk   Source File: JVM_MANAGEMENT_MIB.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source Project: hottub   Source File: Repository.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 12
/**
 * 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);
    }
}
 
Example 13
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;
    }
}
 
Example 14
Source Project: galeb   Source File: JmxClientService.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 15
private void unregisterMBeans(Map<ObjectName,?> map) throws JMException {
    for (ObjectName key : map.keySet()) {
        if (mbeanServer.isRegistered(key))
            mbeanServer.unregisterMBean(key);
        map.remove(key);
    }
}
 
Example 16
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;
    }
}
 
Example 17
Source Project: cosmic   Source File: JmxUtil.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
 
Example 18
Source Project: gemfirexd-oss   Source File: DistributedSystemBridge.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
  }

}
 
Example 19
Source Project: jdk8u60   Source File: RMIConnector.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 20
Source Project: openjdk-jdk9   Source File: WSEndpointImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
    }
}
 
Example 21
Source Project: java-technology-stack   Source File: AbstractJmxAssemblerTests.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 22
Source Project: JDKSourceCode1.8   Source File: DefaultMBeanServerInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 23
Source Project: jdk8u60   Source File: ClientNotifForwarder.java    License: GNU General Public License v2.0 5 votes vote down vote up
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]);
}
 
Example 24
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();
    }
}
 
Example 25
Source Project: extended-objects   Source File: TraceDatastore.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 26
Source Project: jdk8u60   Source File: Role.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 27
Source Project: jdk8u-jdk   Source File: Util.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static ObjectName newObjectName(String string) {
    try {
        return new ObjectName(string);
    } catch (MalformedObjectNameException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 28
Source Project: incubator-iotdb   Source File: JMXService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 29
Source Project: lams   Source File: MBeanExporter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Source Project: jdk8u-jdk   Source File: JmxMBeanServer.java    License: GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}