Example usage for javax.management JMX newMXBeanProxy

List of usage examples for javax.management JMX newMXBeanProxy

Introduction

In this page you can find the example usage for javax.management JMX newMXBeanProxy.

Prototype

public static <T> T newMXBeanProxy(MBeanServerConnection connection, ObjectName objectName,
        Class<T> interfaceClass) 

Source Link

Document

Make a proxy for an MXBean in a local or remote MBean Server.

Usage

From source file:com.example.Client.java

public static void main(String[] args) throws Exception {
    // Create an RMI connector client and
    // connect it to the RMI connector server
    ///*from   w w  w  . j  ava2 s. c  o m*/
    echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

    // Create listener
    //
    ClientListener listener = new ClientListener();

    // Get an MBeanServerConnection
    //
    echo("\nGet an MBeanServerConnection");
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    waitForEnterPressed();

    // Get domains from MBeanServer
    //
    echo("\nDomains:");
    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
        echo("\tDomain = " + domain);
    }
    waitForEnterPressed();

    // Get MBeanServer's default domain
    //
    echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());

    // Get MBean count
    //
    echo("\nMBean count = " + mbsc.getMBeanCount());

    // Query MBean names
    //
    echo("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
    for (ObjectName name : names) {
        echo("\tObjectName = " + name);
    }
    waitForEnterPressed();

    // ----------------------
    // Manage the Hello MBean
    // ----------------------

    echo("\n>>> Perform operations on Hello MBean <<<");

    // Construct the ObjectName for the Hello MBean
    //
    ObjectName mbeanName = new ObjectName("com.example:type=Hello");

    // Create a dedicated proxy for the MBean instead of
    // going directly through the MBean server connection
    //
    HelloMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, HelloMBean.class, true);

    // Add notification listener on Hello MBean
    //
    echo("\nAdd notification listener...");
    mbsc.addNotificationListener(mbeanName, listener, null, null);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Set CacheSize attribute in Hello MBean
    // Calling "reset" makes the Hello MBean emit a
    // notification that will be received by the registered
    // ClientListener.
    //
    mbeanProxy.setCacheSize(150);

    // Sleep for 2 seconds to have time to receive the notification
    //
    echo("\nWaiting for notification...");
    sleep(2000);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Invoke "sayHello" in Hello MBean
    //
    echo("\nInvoke sayHello() in Hello MBean...");
    mbeanProxy.sayHello();

    // Invoke "add" in Hello MBean
    //
    echo("\nInvoke add(2, 3) in Hello MBean...");
    echo("\nadd(2, 3) = " + mbeanProxy.add(2, 3));

    waitForEnterPressed();

    // ------------------------------
    // Manage the QueueSampler MXBean
    // ------------------------------

    echo("\n>>> Perform operations on QueueSampler MXBean <<<");

    // Construct the ObjectName for the QueueSampler MXBean
    //
    ObjectName mxbeanName = new ObjectName("com.example:type=QueueSampler");

    // Create a dedicated proxy for the MXBean instead of
    // going directly through the MBean server connection
    //
    QueueSamplerMXBean mxbeanProxy = JMX.newMXBeanProxy(mbsc, mxbeanName, QueueSamplerMXBean.class);

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue1 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue1.getDate());
    echo("QueueSample.Head = " + queue1.getHead());
    echo("QueueSample.Size = " + queue1.getSize());

    // Invoke "clearQueue" in QueueSampler MXBean
    //
    echo("\nInvoke clearQueue() in QueueSampler MXBean...");
    mxbeanProxy.clearQueue();

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue2 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue2.getDate());
    echo("QueueSample.Head = " + queue2.getHead());
    echo("QueueSample.Size = " + queue2.getSize());

    waitForEnterPressed();

    // Close MBeanServer connection
    //
    echo("\nClose the connection to the server");
    jmxc.close();
    echo("\nBye! Bye!");
}

From source file:org.eclipse.virgo.web.test.AbstractWebIntegrationTests.java

private void awaitWebAppStart(String name, String version) throws InterruptedException {
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {// www .ja va 2s .  c  o  m
        ObjectName objectName = new ObjectName(String.format(
                "org.eclipse.virgo.kernel:type=ArtifactModel,artifact-type=bundle,name=%s,version=%s,region=%s",
                name, version, USER_REGION_NAME));
        ManageableArtifact artifact = JMX.newMXBeanProxy(mBeanServer, objectName, ManageableArtifact.class);

        long startTime = System.currentTimeMillis();

        while (artifact.getProperties().get("org.eclipse.virgo.web.contextPath") == null) {
            Thread.sleep(100);
            if (System.currentTimeMillis() - startTime > HOT_DEPLOY_TIMEOUT) {
                throw new RuntimeException(name + " " + version + " failed to set its context path within "
                        + (HOT_DEPLOY_TIMEOUT / 1000) + " seconds.");
            }
        }
    } catch (JMException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.marketcetera.client.ClientModuleTestBase.java

@Test
public void jmx() throws Exception {
    //Verify descriptors
    verifyBeanInfo(getMBeanServer().getMBeanInfo(ClientModuleFactory.PROVIDER_URN.toObjectName()));
    verifyBeanInfo(getMBeanServer().getMBeanInfo(ClientModuleFactory.INSTANCE_URN.toObjectName()));
    ClientModuleFactoryMXBean factory = JMX.newMXBeanProxy(getMBeanServer(),
            ClientModuleFactory.PROVIDER_URN.toObjectName(), ClientModuleFactoryMXBean.class);
    assertEquals(getExpectedURL(), factory.getURL());
    assertEquals(getExpectedUsername(), factory.getUsername());
    ClientModuleMXBean instance = JMX.newMXBeanProxy(getMBeanServer(),
            ClientModuleFactory.INSTANCE_URN.toObjectName(), ClientModuleMXBean.class);
    final Date lastTime = ClientManager.getInstance().getLastConnectTime();
    assertEquals(lastTime, instance.getLastConnectTime());
    ClientTest.assertCPEquals(ClientManager.getInstance().getParameters(), instance.getParameters());
    //Sleep so that we definitely get a different connect time.
    Thread.sleep(100);// w  w  w  .ja  v  a 2  s  . c  o m
    instance.reconnect();
    assertEquals(ClientManager.getInstance().getLastConnectTime(), instance.getLastConnectTime());
    assertTrue(instance.getLastConnectTime().compareTo(lastTime) > 0);
}

From source file:org.marketcetera.photon.internal.strategy.StrategyManager.java

/**
 * Sets the parameters for the given strategy.
 * //from   ww w. j a v  a2s .co m
 * Note: currently the UI prevents this from being called when the strategy module is stopped.
 * 
 * @param strategy
 *            strategy to be changed
 * @param parameters
 *            the new parameters
 */
public void setParameters(Strategy strategy, Properties parameters) {
    try {
        ObjectName objectName = strategy.getURN().toObjectName();
        StrategyMXBean proxy = JMX.newMXBeanProxy(mMBeanServer, objectName, StrategyMXBean.class);
        proxy.setParameters(Util.propertiesToString(parameters));
        strategy.setParameters(parameters);
        saveState();
    } catch (Exception e) {
        PhotonPlugin.getMainConsoleLogger().error(e.getLocalizedMessage());
        ExceptUtils.swallow(e);
    }
}

From source file:org.marketcetera.photon.internal.strategy.StrategyManager.java

/**
 * Specify whether the given strategy should route orders to the server.
 * /*from   ww  w.jav a 2 s .  co m*/
 * Note: currently the UI prevents this from being called when the strategy module is stopped
 * 
 * @param strategy
 *            strategy to be changed
 * @param routeToServer
 *            true if the strategy should send orders to the server, false otherwise
 */
public void setRouteToServer(Strategy strategy, boolean routeToServer) {
    try {
        ObjectName objectName = strategy.getURN().toObjectName();
        StrategyMXBean proxy = JMX.newMXBeanProxy(mMBeanServer, objectName, StrategyMXBean.class);
        proxy.setIsRountingOrdersToORS(routeToServer);
        strategy.setRouteToServer(routeToServer);
        saveState();
    } catch (Exception e) {
        PhotonPlugin.getMainConsoleLogger().error(e.getLocalizedMessage());
        ExceptUtils.swallow(e);
    }
}

From source file:org.marketcetera.strategyagent.StrategyAgent.java

/**
 * Initializes the module manager./*from w  w  w  .j  a  v  a  2 s .  c o m*/
 *
 * @throws ModuleException if there were errors initializing the module
 * manager.
 * @throws MalformedObjectNameException if there were errors creating
 * the object name of the module manager bean.
 */
private void init() throws ModuleException, MalformedObjectNameException {
    //Initialize the module manager.
    mManager.init();
    //Add the logger sink listener
    mManager.addSinkListener(new SinkDataListener() {
        public void receivedData(DataFlowID inFlowID, Object inData) {
            final boolean isNullData = inData == null;
            Messages.LOG_SINK_DATA.info(SINK_DATA, inFlowID, isNullData ? 0 : 1,
                    isNullData ? null : inData.getClass().getName(), inData);
        }
    });
    mManagerBean = JMX.newMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
            new ObjectName(ModuleManager.MODULE_MBEAN_NAME), ModuleManagerMXBean.class);
}

From source file:org.nuxeo.ecm.core.management.jtajca.JtajcaManagementFeature.java

protected <T> void bind(Binder binder, MBeanServer mbs, Class<T> type) {
    final Set<ObjectName> names = mbs.queryNames(nameOf(type), null);
    for (ObjectName name : names) {
        T instance = type.cast(JMX.newMXBeanProxy(mbs, name, type));
        binder.bind(type).annotatedWith(Names.named(name.getKeyProperty("name"))).toInstance(instance);
    }/* w w  w  .ja v  a  2  s.  c  o m*/
}

From source file:org.nuxeo.ecm.core.management.jtajca.JtajcaManagementFeature.java

public static <T> T getInstanceNamedWithPrefix(Class<T> type, String prefix) {
    MBeanServer mbs = Framework.getService(ServerLocator.class).lookupServer();
    Set<String> names = new HashSet<>();
    for (ObjectName objectName : mbs.queryNames(nameOf(type), null)) {
        String name = objectName.getKeyProperty("name");
        names.add(name); // for error case
        if (name.startsWith(prefix)) {
            return JMX.newMXBeanProxy(mbs, objectName, type);
        }/*from w  w  w  .j  a v a2  s.  c  o  m*/
    }
    throw new RuntimeException("Found no bean with name prefix: " + prefix + " in available names: " + names);
}

From source file:org.nuxeo.runtime.jtajca.management.CanMonitorTransactions.java

@Before
public void lookupMonitor() throws MalformedObjectNameException {
    MBeanServer srv = ManagementFactory.getPlatformMBeanServer();
    monitor = JMX.newMXBeanProxy(srv, new ObjectName(TransactionMonitor.NAME), TransactionMonitor.class);
}

From source file:org.opendaylight.controller.config.yang.logback.config.LogbackModuleWithInitialConfigurationTest.java

/**
 * Tests that initial configuration was changed. Changed attributes:
 * location, fileName, duplicateInsertTries. Added new FileAppender.
 *//*w w w  .  jav  a2 s .  c  o m*/
@Test
public void test() throws Exception {

    createBeans();

    ConfigTransactionClient transaction = configRegistryClient.createTransaction();

    LogbackModuleMXBean bean = JMX.newMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
            transaction.lookupConfigBean("logback", "singleton"), LogbackModuleMXBean.class);
    assertEquals(1, bean.getConsoleAppenderTO().size());
    assertEquals(1, bean.getRollingFileAppenderTO().size());
    assertEquals(0, bean.getFileAppenderTO().size());
    assertEquals(1, bean.getLoggerTO().size());

    RollingFileAppenderTO rolling = new RollingFileAppenderTO();
    RollingFileAppenderTO old = bean.getRollingFileAppenderTO().get(0);
    rolling.setAppend(old.getAppend());
    rolling.setEncoderPattern(old.getEncoderPattern());
    rolling.setRollingPolicyType(old.getRollingPolicyType());
    rolling.setFileName("target/logFile1.log");
    rolling.setFileNamePattern("target/%i.log");
    rolling.setMaxFileSize(old.getMaxFileSize());
    rolling.setMinIndex(old.getMinIndex());
    rolling.setMaxIndex(old.getMaxIndex());
    rolling.setName("FILE");

    ConsoleAppenderTO console = new ConsoleAppenderTO();
    console.setEncoderPattern("%date %level [%thread] %logger{10} %msg%n");
    console.setName("SYSTEM");
    console.setThresholdFilter("DEBUG");

    FileAppenderTO file = new FileAppenderTO();
    file.setName("FILE_APPENDER");
    file.setAppend(true);
    file.setEncoderPattern("%-4relative [%thread] %-5level %logger{35} - %msg%n");
    file.setFileName("target/testFile.log");

    bean.setConsoleAppenderTO(Lists.newArrayList(console));
    bean.setRollingFileAppenderTO(Lists.newArrayList(rolling));
    bean.setFileAppenderTO(Lists.newArrayList(file));

    LoggerTO logger = new LoggerTO();
    logger.setLevel("INFO");
    logger.setLoggerName("logger");
    logger.setAppenders(Lists.newArrayList("SYSTEM"));

    LoggerTO fileLogger = new LoggerTO();
    fileLogger.setLevel("DEBUG");
    fileLogger.setLoggerName("fileLogger");
    fileLogger.setAppenders(Lists.newArrayList("FILE_APPENDER"));

    List<LoggerTO> loggers = Lists.newArrayList(logger, fileLogger);
    bean.setLoggerTO(loggers);

    transaction.commit();

    LogbackModuleMXBean logback = configRegistryClient.newMXBeanProxy(
            ObjectNameUtil.createReadOnlyModuleON("logback", "singleton"), LogbackModuleMXBean.class);

    List<RollingFileAppenderTO> rollingList = logback.getRollingFileAppenderTO();
    assertEquals(1, rollingList.size());

    RollingFileAppenderTO rollingApp = rollingList.get(0);
    assertEquals(rollingApp.getFileName(), "target/logFile1.log");
    assertEquals(rollingApp.getName(), "FILE");

    List<ConsoleAppenderTO> consoleList = logback.getConsoleAppenderTO();
    assertEquals(1, consoleList.size());

    ConsoleAppenderTO consoleApp = consoleList.get(0);
    assertEquals(consoleApp.getThresholdFilter(), "DEBUG");
    assertEquals(consoleApp.getName(), "SYSTEM");

    List<FileAppenderTO> fileList = logback.getFileAppenderTO();
    assertEquals(1, fileList.size());

    FileAppenderTO fileApp = fileList.get(0);
    assertEquals(fileApp.getFileName(), "target/testFile.log");
    assertEquals(fileApp.getName(), "FILE_APPENDER");

    loggers = logback.getLoggerTO();
    assertEquals(2, loggers.size());
    assertEquals("logger", loggers.get(0).getLoggerName());
    assertEquals("fileLogger", loggers.get(1).getLoggerName());

}