Java Code Examples for java.lang.management.ManagementFactory.getPlatformMBeanServer()

The following are Jave code examples for showing how to use getPlatformMBeanServer() of the java.lang.management.ManagementFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jdk8u-jdk   File: ConnectorStopDeadlockTest.java   View Source Code Vote up 6 votes
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 2
Project: otus_java_2017_06   File: Main.java   View Source Code Vote up 6 votes
public static void main(String... args) throws Exception {
    System.out.println("Starting pid: " + ManagementFactory.getRuntimeMXBean().getName());

    int size = 5 * 1000 * 1000;
    //int size = 50 * 1000 * 1000;//for OOM with -Xms512m
    //int size = 50 * 1000 * 100; //for small dump


    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("ru.otus:type=Benchmark");
    Benchmark mbean = new Benchmark();
    mbs.registerMBean(mbean, name);

    mbean.setSize(size);
    mbean.run();
}
 
Example 3
Project: hadoop   File: TestFSNamesystemMBean.java   View Source Code Vote up 5 votes
@Override
public void run() {
  try {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Metrics that belong to "FSNamesystem", these are metrics that
    // come from hadoop metrics framework for the class FSNamesystem.
    ObjectName mxbeanNamefsn = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystem");

    // Metrics that belong to "FSNamesystemState".
    // These are metrics that FSNamesystem registers directly with MBeanServer.
    ObjectName mxbeanNameFsns = new ObjectName(
        "Hadoop:service=NameNode,name=FSNamesystemState");

    // Metrics that belong to "NameNodeInfo".
    // These are metrics that FSNamesystem registers directly with MBeanServer.
    ObjectName mxbeanNameNni = new ObjectName(
        "Hadoop:service=NameNode,name=NameNodeInfo");

    final Set<ObjectName> mbeans = new HashSet<ObjectName>();
    mbeans.add(mxbeanNamefsn);
    mbeans.add(mxbeanNameFsns);
    mbeans.add(mxbeanNameNni);

    for(ObjectName mbean : mbeans) {
      MBeanInfo attributes = mbs.getMBeanInfo(mbean);
      for (MBeanAttributeInfo attributeInfo : attributes.getAttributes()) {
        mbs.getAttribute(mbean, attributeInfo.getName());
      }
    }

    succeeded = true;
  } catch (Exception e) {
  }
}
 
Example 4
Project: otus_java_2017_06   File: ServerMain.java   View Source Code Vote up 5 votes
private void startEchoServer() throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    ObjectName name = new ObjectName("ru.otus:type=Server");
    NonBlockingEchoSocketMsgServer server = new NonBlockingEchoSocketMsgServer();
    mbs.registerMBean(server, name);

    server.start();
}
 
Example 5
Project: openjdk-jdk10   File: GetVMOption.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    List<HotSpotDiagnosticMXBean> list =
        ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
    HotSpotDiagnosticMXBean mbean = list.get(0);
    checkVMOption(mbean);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    mbean = ManagementFactory.newPlatformMXBeanProxy(mbs,
                HOTSPOT_DIAGNOSTIC_MXBEAN_NAME,
                HotSpotDiagnosticMXBean.class);
    checkVMOption(mbean);
}
 
Example 6
Project: incubator-netbeans   File: JavaCustomIndexer.java   View Source Code Vote up 5 votes
@CheckForNull
private static File dumpHeap(@NonNull final String path) {
    try {
        if (heapDumper == null) {
            final Class<?> clz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");   //NOI18N
            final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            final Object bean = ManagementFactory.newPlatformMXBeanProxy(
                server,
                "com.sun.management:type=HotSpotDiagnostic",    //NOI18N
                clz);
            final Method m = clz.getDeclaredMethod("dumpHeap", String.class, Boolean.TYPE);
            heapDumper = Pair.of(bean,m);
        }
        final File folder = new File(path);
        final File[] children = folder.listFiles();
        if (children != null) {
            final String namePattern = "heapdump_"; //NOI18N
            final Set<String> names = Arrays.stream(children)
                    .map((f) -> f.getName())
                    .filter((n) -> n.startsWith(namePattern))
                    .collect(Collectors.toSet());
            int index = 1;
            while (true) {
                if (!names.contains(namePattern + index)) {
                    break;
                }
                index++;
            }
            final File file = new File(folder, namePattern + index);
            heapDumper.second().invoke(heapDumper.first(), file.getAbsolutePath(), true);
            return file;
        }
    } catch (Exception e) {
        //pass
    }
    return null;
}
 
Example 7
Project: monarch   File: LauncherMemberMXBeanIntegrationTest.java   View Source Code Vote up 5 votes
@Test
public void testQueryForMemberMXBeanWithProcessId() throws Exception {
  final Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");
  props.setProperty("name", getUniqueName());
  new CacheFactory(props).create();

  final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
  final ObjectName pattern = ObjectName.getInstance("GemFire:type=Member,*");
  final QueryExp constraint =
      Query.eq(Query.attr("ProcessId"), Query.value(ProcessUtils.identifyPid()));

  waitForMemberMXBean(mbeanServer, pattern);

  final Set<ObjectName> mbeanNames = mbeanServer.queryNames(pattern, constraint);
  assertFalse(mbeanNames.isEmpty());
  assertEquals(1, mbeanNames.size());

  final ObjectName objectName = mbeanNames.iterator().next();
  final MemberMXBean mbean = MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
      objectName, MemberMXBean.class, false);

  assertNotNull(mbean);
  assertEquals(ProcessUtils.identifyPid(), mbean.getProcessId());
  assertEquals(getUniqueName(), mbean.getName());
  assertEquals(getUniqueName(), mbean.getMember());
}
 
Example 8
Project: hashsdn-controller   File: ShardStatsTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws Exception {

    shardStats = new ShardStats("shard-1", "DataStore", null);
    shardStats.registerMBean();
    mbeanServer = ManagementFactory.getPlatformMBeanServer();
    String objectName = AbstractMXBean.BASE_JMX_PREFIX + "type=" + shardStats.getMBeanType() + ",Category="
            + shardStats.getMBeanCategory() + ",name=" + shardStats.getMBeanName();
    testMBeanName = new ObjectName(objectName);
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: JmxPasswordTest.java   View Source Code Vote up 5 votes
@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 10
Project: Lucid2.0   File: ShutdownServer.java   View Source Code Vote up 5 votes
public static void registerMBean() {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        instance = new ShutdownServer();
        mBeanServer.registerMBean(instance, new ObjectName("server:type=ShutdownServer"));
    } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
        System.out.println("Error registering Shutdown MBean");
    }
}
 
Example 11
Project: openjdk-jdk10   File: MBeanServerMXBeanUnsupportedTest.java   View Source Code Vote up 5 votes
public static void main(String args[]) throws Exception {
    System.setProperty("javax.management.builder.initial",
            MBeanServerBuilderImpl.class.getName());
    try {
        ManagementFactory.getPlatformMBeanServer();
    } catch (RuntimeException e) {
        System.out.println(">>> Unhappy Bye, Bye!");
        throw e;
    }
    System.out.println(">>> Happy Bye, Bye!");
}
 
Example 12
Project: jdk8u-jdk   File: ScanDirConfigTest.java   View Source Code Vote up 5 votes
/**
 * Test of save method, of class com.sun.jmx.examples.scandir.ScanDirConfig.
 */
public void testSave() throws Exception {
    System.out.println("save");

    final File file = File.createTempFile("testconf",".xml");
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ScanManagerMXBean manager = ScanManager.register(mbs);

    try {
        final ScanDirConfigMXBean instance =
                manager.createOtherConfigurationMBean("testSave",file.getAbsolutePath());
        assertTrue(mbs.isRegistered(
                ScanManager.makeScanDirConfigName("testSave")));
        final ScanManagerConfig bean =
            new  ScanManagerConfig("testSave");
        final DirectoryScannerConfig dir =
            new DirectoryScannerConfig("tmp");
        dir.setRootDirectory(file.getParent());
        bean.putScan(dir);
        instance.setConfiguration(bean);
        instance.save();
        final ScanManagerConfig loaded =
            new XmlConfigUtils(file.getAbsolutePath()).readFromFile();
        assertEquals(instance.getConfiguration(),loaded);
        assertEquals(bean,loaded);

        instance.getConfiguration().removeScan("tmp");
        instance.save();
        assertNotSame(loaded,instance.getConfiguration());
        final ScanManagerConfig loaded2 =
            new XmlConfigUtils(file.getAbsolutePath()).readFromFile();
        assertEquals(instance.getConfiguration(),loaded2);
    } finally {
        manager.close();
        mbs.unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
    }
    final ObjectName all =
            new ObjectName(ScanManager.SCAN_MANAGER_NAME.getDomain()+":*");
    assertEquals(0,mbs.queryNames(all,null).size());
}
 
Example 13
Project: BibliotecaPS   File: ReplicationGroupManager.java   View Source Code Vote up 5 votes
public synchronized void registerJmx() throws SQLException {
    if (this.isJmxRegistered) {
        return;
    }
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName name = new ObjectName("com.mysql.jdbc.jmx:type=ReplicationGroupManager");
        mbs.registerMBean(this, name);
        this.isJmxRegistered = true;
    } catch (Exception e) {
        throw SQLError.createSQLException("Unable to register replication host management bean with JMX", null, e, null);
    }

}
 
Example 14
Project: hadoop   File: TestDataNodeMetrics.java   View Source Code Vote up 4 votes
@Test(timeout=60000)
public void testTimeoutMetric() throws Exception {
  final Configuration conf = new HdfsConfiguration();
  final Path path = new Path("/test");

  final MiniDFSCluster cluster =
      new MiniDFSCluster.Builder(conf).numDataNodes(2).build();

  final List<FSDataOutputStream> streams = Lists.newArrayList();
  try {
    final FSDataOutputStream out =
        cluster.getFileSystem().create(path, (short) 2);
    final DataNodeFaultInjector injector = Mockito.mock
        (DataNodeFaultInjector.class);
    Mockito.doThrow(new IOException("mock IOException")).
        when(injector).
        writeBlockAfterFlush();
    DataNodeFaultInjector.instance = injector;
    streams.add(out);
    out.writeBytes("old gs data\n");
    out.hflush();

    /* Test the metric. */
    final MetricsRecordBuilder dnMetrics =
        getMetrics(cluster.getDataNodes().get(0).getMetrics().name());
    assertCounter("DatanodeNetworkErrors", 1L, dnMetrics);

    /* Test JMX datanode network counts. */
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName mxbeanName =
        new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
    final Object dnc =
        mbs.getAttribute(mxbeanName, "DatanodeNetworkCounts");
    final String allDnc = dnc.toString();
    assertTrue("expected to see loopback address",
        allDnc.indexOf("127.0.0.1") >= 0);
    assertTrue("expected to see networkErrors",
        allDnc.indexOf("networkErrors") >= 0);
  } finally {
    IOUtils.cleanup(LOG, streams.toArray(new Closeable[0]));
    if (cluster != null) {
      cluster.shutdown();
    }
    DataNodeFaultInjector.instance = new DataNodeFaultInjector();
  }
}
 
Example 15
Project: tomcat_exporter   File: TomcatJdbcPoolExports.java   View Source Code Vote up 4 votes
public List<MetricFamilySamples> collect() {
    List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
    try {
        final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName filterName = new ObjectName("tomcat.jdbc:class=org.apache.tomcat.jdbc.pool.DataSource,type=ConnectionPool,*");
        Set<ObjectInstance> mBeans = server.queryMBeans(filterName, null);

        if (mBeans.size() > 0) {
            List<String> labelList = Collections.singletonList("pool");

            GaugeMetricFamily maxActiveConnectionsGauge = new GaugeMetricFamily(
                    "tomcat_jdbc_connections_max",
                    "Maximum number of active connections that can be allocated from this pool at the same time",
                    labelList);

            GaugeMetricFamily activeConnectionsGauge = new GaugeMetricFamily(
                    "tomcat_jdbc_connections_active_total",
                    "Number of active connections allocated from this pool",
                    labelList);

            GaugeMetricFamily idleConnectionsGauge = new GaugeMetricFamily(
                    "tomcat_jdbc_connections_idle_total",
                    "Number of idle connections in this pool",
                    labelList);

            GaugeMetricFamily totalConnectionsGauge = new GaugeMetricFamily(
                    "tomcat_jdbc_connections_total",
                    "Total number of connections in this pool",
                    labelList);

            GaugeMetricFamily waitingThreadsCountGauge = new GaugeMetricFamily(
                    "tomcat_jdbc_waitingthreads_total",
                    "Number of threads waiting for connections from this pool",
                    labelList);

            for (final ObjectInstance mBean : mBeans) {
                List<String> labelValueList = Collections.singletonList(mBean.getObjectName().getKeyProperty("name").replaceAll("[\"\\\\]", ""));

                maxActiveConnectionsGauge.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "MaxActive")).doubleValue());

                activeConnectionsGauge.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "Active")).doubleValue());

                idleConnectionsGauge.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "Idle")).doubleValue());

                totalConnectionsGauge.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "Size")).doubleValue());

                waitingThreadsCountGauge.addMetric(
                        labelValueList,
                        ((Integer) server.getAttribute(mBean.getObjectName(), "WaitCount")).doubleValue());
            }

            mfs.add(maxActiveConnectionsGauge);
            mfs.add(activeConnectionsGauge);
            mfs.add(idleConnectionsGauge);
            mfs.add(totalConnectionsGauge);
            mfs.add(waitingThreadsCountGauge);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return mfs;
}
 
Example 16
Project: flume-release-1.7.0   File: TestMonitoredCounterGroup.java   View Source Code Vote up 4 votes
@Before
public void setUp() {
  mbServer = ManagementFactory.getPlatformMBeanServer();
  random = new Random(System.nanoTime());
}
 
Example 17
Project: openjdk-jdk10   File: Basic.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    Random rand = new Random();

    // allocate a few direct buffers
    int bufferCount = 5 + rand.nextInt(20);
    buffers = new ArrayList<ByteBuffer>(bufferCount);
    long totalCapacity = 0L;
    for (int i=0; i<bufferCount; i++) {
        int cap = 1024 + rand.nextInt(4096);
        buffers.add( ByteBuffer.allocateDirect(cap) );
        totalCapacity += cap;
    }

    // create a mapped buffer
    Path tmpfile = Files.createTempFile("blah", null);
    tmpfile.toFile().deleteOnExit();
    try (FileChannel fc = FileChannel.open(tmpfile, READ, WRITE)) {
        mbb = fc.map(FileChannel.MapMode.READ_WRITE, 10, 100);
        bufferCount++;
        totalCapacity += mbb.capacity();
    }

    // use platform MXBeans directly
    List<BufferPoolMXBean> pools =
        ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
    check(pools, bufferCount, totalCapacity);

    // use MBeanServer
    MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> mbeans = server.queryNames(
        new ObjectName("java.nio:type=BufferPool,*"), null);
    pools = new ArrayList<BufferPoolMXBean>();
    for (ObjectName name: mbeans) {
        BufferPoolMXBean pool = ManagementFactory
            .newPlatformMXBeanProxy(server, name.toString(), BufferPoolMXBean.class);
        pools.add(pool);
    }
    check(pools, bufferCount, totalCapacity);

    // attempt to unmap mapped buffer
    WeakReference<MappedByteBuffer> ref = new WeakReference<>(mbb);
    mbb = null;
    do {
        System.gc();
        Thread.sleep(250);
    } while (ref.get() != null);
}
 
Example 18
Project: openjdk-jdk10   File: HotSpotGraalMBeanTest.java   View Source Code Vote up 4 votes
@Test
public void dumpOperation() throws Exception {
    Field field = null;
    try {
        field = stopMBeanServer();
    } catch (Exception ex) {
        if (ex.getClass().getName().equals("java.lang.reflect.InaccessibleObjectException")) {
            // skip on JDK9
            return;
        }
    }
    assertNull("The platformMBeanServer isn't initialized now", field.get(null));

    ObjectName name;

    assertNotNull("Server is started", ManagementFactory.getPlatformMBeanServer());

    HotSpotGraalMBean realBean = HotSpotGraalMBean.create(null);

    assertNotNull("Bean is registered", name = realBean.ensureRegistered(false));
    final MBeanServer server = ManagementFactory.getPlatformMBeanServer();

    ObjectInstance bean = server.getObjectInstance(name);
    assertNotNull("Bean is registered", bean);

    MBeanInfo info = server.getMBeanInfo(name);
    assertNotNull("Info is found", info);

    final MBeanOperationInfo[] arr = info.getOperations();
    assertEquals("Currently three overloads", 3, arr.length);
    MBeanOperationInfo dumpOp = null;
    for (int i = 0; i < arr.length; i++) {
        assertEquals("dumpMethod", arr[i].getName());
        if (arr[i].getSignature().length == 3) {
            dumpOp = arr[i];
        }
    }
    assertNotNull("three args variant found", dumpOp);

    server.invoke(name, "dumpMethod", new Object[]{
                    "java.util.Arrays", "asList", ":3"
    }, null);

    MBeanAttributeInfo dump = (MBeanAttributeInfo) findAttributeInfo("Dump", info);
    Attribute dumpTo1 = new Attribute(dump.getName(), "");
    server.setAttribute(name, dumpTo1);
    Object after = server.getAttribute(name, dump.getName());
    assertEquals("", after);

    OptionValues empty = new OptionValues(EconomicMap.create());
    OptionValues unsetDump = realBean.optionsFor(empty, null);
    final MetaAccessProvider metaAccess = jdk.vm.ci.runtime.JVMCI.getRuntime().getHostJVMCIBackend().getMetaAccess();
    ResolvedJavaMethod method = metaAccess.lookupJavaMethod(Arrays.class.getMethod("asList", Object[].class));
    final OptionValues forMethod = realBean.optionsFor(unsetDump, method);
    assertNotSame(unsetDump, forMethod);
    Object nothing = unsetDump.getMap().get(DebugOptions.Dump);
    assertEquals("Empty string", "", nothing);

    Object specialValue = forMethod.getMap().get(DebugOptions.Dump);
    assertEquals(":3", specialValue);

    OptionValues normalMethod = realBean.optionsFor(unsetDump, null);
    Object noSpecialValue = normalMethod.getMap().get(DebugOptions.Dump);
    assertEquals("Empty string", "", noSpecialValue);
}
 
Example 19
Project: hashsdn-controller   File: DynamicReadableWrapperTest.java   View Source Code Vote up 4 votes
@Override
protected AbstractDynamicWrapper getDynamicWrapper(final Module module,
        final ModuleIdentifier moduleIdentifier) {
    return new DynamicReadableWrapper(module, null, moduleIdentifier,
            internalServer, ManagementFactory.getPlatformMBeanServer());
}
 
Example 20
Project: ProyectoPacientes   File: ConnectionRegressionTest.java   View Source Code Vote up 3 votes
private ReplicationGroupManagerMBean getReplicationMBean() throws Exception {
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    ObjectName mbeanName = new ObjectName("com.mysql.jdbc.jmx:type=ReplicationGroupManager");
    return (ReplicationGroupManagerMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, mbeanName, ReplicationGroupManagerMBean.class, false);

}