javax.management.MBeanServer Java Examples

The following examples show how to use javax.management.MBeanServer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JMXProxyFallbackTest.java    From jdk8u-jdk with GNU General Public License v2.0 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 #2
Source File: SnmpRequestHandler.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Full constructor
 */
public SnmpRequestHandler(SnmpAdaptorServer server, int id,
                          DatagramSocket s, DatagramPacket p,
                          SnmpMibTree tree, Vector<SnmpMibAgent> m,
                          InetAddressAcl a,
                          SnmpPduFactory factory,
                          SnmpUserDataFactory dataFactory,
                          MBeanServer f, ObjectName n)
{
    super(server, id, f, n);

    // Need a reference on SnmpAdaptorServer for getNext & getBulk,
    // in case of oid equality (mib overlapping).
    //
    adaptor = server;
    socket = s;
    packet = p;
    root= tree;
    mibs = new Vector<>(m);
    subs= new Hashtable<>(mibs.size());
    ipacl = a;
    pduFactory = factory ;
    userDataFactory = dataFactory ;
    //thread.start();
}
 
Example #3
Source File: AgentImpl.java    From gemfirexd-oss with Apache License 2.0 6 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) {
    this.logWriter.info(LocalizedStrings.AgentImpl_0__IS_ALREADY_REGISTERED,
                        registryName);
  }
  mbs.invoke(registryName, "start", null, null);
}
 
Example #4
Source File: MLetCommand.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (System.getSecurityManager() == null)
        throw new IllegalStateException("No security manager installed!");

    System.out.println("java.security.policy=" +
                       System.getProperty("java.security.policy"));

    // Instantiate the MBean server
    //
    System.out.println("Create the MBean server");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    // Register the MLetMBean
    //
    System.out.println("Create MLet MBean");
    ObjectName mlet = new ObjectName("MLetTest:name=MLetMBean");
    mbs.createMBean("javax.management.loading.MLet", mlet);
    // Test OK!
    //
    System.out.println("Bye! Bye!");
}
 
Example #5
Source File: GaugeCollector.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
protected void runInternal() throws Exception {
    final List<GaugeValue> gaugeValues = Lists.newArrayList();
    if (priorRawCounterValues == null) {
        // wait to now to initialize priorGaugeValues inside of the dedicated thread
        priorRawCounterValues = Maps.newHashMap();
    }
    List<MBeanServer> mbeanServers = lazyPlatformMBeanServer.findAllMBeanServers();
    for (GaugeConfig gaugeConfig : configService.getGaugeConfigs()) {
        gaugeValues.addAll(collectGaugeValues(gaugeConfig, mbeanServers));
    }
    if (!pending.offer(gaugeValues)) {
        backPressureLogger.warn("not storing a gauge collection because of an excessive backlog"
                + " of {} gauge collections already waiting to be stored", PENDING_LIMIT);
    }
}
 
Example #6
Source File: ExceptionDiagnosisTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void testCaseProb() throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new CaseProbImpl(), name);
    CaseProbMXBean proxy = JMX.newMXBeanProxy(mbs, name, CaseProbMXBean.class);
    try {
        CaseProb prob = proxy.getCaseProb();
        fail("No exception from proxy method getCaseProb");
    } catch (IllegalArgumentException e) {
        String messageChain = messageChain(e);
        if (messageChain.contains("URLPath")) {
            System.out.println("Message chain contains URLPath as required: "
                    + messageChain);
        } else {
            fail("Exception chain for CaseProb does not mention property" +
                    " URLPath differing only in case");
            System.out.println("Full stack trace:");
            e.printStackTrace(System.out);
        }
    }
}
 
Example #7
Source File: ImmutableNotificationInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 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 #8
Source File: ImmutableNotificationInfoTest.java    From jdk8u-jdk with GNU General Public License v2.0 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 #9
Source File: RandomMXBeanTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static <T> void test(MBeanServer mbs, Class<T> c) throws Exception {
    System.out.println("Testing " + c.getName());
    T merlin = c.cast(
        Proxy.newProxyInstance(c.getClassLoader(),
            new Class<?>[] {c},
            new DullInvocationHandler()));
    ObjectName merlinName = new ObjectName("a:type=" + c.getName());
    mbs.registerMBean(merlin, merlinName);
    System.out.println(mbs.getMBeanInfo(merlinName));
    T merlinProxy = JMX.newMXBeanProxy(mbs, merlinName, c);
    Method[] merlinMethods = c.getMethods();
    for (Method m : merlinMethods) {
        Class<?>[] types = m.getParameterTypes();
        Object[] params = new Object[types.length];
        for (int i = 0; i < types.length; i++)
            params[i] = DullInvocationHandler.zeroFor(types[i]);
        System.out.println("Invoking " + m.getName());
        m.invoke(merlinProxy, (Object[]) params);
    }
}
 
Example #10
Source File: TestBasicDataSource.java    From commons-dbcp with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure setting jmxName to null suppresses JMX registration of connection and statement pools.
 * JIRA: DBCP-434
 */
@Test
public void testJmxDisabled() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    // Unregister leftovers from other tests (TODO: worry about concurrent test execution)
    final ObjectName commons = new ObjectName("org.apache.commons.*:*");
    final Set<ObjectName> results = mbs.queryNames(commons, null);
    for (final ObjectName result : results) {
        mbs.unregisterMBean(result);
    }
    ds.setJmxName(null);  // Should disable JMX for both connection and statement pools
    ds.setPoolPreparedStatements(true);
    ds.getConnection();  // Trigger initialization
    // Nothing should be registered
    assertEquals(0, mbs.queryNames(commons, null).size());
}
 
Example #11
Source File: ComparatorExceptionTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName name = new ObjectName("a:b=c");
    mbs.registerMBean(new TestImpl(), name);

    for (String attr : new String[] {"SortedSet", "SortedMap"}) {
        try {
            Object value = mbs.getAttribute(name, attr);
            fail("get " + attr + " did not throw exception");
        } catch (Exception e) {
            Throwable t = e;
            while (!(t instanceof IllegalArgumentException)) {
                if (t == null)
                    break;
                t = t.getCause();
            }
            if (t != null)
                System.out.println("Correct exception for " + attr);
            else {
                fail("get " + attr + " got wrong exception");
                e.printStackTrace(System.out);
            }
        }
    }

    if (failure != null)
        throw new Exception(failure);
}
 
Example #12
Source File: LazyInitMBeanTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void invokeOnLazyInitBean() throws Exception {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/lazyInit.xml");
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean"));
	assertFalse(ctx.getBeanFactory().containsSingleton("testBean2"));
	try {
		MBeanServer server = (MBeanServer) ctx.getBean("server");
		ObjectName oname = ObjectNameManager.getInstance("bean:name=testBean2");
		String name = (String) server.getAttribute(oname, "Name");
		assertEquals("Invalid name returned", "foo", name);
	}
	finally {
		ctx.close();
	}
}
 
Example #13
Source File: ImplVersionCommand.java    From dragonwell8_jdk with GNU General Public License v2.0 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 #14
Source File: JmxMetricsReporter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private JmxListener(MBeanServer mBeanServer, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit,
                    ObjectNameFactory objectNameFactory, String tag) {
  this.mBeanServer = mBeanServer;
  this.name = name;
  this.filter = filter;
  this.rateUnit = rateUnit;
  this.durationUnit = durationUnit;
  this.registered = new ConcurrentHashMap<>();
  this.objectNameFactory = objectNameFactory;
  this.tag = tag;
  this.exp = Query.eq(Query.attr(INSTANCE_TAG), Query.value(tag));
}
 
Example #15
Source File: EjbdJmxTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception {
    System.setProperty("openejb.jmx.active", "true");
    final MBeanServer server = LocalMBeanServer.get();

    OpenEJB.init(new Properties());

    final Properties p = new Properties();
    p.put("server", "org.apache.openejb.server.ejbd.EjbServer");
    p.put("bind", "127.0.0.1");
    p.put("port", "0");
    p.put("disabled", "false");
    p.put("threads", "10");
    p.put("backlog", "200");
    p.put("discovery", "ejb:ejbd://{bind}:{port}");
    final ServerService service = ServiceManager.manage("ejbd", p, new EjbServer());
    service.init(p);
    service.start();

    ServiceManager.register("ejbd", service, server);

    ObjectName invocationsName = new ObjectName("openejb:type=ServerService,name=ejbd");

    MBeanInfo beanInfo = server.getMBeanInfo(invocationsName);

    for (MBeanAttributeInfo info : beanInfo.getAttributes()) {
        System.out.println(info);
    }

    service.stop();
    OpenEJB.destroy();
}
 
Example #16
Source File: FlightCommand.java    From LagMonitor with MIT License 5 votes vote down vote up
private boolean areFlightMethodsAvailable() {
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = ObjectName.getInstance(DIAGNOSTIC_BEAN);
        MBeanInfo beanInfo = beanServer.getMBeanInfo(objectName);
        return Arrays.stream(beanInfo.getOperations())
                .map(MBeanFeatureInfo::getName)
                .anyMatch(op -> op.contains("jfr"));
    } catch (JMException instanceNotFoundEx) {
        return false;
    }
}
 
Example #17
Source File: SetAllVMOptions.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    List<HotSpotDiagnosticMXBean> list =
        ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
    HotSpotDiagnosticMXBean mbean = list.get(0);
    setAllVMOptions(mbean);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    mbean = ManagementFactory.newPlatformMXBeanProxy(mbs,
                HOTSPOT_DIAGNOSTIC_MXBEAN_NAME,
                HotSpotDiagnosticMXBean.class);
    setAllVMOptions(mbean);
}
 
Example #18
Source File: MBeanServerLocator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the first MBeanServer registered under the agentID
 * 
 * @param agentID the id of the MBeanServer to look for
 * @return the first MBeanServer with an agentID
 */
public static MBeanServer locate(final String agentID)
{
   MBeanServer server = (MBeanServer)
      MBeanServerFactory.findMBeanServer(agentID).iterator().next();

   return server;
}
 
Example #19
Source File: JmxPasswordTest.java    From tomcatsrc with Apache License 2.0 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 #20
Source File: DcmdMBeanInvocationTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.out.println("--->JRCMD MBean Test: invocation on \"help -all\" ...");

    ObjectName name = new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME);
    String[] helpArgs = {"-all"};
    Object[] dcmdArgs = {helpArgs};
    String[] signature = {String[].class.getName()};

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
    JMXConnectorServer cs = null;
    JMXConnector cc = null;
    try {
        cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
        cs.start();
        JMXServiceURL addr = cs.getAddress();
        cc = JMXConnectorFactory.connect(addr);
        MBeanServerConnection mbsc = cc.getMBeanServerConnection();

        String result = (String) mbsc.invoke(name, "help", dcmdArgs, signature);
        System.out.println(result);
    } finally {
        try {
            cc.close();
            cs.stop();
        } catch (Exception e) {
        }
    }

    System.out.println("Test passed");
}
 
Example #21
Source File: ActiveMQServerImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void setMBeanServer(MBeanServer mbeanServer) {
   if (state == SERVER_STATE.STARTING || state == SERVER_STATE.STARTED) {
      throw ActiveMQMessageBundle.BUNDLE.cannotSetMBeanserver();
   }
   this.mbeanServer = mbeanServer;
}
 
Example #22
Source File: EndpointSnitchInfo.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public static void create()
{
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    try
    {
        mbs.registerMBean(new EndpointSnitchInfo(), new ObjectName("org.apache.cassandra.db:type=EndpointSnitchInfo"));
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #23
Source File: PerformanceTestUtils.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Not very fine-grained so not very useful; use {@link #getProcessCpuTime(Duration)} */ 
public static double getProcessCpuAverage() {
    try {
        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
        ObjectName osMBeanName = ObjectName.getInstance(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
        return (Double) mbeanServer.getAttribute(osMBeanName, "ProcessCpuLoad");
    } catch (Exception e) {
        if (!hasLoggedProcessCpuLoadUnavailable) {
            hasLoggedProcessCpuLoadUnavailable = true;
            LOG.warn("ProcessCpuLoad not available in local JVM MXBean "+ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME+" (only available in sun JVM?)");
        }
        return -1;
    }
}
 
Example #24
Source File: DerivedGaugeMonitorTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void check(String attr, MBeanServer server, ObjectName mon,
        ObjectName mbean, long start) throws Exception {
    final Object obj = server.getAttribute(mon, "DerivedGauge");
    final long now = System.currentTimeMillis();
    final long gran = (Long)server.getAttribute(mon, "GranularityPeriod");
    if (now > start +2*gran) {
        throw new Exception(attr+": Can't verify test case: " +
                "granularity period expired!");
    }
    check(attr,server,mon,mbean,obj);
}
 
Example #25
Source File: HotspotInternal.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public ObjectName preRegister(MBeanServer server,
                              ObjectName name) throws java.lang.Exception {
    // register all internal MBeans when this MBean is instantiated
    // and to be registered in a MBeanServer.
    ManagementFactoryHelper.registerInternalMBeans(server);
    this.server = server;
    return objName;
}
 
Example #26
Source File: MXBeanTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void testMXBean(MBeanServer mbs, ObjectName on)
        throws Exception {
    MBeanInfo mbi = mbs.getMBeanInfo(on);
    MBeanAttributeInfo[] attrs = mbi.getAttributes();
    int nattrs = attrs.length;
    if (mbi.getAttributes().length != 1)
        failure("wrong number of attributes: " + attrs);
    else {
        MBeanAttributeInfo mbai = attrs[0];
        if (mbai.getName().equals("Ints")
            && mbai.isReadable() && !mbai.isWritable()
            && mbai.getDescriptor().getFieldValue("openType")
                .equals(new ArrayType<int[]>(SimpleType.INTEGER, true))
            && attrs[0].getType().equals("[I"))
            success("MBeanAttributeInfo");
        else
            failure("MBeanAttributeInfo: " + mbai);
    }

    int[] ints = (int[]) mbs.getAttribute(on, "Ints");
    if (equal(ints, new int[] {1, 2, 3}, null))
        success("getAttribute");
    else
        failure("getAttribute: " + Arrays.toString(ints));

    ExplicitMXBean proxy =
        JMX.newMXBeanProxy(mbs, on, ExplicitMXBean.class);
    int[] pints = proxy.getInts();
    if (equal(pints, new int[] {1, 2, 3}, null))
        success("getAttribute through proxy");
    else
        failure("getAttribute through proxy: " + Arrays.toString(pints));
}
 
Example #27
Source File: MappingProvidersDecodeAction.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** Decrypt the secret using the cipherKey.
 *
 * @param secret - the encrypted secret to decrypt.
 * @return the decrypted secret
 * @throws Exception
 */
private byte[] decode64(String secret)
   throws Exception
{
   SecurityManager sm = System.getSecurityManager();
   if( sm != null )
      sm.checkPermission(decodePermission);

   MBeanServer server = MBeanServerLocator.locateJBoss();
   return (byte[]) server.invoke(serviceName, "decode64", new Object[] {secret}, 
         new String[] {String.class.getName()});
}
 
Example #28
Source File: MBeans.java    From hadoop with Apache License 2.0 5 votes vote down vote up
static public void unregister(ObjectName mbeanName) {
  LOG.debug("Unregistering "+ mbeanName);
  final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
  if (mbeanName == null) {
    LOG.debug("Stacktrace: ", new Throwable());
    return;
  }
  try {
    mbs.unregisterMBean(mbeanName);
  } catch (Exception e) {
    LOG.warn("Error unregistering "+ mbeanName, e);
  }
  DefaultMetricsSystem.removeMBeanName(mbeanName);
}
 
Example #29
Source File: Server.java    From jdk8u-jdk with GNU General Public License v2.0 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 #30
Source File: MemoryLogger.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new memory logger that logs in the given interval and lives until the
 * given termination future completes.
 *
 * @param logger The logger to use for outputting the memory statistics.
 * @param interval The interval in which the thread logs.
 * @param monitored termination future for the system to whose life the thread is bound. The thread terminates
 *                  once the system terminates.
 */
public MemoryLogger(Logger logger, long interval, CompletableFuture<Void> monitored) {
	super("Memory Logger");
	setDaemon(true);
	setPriority(Thread.MIN_PRIORITY);
	
	this.logger = logger;
	this.interval = interval;
	this.monitored = monitored;

	this.memoryBean = ManagementFactory.getMemoryMXBean();
	this.poolBeans = ManagementFactory.getMemoryPoolMXBeans();
	this.gcBeans = ManagementFactory.getGarbageCollectorMXBeans();

	// The direct buffer pool bean needs to be accessed via the bean server
	MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
	BufferPoolMXBean directBufferBean = null;
	try {
		directBufferBean = ManagementFactory.newPlatformMXBeanProxy(
				beanServer,
				"java.nio:type=BufferPool,name=direct",
				BufferPoolMXBean.class);
	}
	catch (Exception e) {
		logger.warn("Failed to initialize direct buffer pool bean.", e);
	}
	finally {
		this.directBufferBean = directBufferBean;
	}
}