Java Code Examples for javax.management.MBeanServer

The following are top voted examples for showing how to use javax.management.MBeanServer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: AgentImpl.java   Source Code and License 7 votes vote down vote up
private void createRMIRegistry() throws Exception {
  if (!this.agentConfig.isRmiRegistryEnabled()) {
    return;
  }
  MBeanServer mbs = getMBeanServer();
  String host = this.agentConfig.getRmiBindAddress();
  int port = this.agentConfig.getRmiPort();

  /*
   * Register and start the rmi-registry naming MBean, which is needed by JSR 160
   * RMIConnectorServer
   */
  ObjectName registryName = getRMIRegistryNamingName();
  try {
    RMIRegistryService registryNamingService = null;
    if (host != null && !("".equals(host.trim()))) {
      registryNamingService = new RMIRegistryService(host, port);
    } else {
      registryNamingService = new RMIRegistryService(port);
    }
    mbs.registerMBean(registryNamingService, registryName);
  } catch (javax.management.InstanceAlreadyExistsException e) {
    logger.info(LocalizedMessage.create(LocalizedStrings.AgentImpl_0__IS_ALREADY_REGISTERED,
        registryName));
  }
  mbs.invoke(registryName, "start", null, null);
}
 
Example 2
Project: metrics-tomcat   File: AnnotatedStandardMBean.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({
		"unchecked", "rawtypes"
})
public static String registerMBean(final Object object) throws JMException {
	final ObjectName objectName = generateMBeanName(object.getClass());
	final MBeanServer context = ManagementFactory.getPlatformMBeanServer();
	final String mbeanName = object.getClass().getName() + "MBean";
	for (final Class c : object.getClass().getInterfaces()) {
		if (mbeanName.equals(c.getName())) {
			context.registerMBean(new AnnotatedStandardMBean(object, c), objectName);
			return objectName.getCanonicalName();
		}
	}
	context.registerMBean(object, objectName);
	return objectName.getCanonicalName();
}
 
Example 3
Project: openjdk-jdk10   File: ConnectorStopDeadlockTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    RMIJRMPServerImplSub impl = new RMIJRMPServerImplSub();

    System.out.println("Creating connectorServer");
    connectorServer = new RMIConnectorServer(url, null, impl, mbs);
    System.out.println("Starting connectorServer");
    connectorServer.start();
    System.out.println("Making client");
    RMIConnection cc = impl.newClient(null);
    System.out.println("Closing client");
    cc.close();
    if (connectorServer.isActive()) {
        System.out.println("Stopping connectorServer");
        connectorServer.stop();
    }
    if (failure == null)
        System.out.println("TEST PASSED, no deadlock");
    else
        System.out.println("TEST FAILED");
}
 
Example 4
Project: OpenJSharp   File: JVM_MANAGEMENT_MIB.java   Source Code and License 6 votes vote down vote up
/**
 * 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 5
Project: jdk8u-jdk   File: JVM_MANAGEMENT_MIB.java   Source Code and License 6 votes vote down vote up
/**
 * Initialization of the "JvmThreading" group.
 *
 * To disable support of this group, redefine the
 * "createJvmThreadingMetaNode()" factory method, and make it return "null"
 *
 * @param server    MBeanServer for this group (may be null)
 *
 **/
protected void initJvmThreading(MBeanServer server)
    throws Exception {
    final String oid = getGroupOid("JvmThreading", "1.3.6.1.4.1.42.2.145.3.163.1.1.3");
    ObjectName objname = null;
    if (server != null) {
        objname = getGroupObjectName("JvmThreading", oid, mibName + ":name=sun.management.snmp.jvmmib.JvmThreading");
    }
    final JvmThreadingMeta meta = createJvmThreadingMetaNode("JvmThreading", oid, objname, server);
    if (meta != null) {
        meta.registerTableNodes( this, server );

        // Note that when using standard metadata,
        // the returned object must implement the "JvmThreadingMBean"
        // interface.
        //
        final JvmThreadingMBean group = (JvmThreadingMBean) createJvmThreadingMBean("JvmThreading", oid, objname, server);
        meta.setInstance( group );
        registerGroupNode("JvmThreading", oid, objname, meta, group, server);
    }
}
 
Example 6
Project: OpenJSharp   File: SnmpAdaptorServer.java   Source Code and License 6 votes vote down vote up
private void createSnmpRequestHandler(SnmpAdaptorServer server,
                                      int id,
                                      DatagramSocket s,
                                      DatagramPacket p,
                                      SnmpMibTree tree,
                                      Vector<SnmpMibAgent> m,
                                      InetAddressAcl a,
                                      SnmpPduFactory factory,
                                      SnmpUserDataFactory dataFactory,
                                      MBeanServer f,
                                      ObjectName n) {
    final SnmpRequestHandler handler =
        new SnmpRequestHandler(this, id, s, p, tree, m, a, factory,
                               dataFactory, f, n);
    threadService.submitTask(handler);
}
 
Example 7
Project: jdk8u-jdk   File: ClientHandler.java   Source Code and License 6 votes vote down vote up
public ClientHandler(CommunicatorServer server, int id, MBeanServer f, ObjectName n) {
    adaptorServer = server ;
    requestId = id ;
    mbs = f ;
    objectName = n ;
    interruptCalled = false ;
    dbgTag = makeDebugTag() ;
    //if (mbs == null ){
    //thread = new Thread (this) ;
    thread =  createThread(this);

    //} else {
    //thread = mbs.getThreadAllocatorSrvIf().obtainThread(objectName,this) ;
    //}
    // Note: the thread will be started by the subclass.
}
 
Example 8
Project: jdk8u-jdk   File: JMXProxyFallbackTest.java   Source Code and License 6 votes vote down vote up
private static void testPrivate(Class<?> iface) throws Exception {
    try {
        System.out.println("Creating a proxy for private M(X)Bean " +
                            iface.getName() + " ...");

        MBeanServer mbs = MBeanServerFactory.newMBeanServer();
        ObjectName on = new ObjectName("test:type=Proxy");

        JMX.newMBeanProxy(mbs, on, iface);
        success("Created a proxy for private M(X)Bean - " + iface.getName());
    } catch (Exception e) {
        Throwable t = e;
        while (t != null && !(t instanceof NotCompliantMBeanException)) {
            t = t.getCause();
        }
        if (t != null) {
            fail("Proxy not created");
        } else {
            throw e;
        }
    }
}
 
Example 9
Project: hadoop   File: TestSecondaryWebUi.java   Source Code and License 6 votes vote down vote up
@Test
public void testSecondaryWebUi()
        throws IOException, MalformedObjectNameException,
               AttributeNotFoundException, MBeanException,
               ReflectionException, InstanceNotFoundException {
  MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  ObjectName mxbeanName = new ObjectName(
          "Hadoop:service=SecondaryNameNode,name=SecondaryNameNodeInfo");

  String[] checkpointDir = (String[]) mbs.getAttribute(mxbeanName,
          "CheckpointDirectories");
  Assert.assertArrayEquals(checkpointDir, snn.getCheckpointDirectories());
  String[] checkpointEditlogDir = (String[]) mbs.getAttribute(mxbeanName,
          "CheckpointEditlogDirectories");
  Assert.assertArrayEquals(checkpointEditlogDir,
          snn.getCheckpointEditlogDirectories());
}
 
Example 10
Project: OpenJSharp   File: JVM_MANAGEMENT_MIB.java   Source Code and License 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
Project: neoscada   File: ManagedConnection.java   Source Code and License 6 votes vote down vote up
public static ManagedConnection register ( final ManagedConnection connection, final SocketAddress socketAddress, final String baseName )
{
    try
    {
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer ();
        logger.debug ( "Creating name for: {}", socketAddress );

        final String remote = URLEncoder.encode ( socketAddress.toString (), "UTF-8" );

        final ObjectName name = new ObjectName ( baseName, "remote", remote );
        connection.setName ( name );
        mbs.registerMBean ( connection, name );
        return connection;
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to register MXBean", e );
        return null;
    }

}
 
Example 12
Project: openjdk-jdk10   File: MBeanFallbackTest.java   Source Code and License 6 votes vote down vote up
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 13
Project: jdk8u-jdk   File: ImmutableNotificationInfoTest.java   Source Code and License 6 votes vote down vote up
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
Project: jdk8u-jdk   File: DefaultMBeanServerInterceptor.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: lams   File: MBeanUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Create and configure (if necessary) and return the
 * <code>MBeanServer</code> with which we will be
 * registering our <code>DynamicMBean</code> implementations.
 */
public synchronized static MBeanServer createServer() {

    if (mserver == null) {
        try {
            mserver = Registry.getRegistry(null, null).getMBeanServer();
        } catch (Throwable t) {
            t.printStackTrace(System.out);
            System.exit(1);
        }
    }
    return (mserver);

}
 
Example 16
Project: log4j2-redis-appender   File: RedisThrottler.java   Source Code and License 5 votes vote down vote up
private void unregisterJmxBean() {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    synchronized (jmxBeanReferenceCountByName) {

        // Get the reference count for the JMX bean.
        Integer jmxBeanReferenceCount = jmxBeanReferenceCountByName.get(jmxBeanName);

        // Check if we have a valid state, that is, jmxBeanReferenceCount > 0.
        if (jmxBeanReferenceCount == null || jmxBeanReferenceCount == 0) {
            logger.debug(
                    "failed unregistering the JMX bean (jmxBeanName=%s, jmxBeanReferenceCount=%s)",
                    jmxBeanName, jmxBeanReferenceCount);
        }

        // If there is just a single reference so far, it is safe to unregister the bean.
        else if (jmxBeanReferenceCount == 1) {
            try {
                mbs.unregisterMBean(jmxBeanName);
                jmxBeanReferenceCountByName.remove(jmxBeanName);
            } catch (Throwable error) {
                logger.debug("failed unregistering the JMX bean (jmxBeanName=%s)", jmxBeanName);
            }
        }

        // Apparently there are more consumers of the bean. Just decrement the reference count.
        else {
            jmxBeanReferenceCountByName.put(jmxBeanName, jmxBeanReferenceCount - 1);
        }

    }
}
 
Example 17
Project: openjdk-jdk10   File: QueryMatchTest.java   Source Code and License 5 votes vote down vote up
private static int query(MBeanServer mbs,
                         String pattern,
                         String[][] data) throws Exception {

    int error = 0;

    System.out.println("\nAttribute Value Pattern = " + pattern + "\n");
    for (int i = 0; i < data.length; i++) {
        ObjectName on = new ObjectName("domain:type=Simple,pattern=" +
                                       ObjectName.quote(pattern) +
                                       ",name=" + i);
        Simple s = new Simple(data[i][0]);
        mbs.registerMBean(s, on);
        QueryExp q =
            Query.match(Query.attr("StringNumber"), Query.value(pattern));
        q.setMBeanServer(mbs);
        boolean r = q.apply(on);
        System.out.print("Attribute Value = " +
            mbs.getAttribute(on, "StringNumber"));
        if (r && "OK".equals(data[i][1])) {
            System.out.println(" OK");
        } else if (!r && "KO".equals(data[i][1])) {
            System.out.println(" KO");
        } else {
            System.out.println(" Error");
            error++;
        }
    }

    return error;
}
 
Example 18
Project: hashsdn-controller   File: AbstractDynamicWrapper.java   Source Code and License 5 votes vote down vote up
public AbstractDynamicWrapper(final Module module, final boolean writable, final ModuleIdentifier moduleIdentifier,
        final ObjectName thisWrapperObjectName, final MBeanOperationInfo[] operations,
        final MBeanServer internalServer, final MBeanServer configMBeanServer) {
    this.module = module;
    this.moduleIdentifier = moduleIdentifier;
    this.internalServer = internalServer;
    this.objectNameInternal = thisWrapperObjectName;
    // register the actual instance into an mbean server.
    registerActualModule(objectNameInternal, configMBeanServer);
    Set<Class<?>> jmxInterfaces = InterfacesHelper.getMXInterfaces(module.getClass());
    this.attributeHolderMap = buildMBeanInfo(writable, moduleIdentifier, jmxInterfaces, objectNameInternal);
    this.mbeanInfo = generateMBeanInfo(module, attributeHolderMap, operations, jmxInterfaces);
}
 
Example 19
Project: lams   File: QuartzScheduler.java   Source Code and License 5 votes vote down vote up
/**
 * Register the scheduler in the local MBeanServer.
 */
private void registerJMX() throws Exception {
    String jmxObjectName = resources.getJMXObjectName();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    jmxBean = new QuartzSchedulerMBeanImpl(this);
    mbs.registerMBean(jmxBean, new ObjectName(jmxObjectName));
}
 
Example 20
Project: lazycat   File: StatusTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Write detailed information about a manager.
 */
public static void writeManager(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode)
		throws Exception {

	if (mode == 0) {
		writer.print("<br>");
		writer.print(" Active sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "activeSessions"));
		writer.print(" Session count: ");
		writer.print(mBeanServer.getAttribute(objectName, "sessionCounter"));
		writer.print(" Max active sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "maxActive"));
		writer.print(" Rejected session creations: ");
		writer.print(mBeanServer.getAttribute(objectName, "rejectedSessions"));
		writer.print(" Expired sessions: ");
		writer.print(mBeanServer.getAttribute(objectName, "expiredSessions"));
		writer.print(" Longest session alive time: ");
		writer.print(formatSeconds(mBeanServer.getAttribute(objectName, "sessionMaxAliveTime")));
		writer.print(" Average session alive time: ");
		writer.print(formatSeconds(mBeanServer.getAttribute(objectName, "sessionAverageAliveTime")));
		writer.print(" Processing time: ");
		writer.print(formatTime(mBeanServer.getAttribute(objectName, "processingTime"), false));
	} else if (mode == 1) {
		// for now we don't write out the wrapper details
	}

}
 
Example 21
Project: jdk8u-jdk   File: JmxMBeanServer.java   Source Code and License 5 votes vote down vote up
/**
 * <b>Package:</b> Creates an MBeanServer.
 * @param domain The default domain name used by this MBeanServer.
 * @param outer A pointer to the MBeanServer object that must be
 *        passed to the MBeans when invoking their
 *        {@link javax.management.MBeanRegistration} interface.
 * @param delegate A pointer to the MBeanServerDelegate associated
 *        with the new MBeanServer. The new MBeanServer must register
 *        this MBean in its MBean repository.
 * @param instantiator The MBeanInstantiator that will be used to
 *        instantiate MBeans and take care of class loading issues.
 * @param metadata The MetaData object that will be used by the
 *        MBean server in order to invoke the MBean interface of
 *        the registered MBeans.
 * @param interceptors If <code>true</code>,
 *        {@link MBeanServerInterceptor} will be enabled (default is
 *        <code>false</code>).
 * @param fairLock If {@code true}, the MBean repository will use a {@link
 *        java.util.concurrent.locks.ReentrantReadWriteLock#ReentrantReadWriteLock(boolean)
 *        fair locking} policy.
 */
JmxMBeanServer(String domain, MBeanServer outer,
               MBeanServerDelegate    delegate,
               MBeanInstantiator      instantiator,
               boolean                interceptors,
               boolean                fairLock)  {

    if (instantiator == null) {
        final ModifiableClassLoaderRepository
            clr = new ClassLoaderRepositorySupport();
        instantiator = new MBeanInstantiator(clr);
    }

    final MBeanInstantiator fInstantiator = instantiator;
    this.secureClr = new
        SecureClassLoaderRepository(AccessController.doPrivileged(new PrivilegedAction<ClassLoaderRepository>() {
            @Override
            public ClassLoaderRepository run() {
                return fInstantiator.getClassLoaderRepository();
            }
        })
    );
    if (delegate == null)
        delegate = new MBeanServerDelegateImpl();
    if (outer == null)
        outer = this;

    this.instantiator = instantiator;
    this.mBeanServerDelegateObject = delegate;
    this.outerShell   = outer;

    final Repository repository = new Repository(domain);
    this.mbsInterceptor =
        new DefaultMBeanServerInterceptor(outer, delegate, instantiator,
                                          repository);
    this.interceptorsEnabled = interceptors;
    initialize();
}
 
Example 22
Project: kafka-0.11.0.0-src-with-comment   File: AppInfoParser.java   Source Code and License 5 votes vote down vote up
public static void unregisterAppInfo(String prefix, String id) {
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName name = new ObjectName(prefix + ":type=app-info,id=" + id);
        if (server.isRegistered(name))
            server.unregisterMBean(name);
    } catch (JMException e) {
        log.warn("Error unregistering AppInfo mbean", e);
    }
}
 
Example 23
Project: OpenJSharp   File: JvmMemoryMeta.java   Source Code and License 5 votes vote down vote up
/**
 * Register the group's SnmpMibTable objects with the meta-data.
 */
public void registerTableNodes(SnmpMib mib, MBeanServer server) {
    tableJvmMemMgrPoolRelTable = createJvmMemMgrPoolRelTableMetaNode("JvmMemMgrPoolRelTable", "JvmMemory", mib, server);
    if ( tableJvmMemMgrPoolRelTable != null)  {
        tableJvmMemMgrPoolRelTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmMemMgrPoolRelTable", tableJvmMemMgrPoolRelTable);
    }

    tableJvmMemPoolTable = createJvmMemPoolTableMetaNode("JvmMemPoolTable", "JvmMemory", mib, server);
    if ( tableJvmMemPoolTable != null)  {
        tableJvmMemPoolTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmMemPoolTable", tableJvmMemPoolTable);
    }

    tableJvmMemGCTable = createJvmMemGCTableMetaNode("JvmMemGCTable", "JvmMemory", mib, server);
    if ( tableJvmMemGCTable != null)  {
        tableJvmMemGCTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmMemGCTable", tableJvmMemGCTable);
    }

    tableJvmMemManagerTable = createJvmMemManagerTableMetaNode("JvmMemManagerTable", "JvmMemory", mib, server);
    if ( tableJvmMemManagerTable != null)  {
        tableJvmMemManagerTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmMemManagerTable", tableJvmMemManagerTable);
    }

}
 
Example 24
Project: hashsdn-controller   File: DependencyResolverImpl.java   Source Code and License 5 votes vote down vote up
public DependencyResolverImpl(final ModuleIdentifier currentModule, final TransactionStatus transactionStatus,
        final ModulesHolder modulesHolder, final ServiceReferenceReadableRegistry readableRegistry,
        final BindingContextProvider bindingContextProvider, final String transactionName,
        final MBeanServer beanServer) {
    this.bindingContextProvider = bindingContextProvider;
    this.name = currentModule;
    this.transactionStatus = transactionStatus;
    this.modulesHolder = modulesHolder;
    this.readableRegistry = readableRegistry;
    this.transactionName = transactionName;
    this.beanServer = beanServer;
}
 
Example 25
Project: OpenJSharp   File: JvmRuntimeMeta.java   Source Code and License 5 votes vote down vote up
/**
 * Register the group's SnmpMibTable objects with the meta-data.
 */
public void registerTableNodes(SnmpMib mib, MBeanServer server) {
    tableJvmRTLibraryPathTable = createJvmRTLibraryPathTableMetaNode("JvmRTLibraryPathTable", "JvmRuntime", mib, server);
    if ( tableJvmRTLibraryPathTable != null)  {
        tableJvmRTLibraryPathTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmRTLibraryPathTable", tableJvmRTLibraryPathTable);
    }

    tableJvmRTClassPathTable = createJvmRTClassPathTableMetaNode("JvmRTClassPathTable", "JvmRuntime", mib, server);
    if ( tableJvmRTClassPathTable != null)  {
        tableJvmRTClassPathTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmRTClassPathTable", tableJvmRTClassPathTable);
    }

    tableJvmRTBootClassPathTable = createJvmRTBootClassPathTableMetaNode("JvmRTBootClassPathTable", "JvmRuntime", mib, server);
    if ( tableJvmRTBootClassPathTable != null)  {
        tableJvmRTBootClassPathTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmRTBootClassPathTable", tableJvmRTBootClassPathTable);
    }

    tableJvmRTInputArgsTable = createJvmRTInputArgsTableMetaNode("JvmRTInputArgsTable", "JvmRuntime", mib, server);
    if ( tableJvmRTInputArgsTable != null)  {
        tableJvmRTInputArgsTable.registerEntryNode(mib,server);
        mib.registerTableMeta("JvmRTInputArgsTable", tableJvmRTInputArgsTable);
    }

}
 
Example 26
Project: hadoop   File: TestHostsFiles.java   Source Code and License 5 votes vote down vote up
@Test
public void testHostsIncludeForDeadCount() throws Exception {
  Configuration conf = getConf();

  // Configure an excludes file
  FileSystem localFileSys = FileSystem.getLocal(conf);
  Path workingDir = localFileSys.getWorkingDirectory();
  Path dir = new Path(workingDir, "build/test/data/temp/decommission");
  Path excludeFile = new Path(dir, "exclude");
  Path includeFile = new Path(dir, "include");
  assertTrue(localFileSys.mkdirs(dir));
  StringBuilder includeHosts = new StringBuilder();
  includeHosts.append("localhost:52").append("\n").append("127.0.0.1:7777")
      .append("\n");
  DFSTestUtil.writeFile(localFileSys, excludeFile, "");
  DFSTestUtil.writeFile(localFileSys, includeFile, includeHosts.toString());
  conf.set(DFSConfigKeys.DFS_HOSTS_EXCLUDE, excludeFile.toUri().getPath());
  conf.set(DFSConfigKeys.DFS_HOSTS, includeFile.toUri().getPath());

  MiniDFSCluster cluster = null;
  try {
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
    final FSNamesystem ns = cluster.getNameNode().getNamesystem();
    assertTrue(ns.getNumDeadDataNodes() == 2);
    assertTrue(ns.getNumLiveDataNodes() == 0);

    // Testing using MBeans
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanName = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");
    String nodes = mbs.getAttribute(mxbeanName, "NumDeadDataNodes") + "";
    assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumDeadDataNodes") == 2);
    assertTrue((Integer) mbs.getAttribute(mxbeanName, "NumLiveDataNodes") == 0);
  } finally {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 27
Project: hadoop   File: TestNameNodeMXBean.java   Source Code and License 5 votes vote down vote up
@Test(timeout=120000)
public void testTopUsersDisabled() throws Exception {
  final Configuration conf = new Configuration();
  // Disable nntop
  conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, false);
  MiniDFSCluster cluster = null;
  try {
    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build();
    cluster.waitActive();
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanNameFsns = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");
    FileSystem fs = cluster.getFileSystem();
    final Path path = new Path("/");
    final int NUM_OPS = 10;
    for (int i=0; i< NUM_OPS; i++) {
      fs.listStatus(path);
      fs.setTimes(path, 0, 1);
    }
    String topUsers =
        (String) (mbs.getAttribute(mxbeanNameFsns, "TopUserOpCounts"));
    assertNull("Did not expect to find TopUserOpCounts bean!", topUsers);
  } finally {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 28
Project: OpenJSharp   File: MXBeanSupport.java   Source Code and License 5 votes vote down vote up
@Override
public void register(MBeanServer server, ObjectName name)
        throws InstanceAlreadyExistsException {
    if (name == null)
        throw new IllegalArgumentException("Null object name");
    // eventually we could have some logic to supply a default name

    synchronized (lock) {
        this.mxbeanLookup = MXBeanLookup.lookupFor(server);
        this.mxbeanLookup.addReference(name, getResource());
        this.objectName = name;
    }
}
 
Example 29
Project: jdk8u-jdk   File: JMXProxyTest.java   Source Code and License 5 votes vote down vote up
private static void testCompliant(Class<?> iface, boolean isMx) throws Exception {
    try {
        System.out.println("Creating a proxy for compliant " +
                           (isMx ? "MXBean" : "MBean") + " " +
                           iface.getName() + " ...");

        MBeanServer mbs = MBeanServerFactory.newMBeanServer();
        ObjectName on = new ObjectName("test:type=Proxy");

        if (isMx) {
            JMX.newMXBeanProxy(mbs, on, iface);
        } else {
            JMX.newMBeanProxy(mbs, on, iface);
        }
        success("Created a proxy for compliant " +
                (isMx ? "MXBean" : "MBean") + " - " + iface.getName());
    } catch (Exception e) {
        Throwable t = e;
        while (t != null && !(t instanceof NotCompliantMBeanException)) {
            t = t.getCause();
        }
        if (t != null) {
            fail("Proxy not created");
        } else {
            throw e;
        }
    }
}
 
Example 30
Project: tomcat7   File: MBeanUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Create and configure (if necessary) and return the
 * <code>MBeanServer</code> with which we will be
 * registering our <code>DynamicMBean</code> implementations.
 */
public static synchronized MBeanServer createServer() {

    if (mserver == null) {
        mserver = Registry.getRegistry(null, null).getMBeanServer();
    }
    return (mserver);

}
 
Example 31
Project: tomcat7   File: LifecycleMBeanBase.java   Source Code and License 5 votes vote down vote up
/**
 * Allows the object to be registered with an alternative
 * {@link MBeanServer} and/or {@link ObjectName}.
 */
@Override
public final ObjectName preRegister(MBeanServer server, ObjectName name)
        throws Exception {
    
    this.mserver = server;
    this.oname = name;
    this.domain = name.getDomain();

    return oname;
}
 
Example 32
Project: lams   File: ValveBase.java   Source Code and License 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception {
    oname=name;
    mserver=server;
    domain=name.getDomain();


    return name;
}
 
Example 33
Project: OpenJSharp   File: AMXGlassfish.java   Source Code and License 5 votes vote down vote up
public ObjectName bootAMX(final MBeanServer server)
{
    try
    {
        return bootAMX( (MBeanServerConnection)server);
    }
    catch( final IOException e )
    {
        throw new RuntimeException(e);
    }
}
 
Example 34
Project: apache-tomcat-7.0.73-with-comment   File: DataSource.java   Source Code and License 5 votes vote down vote up
/**
 * If the connection pool MBean exists, it will be registered during this operation.<br/>
 * {@inheritDoc}
 */
@Override
public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
    try {
        if ( isJmxEnabled() ) { 
            this.oname = createObjectName(name);
            if (oname!=null) registerJmx();
        }
    }catch (MalformedObjectNameException x) {
        log.error("Unable to create object name for JDBC pool.",x);
    }
    return name;
}
 
Example 35
Project: tomcat7   File: JmxPasswordTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPassword() throws Exception {
    Assert.assertEquals("Passwords should match when not using JMX.",password,datasource.getPoolProperties().getPassword());
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ConnectionPoolMBean mbean = JMX.newMBeanProxy(mbs, oname, ConnectionPoolMBean.class);
    String jmxPassword = mbean.getPassword();
    Properties jmxProperties = mbean.getDbProperties();
    Assert.assertFalse("Passwords should not match.", password.equals(jmxPassword));
    Assert.assertFalse("Password property should be missing", jmxProperties.containsKey(PoolUtilities.PROP_PASSWORD));
}
 
Example 36
Project: AeroStory   File: TimerManager.java   Source Code and License 5 votes vote down vote up
private TimerManager() {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        mBeanServer.registerMBean(this, new ObjectName("server:type=TimerManger"));
    } catch (Exception e) {
    }
}
 
Example 37
Project: NSS   File: SocksServer.java   Source Code and License 5 votes vote down vote up
/**
 * java MBean 进行流量统计
 */
private void startMBean() {
	MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
	IoAcceptorStat mbean = new IoAcceptorStat();

	try {
		ObjectName acceptorName = new ObjectName(mbean.getClass()
				.getPackage().getName()
				+ ":type=IoAcceptorStat");
		mBeanServer.registerMBean(mbean, acceptorName);
	} catch (Exception e) {
		logger.error("java MBean error", e);
	}
}
 
Example 38
Project: hashsdn-controller   File: DependencyResolverManager.java   Source Code and License 5 votes vote down vote up
public DependencyResolverManager(final TransactionIdentifier transactionIdentifier,
        final TransactionStatus transactionStatus, final ServiceReferenceReadableRegistry readableRegistry,
        final BindingContextProvider bindingContextProvider, final MBeanServer beanServer) {
    this.transactionIdentifier = transactionIdentifier;
    this.modulesHolder = new ModulesHolder(transactionIdentifier);
    this.transactionStatus = transactionStatus;
    this.readableRegistry = readableRegistry;
    this.bindingContextProvider = bindingContextProvider;
    this.deadlockMonitor = new DeadlockMonitor(transactionIdentifier);
    this.beanServer = beanServer;
}
 
Example 39
Project: jdk8u-jdk   File: ImplVersionCommand.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();

    // Get the JMX implementation version from the MBeanServerDelegateMBean
    //
    System.out.println("Get the JMX implementation version");
    ObjectName mbsdName =
        new ObjectName("JMImplementation:type=MBeanServerDelegate");
    String mbsdAttribute = "ImplementationVersion";
    String mbsdVersion = (String) mbs.getAttribute(mbsdName, mbsdAttribute);

    // Display JMX implementation version and JVM implementation version
    //
    System.out.println("JMX implementation version          = " +
                       mbsdVersion);
    System.out.println("Java Runtime implementation version = " +
                       args[0]);

    // Check JMX implementation version vs. JVM implementation version
    //
    if (Boolean.valueOf(args[1]).booleanValue()) {
        if (!mbsdVersion.equals(args[0]))
            throw new IllegalArgumentException(
              "JMX and Java Runtime implementation versions do not match!");
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions match!");
    } else {
        // Test OK!
        //
        System.out.println("JMX and Java Runtime implementation " +
                           "versions do not match because the test " +
                           "is using an unbundled version of JMX!");
    }
    System.out.println("Bye! Bye!");
}
 
Example 40
Project: openjdk-jdk10   File: MXBeanFallbackTest.java   Source Code and License 5 votes vote down vote up
private static void testPrivateMXBean(String type, Object bean) throws Exception {
    System.out.println(type + " MXBean test...");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName on = new ObjectName("test:type=" + type);
    try {
        mbs.registerMBean(bean, on);
        success("Private MXBean registered");
    } catch (NotCompliantMBeanException e) {
        failure("Failed to register the private MXBean - " +
                 bean.getClass().getInterfaces()[0].getName());
    }
}
 
Example 41
Project: lams   File: Http11Protocol.java   Source Code and License 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception {
    oname=name;
    mserver=server;
    domain=name.getDomain();
    return name;
}
 
Example 42
Project: jdk8u-jdk   File: Server.java   Source Code and License 5 votes vote down vote up
public static String start() throws Exception {
    int serverPort = 12345;
    ObjectName name = new ObjectName("test", "foo", "bar");
    MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    SteMBean bean = new Ste();
    jmxServer.registerMBean(bean, name);
    boolean exported = false;
    Random rnd = new Random(System.currentTimeMillis());
    do {
        try {
            LocateRegistry.createRegistry(serverPort);
            exported = true;
        } catch (ExportException ee) {
            if (ee.getCause() instanceof BindException) {
                serverPort = rnd.nextInt(10000) + 4096;
            } else {
                throw ee;
            }
        }

    } while (!exported);
    JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
    JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
    jmxConnector.start();

    return serverUrl.toString();
}
 
Example 43
Project: lams   File: AjpAprProtocol.java   Source Code and License 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception {
    oname=name;
    mserver=server;
    domain=name.getDomain();
    return name;
}
 
Example 44
Project: hashsdn-controller   File: DynamicWritableWrapper.java   Source Code and License 5 votes vote down vote up
public DynamicWritableWrapper(final Module module, final ModuleIdentifier moduleIdentifier,
        final String transactionIdentifier, final ReadOnlyAtomicBoolean configBeanModificationDisabled,
        final MBeanServer internalServer, final MBeanServer configMBeanServer) {
    super(module, true, moduleIdentifier,
            ObjectNameUtil.createTransactionModuleON(transactionIdentifier, moduleIdentifier),
            getOperations(moduleIdentifier), internalServer, configMBeanServer);
    this.configBeanModificationDisabled = configBeanModificationDisabled;
}
 
Example 45
Project: https-github.com-apache-zookeeper   File: JMXEnv.java   Source Code and License 5 votes vote down vote up
public static void setUp() throws IOException {
    MBeanServer mbs = MBeanRegistry.getInstance().getPlatformMBeanServer();
    
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1");
    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();

   JMXServiceURL addr = cs.getAddress();
    
   cc = JMXConnectorFactory.connect(addr);
}
 
Example 46
Project: hadoop   File: TestFSNamesystemMBean.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws Exception {
  Configuration conf = new Configuration();
  MiniDFSCluster cluster = null;

  try {
    cluster = new MiniDFSCluster.Builder(conf).build();
    cluster.waitActive();

    FSNamesystem fsn = cluster.getNameNode().namesystem;

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName mxbeanName = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");

    String snapshotStats = (String) (mbs.getAttribute(mxbeanName,
        "SnapshotStats"));

    @SuppressWarnings("unchecked")
    Map<String, Object> stat = (Map<String, Object>) JSON
        .parse(snapshotStats);

    assertTrue(stat.containsKey("SnapshottableDirectories")
        && (Long) stat.get("SnapshottableDirectories") == fsn
            .getNumSnapshottableDirs());
    assertTrue(stat.containsKey("Snapshots")
        && (Long) stat.get("Snapshots") == fsn.getNumSnapshots());

    Object pendingDeletionBlocks = mbs.getAttribute(mxbeanName,
      "PendingDeletionBlocks");
    assertNotNull(pendingDeletionBlocks);
    assertTrue(pendingDeletionBlocks instanceof Long);
  } finally {
    if (cluster != null) {
      cluster.shutdown();
    }
  }
}
 
Example 47
Project: jspider   File: SpiderMonitor.java   Source Code and License 4 votes vote down vote up
public MBeanServer getMbeanServer() {
    return mbeanServer;
}
 
Example 48
Project: openjdk-jdk10   File: UnexpectedNotifTest.java   Source Code and License 4 votes vote down vote up
private static void test(String proto) throws Exception {
    System.out.println("Unexpected notifications test for protocol " +
                       proto);
    MBeanServer mbs = null;
    try {
        // Create a MBeanServer
        //
        mbs = MBeanServerFactory.createMBeanServer();

        // Create a NotificationEmitter MBean
        //
        mbean = new ObjectName ("Default:name=NotificationEmitter");
        mbs.registerMBean(new NotificationEmitter(), mbean);

        // Create a connector server
        //
        url = new JMXServiceURL("service:jmx:" + proto + "://");

        server = JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                 null,
                                                                 mbs);

        mbs.registerMBean(
                    server,
                    new ObjectName("Default:name=ConnectorServer"));

        server.start();

        url = server.getAddress();

        for (int j = 0; j < 2; j++) {
            test();
        }
    } finally {
        // Stop server
        //
        server.stop();
        // Release the MBeanServer
        //
        MBeanServerFactory.releaseMBeanServer(mbs);
    }
}
 
Example 49
Project: jdk8u-jdk   File: JvmMemPoolTableMeta.java   Source Code and License 4 votes vote down vote up
public void registerEntryNode(SnmpMib mib, MBeanServer server)  {
    node = createJvmMemPoolEntryMetaNode("JvmMemPoolEntry", "JvmMemPoolTable", mib, server);
}
 
Example 50
Project: jdk8u-jdk   File: JvmRTBootClassPathTableMeta.java   Source Code and License 4 votes vote down vote up
public void registerEntryNode(SnmpMib mib, MBeanServer server)  {
    node = createJvmRTBootClassPathEntryMetaNode("JvmRTBootClassPathEntry", "JvmRTBootClassPathTable", mib, server);
}
 
Example 51
Project: openjdk-jdk10   File: MBeanSupport.java   Source Code and License 4 votes vote down vote up
public abstract void register(MBeanServer mbs, ObjectName name)
throws Exception;
 
Example 52
Project: Pogamut3   File: PogamutPlatformProxy.java   Source Code and License 4 votes vote down vote up
@Override
public MBeanServer getMBeanServer() throws PogamutException {
    return platform.getMBeanServer();
}
 
Example 53
Project: jdk8u-jdk   File: EmptyDomainNotificationTest.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

        JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
        server.start();

        JMXConnector client = JMXConnectorFactory.connect(server.getAddress(), null);

        final MBeanServerConnection mbsc = client.getMBeanServerConnection();

        final ObjectName mbean = ObjectName.getInstance(":type=Simple");
        mbsc.createMBean(Simple.class.getName(), mbean);

        System.out.println("EmptyDomainNotificationTest-main: add a listener ...");
        final Listener li = new Listener();
        mbsc.addNotificationListener(mbean, li, null, null);

        System.out.println("EmptyDomainNotificationTest-main: ask to send a notif ...");
        mbsc.invoke(mbean, "emitNotification", null, null);

        System.out.println("EmptyDomainNotificationTest-main: waiting notif...");
        final long stopTime = System.currentTimeMillis() + 2000;
        synchronized(li) {
            long toWait = stopTime - System.currentTimeMillis();

            while (li.received < 1 && toWait > 0) {
                li.wait(toWait);

                toWait = stopTime - System.currentTimeMillis();
            }
        }

        if (li.received < 1) {
            throw new RuntimeException("No notif received!");
        } else if (li.received > 1) {
            throw new RuntimeException("Wait one notif but got: "+li.received);
        }

        System.out.println("EmptyDomainNotificationTest-main: Got the expected notif!");

        System.out.println("EmptyDomainNotificationTest-main: remove the listener.");
        mbsc.removeNotificationListener(mbean, li);

        // clean
        client.close();
        server.stop();

        System.out.println("EmptyDomainNotificationTest-main: Bye.");
    }
 
Example 54
Project: OpenJSharp   File: JvmRTInputArgsTableMeta.java   Source Code and License 4 votes vote down vote up
public void registerEntryNode(SnmpMib mib, MBeanServer server)  {
    node = createJvmRTInputArgsEntryMetaNode("JvmRTInputArgsEntry", "JvmRTInputArgsTable", mib, server);
}
 
Example 55
Project: lams   File: Registry.java   Source Code and License 4 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception 
{
    this.server=server;
    return name;
}
 
Example 56
Project: openjdk-jdk10   File: CounterMonitorDeadlockTest.java   Source Code and License 4 votes vote down vote up
void run() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName observedName = new ObjectName("a:b=c");
    final ObjectName monitorName = new ObjectName("a:type=Monitor");
    mbs.registerMBean(new CounterMonitor(), monitorName);
    final CounterMonitorMBean monitorProxy =
        JMX.newMBeanProxy(mbs, monitorName, CounterMonitorMBean.class);
    final TestMBean observedProxy =
        JMX.newMBeanProxy(mbs, observedName, TestMBean.class);

    final Runnable sensitiveThing = new Runnable() {
        public void run() {
            doSensitiveThing(monitorProxy, observedName);
        }
    };

    final Runnable nothing = new Runnable() {
        public void run() {}
    };

    final Runnable withinGetAttribute =
        (when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;

    mbs.registerMBean(new Test(withinGetAttribute), observedName);
    monitorProxy.addObservedObject(observedName);
    monitorProxy.setObservedAttribute("Thing");
    monitorProxy.setInitThreshold(100);
    monitorProxy.setGranularityPeriod(10L); // 10 ms
    monitorProxy.setNotify(true);

    final int initGetCount = observedProxy.getGetCount();
    monitorProxy.start();

    System.out.println("Checking GetCount, possible deadlock if timeout.");
    do { // 8038322. Until timeout of testing harness
        Thread.sleep(200);
    } while ((observedProxy.getGetCount()) == initGetCount);
    System.out.println("Done!");

    // This won't show up as a deadlock in CTRL-\ or in
    // ThreadMXBean.findDeadlockedThreads(), because they don't
    // see that thread A is waiting for thread B (B.join()), and
    // thread B is waiting for a lock held by thread A

    // Now we know the monitor has observed the initial value,
    // so if we want to test notify behaviour we can trigger by
    // exceeding the threshold.
    if (when == When.IN_NOTIFY) {
        final AtomicInteger notifCount = new AtomicInteger();
        final NotificationListener listener = new NotificationListener() {
            public void handleNotification(Notification n, Object h) {
                Thread t = new Thread(sensitiveThing);
                t.start();
                try {
                    t.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                notifCount.incrementAndGet();
            }
        };
        mbs.addNotificationListener(monitorName, listener, null, null);
        observedProxy.setThing(1000);
        System.out.println("Waiting notifCount.get() != 0, possible deadlock if timeout.");
        do {
            Thread.sleep(200);
        } while(notifCount.get() == 0); // 8038322. Until timeout of testing harness
        System.out.println("Done");
    }

}
 
Example 57
Project: OpenJSharp   File: JvmMemMgrPoolRelTableMeta.java   Source Code and License 4 votes vote down vote up
public void registerEntryNode(SnmpMib mib, MBeanServer server)  {
    node = createJvmMemMgrPoolRelEntryMetaNode("JvmMemMgrPoolRelEntry", "JvmMemMgrPoolRelTable", mib, server);
}
 
Example 58
Project: openjdk-jdk10   File: ManagementFactory.java   Source Code and License 4 votes vote down vote up
/**
 * Returns the platform {@link javax.management.MBeanServer MBeanServer}.
 * On the first call to this method, it first creates the platform
 * {@code MBeanServer} by calling the
 * {@link javax.management.MBeanServerFactory#createMBeanServer
 * MBeanServerFactory.createMBeanServer}
 * method and registers each platform MXBean in this platform
 * {@code MBeanServer} with its
 * {@link PlatformManagedObject#getObjectName ObjectName}.
 * This method, in subsequent calls, will simply return the
 * initially created platform {@code MBeanServer}.
 * <p>
 * MXBeans that get created and destroyed dynamically, for example,
 * memory {@link MemoryPoolMXBean pools} and
 * {@link MemoryManagerMXBean managers},
 * will automatically be registered and deregistered into the platform
 * {@code MBeanServer}.
 * <p>
 * If the system property {@code javax.management.builder.initial}
 * is set, the platform {@code MBeanServer} creation will be done
 * by the specified {@link javax.management.MBeanServerBuilder}.
 * <p>
 * It is recommended that this platform MBeanServer also be used
 * to register other application managed beans
 * besides the platform MXBeans.
 * This will allow all MBeans to be published through the same
 * {@code MBeanServer} and hence allow for easier network publishing
 * and discovery.
 * Name conflicts with the platform MXBeans should be avoided.
 *
 * @return the platform {@code MBeanServer}; the platform
 *         MXBeans are registered into the platform {@code MBeanServer}
 *         at the first time this method is called.
 *
 * @exception SecurityException if there is a security manager
 * and the caller does not have the permission required by
 * {@link javax.management.MBeanServerFactory#createMBeanServer}.
 *
 * @see javax.management.MBeanServerFactory
 * @see javax.management.MBeanServerFactory#createMBeanServer
 */
public static synchronized MBeanServer getPlatformMBeanServer() {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanServerPermission("createMBeanServer");
        sm.checkPermission(perm);
    }

    if (platformMBeanServer == null) {
        platformMBeanServer = MBeanServerFactory.createMBeanServer();
        platformComponents()
                .stream()
                .filter(PlatformComponent::shouldRegister)
                .flatMap(pc -> pc.nameToMBeanMap().entrySet().stream())
                .forEach(entry -> addMXBean(platformMBeanServer, entry.getKey(), entry.getValue()));
    }
    return platformMBeanServer;
}
 
Example 59
Project: jdk8u-jdk   File: GetMBeansFromURLTest.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        boolean error = false;

        // Instantiate the MBean server
        //
        System.out.println("Create the MBean server");
        MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        // Instantiate an MLet
        //
        System.out.println("Create the MLet");
        MLet mlet = new MLet();

        // Register the MLet MBean with the MBeanServer
        //
        System.out.println("Register the MLet MBean");
        ObjectName mletObjectName = new ObjectName("Test:type=MLet");
        mbs.registerMBean(mlet, mletObjectName);

        // Call getMBeansFromURL
        //
        System.out.println("Call mlet.getMBeansFromURL(<url>)");
        try {
            mlet.getMBeansFromURL("bogus://whatever");
            System.out.println("TEST FAILED: Expected " +
                               ServiceNotFoundException.class +
                               " exception not thrown.");
            error = true;
        } catch (ServiceNotFoundException e) {
            if (e.getCause() == null) {
                System.out.println("TEST FAILED: Got null cause in " +
                                   ServiceNotFoundException.class +
                                   " exception.");
                error = true;
            } else {
                System.out.println("TEST PASSED: Got non-null cause in " +
                                   ServiceNotFoundException.class +
                                   " exception.");
                error = false;
            }
            e.printStackTrace(System.out);
        }

        // Unregister the MLet MBean
        //
        System.out.println("Unregister the MLet MBean");
        mbs.unregisterMBean(mletObjectName);

        // Release MBean server
        //
        System.out.println("Release the MBean server");
        MBeanServerFactory.releaseMBeanServer(mbs);

        // End Test
        //
        System.out.println("Bye! Bye!");
        if (error) System.exit(1);
    }
 
Example 60
Project: openjdk-jdk10   File: ArrayNotificationBuffer.java   Source Code and License 4 votes vote down vote up
public boolean apply(final ObjectName name) {
    final MBeanServer mbs = QueryEval.getMBeanServer();
    return isInstanceOf(mbs, name, broadcasterClass);
}