Java 类javax.management.MBeanServer 实例源码

项目:monarch    文件:AgentImpl.java   
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);
}
项目:metrics-tomcat    文件:AnnotatedStandardMBean.java   
@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();
}
项目:openjdk-jdk10    文件:ConnectorStopDeadlockTest.java   
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");
}
项目:OpenJSharp    文件: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);
    }
}
项目:jdk8u-jdk    文件:JVM_MANAGEMENT_MIB.java   
/**
 * 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);
    }
}
项目:OpenJSharp    文件:SnmpAdaptorServer.java   
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);
}
项目:jdk8u-jdk    文件:ClientHandler.java   
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.
}
项目:jdk8u-jdk    文件:JMXProxyFallbackTest.java   
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;
        }
    }
}
项目:hadoop    文件:TestSecondaryWebUi.java   
@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());
}
项目:OpenJSharp    文件: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;
}
项目:neoscada    文件:ManagedConnection.java   
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;
    }

}
项目:openjdk-jdk10    文件: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;
        }
    }
}
项目:jdk8u-jdk    文件:ImmutableNotificationInfoTest.java   
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;
    }
}
项目:jdk8u-jdk    文件:DefaultMBeanServerInterceptor.java   
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;
}
项目:lams    文件:MBeanUtils.java   
/**
 * 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);

}
项目:log4j2-redis-appender    文件:RedisThrottler.java   
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);
        }

    }
}
项目:openjdk-jdk10    文件:QueryMatchTest.java   
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;
}
项目:hashsdn-controller    文件:AbstractDynamicWrapper.java   
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);
}
项目:lams    文件:QuartzScheduler.java   
/**
 * 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));
}
项目:lazycat    文件:StatusTransformer.java   
/**
 * 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
    }

}
项目:jdk8u-jdk    文件:JmxMBeanServer.java   
/**
 * <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();
}
项目:kafka-0.11.0.0-src-with-comment    文件:AppInfoParser.java   
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);
    }
}
项目:OpenJSharp    文件:JvmMemoryMeta.java   
/**
 * 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);
    }

}
项目:hashsdn-controller    文件:DependencyResolverImpl.java   
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;
}
项目:OpenJSharp    文件:JvmRuntimeMeta.java   
/**
 * 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);
    }

}
项目:hadoop    文件:TestHostsFiles.java   
@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();
    }
  }
}
项目:hadoop    文件:TestNameNodeMXBean.java   
@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();
    }
  }
}
项目:OpenJSharp    文件:MXBeanSupport.java   
@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;
    }
}
项目:jdk8u-jdk    文件:JMXProxyTest.java   
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;
        }
    }
}
项目:tomcat7    文件:MBeanUtils.java   
/**
 * 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);

}
项目:tomcat7    文件:LifecycleMBeanBase.java   
/**
 * 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;
}
项目:lams    文件:ValveBase.java   
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws Exception {
    oname=name;
    mserver=server;
    domain=name.getDomain();


    return name;
}
项目:OpenJSharp    文件:AMXGlassfish.java   
public ObjectName bootAMX(final MBeanServer server)
{
    try
    {
        return bootAMX( (MBeanServerConnection)server);
    }
    catch( final IOException e )
    {
        throw new RuntimeException(e);
    }
}
项目:apache-tomcat-7.0.73-with-comment    文件:DataSource.java   
/**
 * 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;
}
项目:tomcat7    文件:JmxPasswordTest.java   
@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));
}
项目:AeroStory    文件:TimerManager.java   
private TimerManager() {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        mBeanServer.registerMBean(this, new ObjectName("server:type=TimerManger"));
    } catch (Exception e) {
    }
}
项目:NSS    文件:SocksServer.java   
/**
 * 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);
    }
}
项目:hashsdn-controller    文件:DependencyResolverManager.java   
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;
}
项目:jdk8u-jdk    文件:ImplVersionCommand.java   
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!");
}
项目:openjdk-jdk10    文件:MXBeanFallbackTest.java   
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());
    }
}