Example usage for javax.management MBeanServerConnection addNotificationListener

List of usage examples for javax.management MBeanServerConnection addNotificationListener

Introduction

In this page you can find the example usage for javax.management MBeanServerConnection addNotificationListener.

Prototype

public void addNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter,
        Object handback) throws InstanceNotFoundException, IOException;

Source Link

Document

Adds a listener to a registered MBean.

A notification emitted by an MBean will be forwarded by the MBeanServer to the listener.

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 ww .  j  a  v  a2s.  com*/
    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:com.continuent.tungsten.common.jmx.JmxManager.java

/**
 * Attach NotificationListener that can be used to listen notifications
 * emitted by MBean server./*from  www. j  av  a  2 s  . co  m*/
 * 
 * @param jmxConnector The MBean server connector.
 * @param mbeanClass The class for which an MBean exists.
 * @param notificationListener User provided NotificationListener instance.
 * @throws InstanceNotFoundException
 * @throws Exception
 */
static public void addNotificationListener(JMXConnector jmxConnector, Class<?> mbeanClass,
        NotificationListener notificationListener) throws InstanceNotFoundException, Exception {
    MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection();
    ObjectName objectName = generateMBeanObjectName(mbeanClass);
    mbsc.addNotificationListener(objectName, notificationListener, null, null);
}

From source file:com.continuent.tungsten.common.jmx.JmxManager.java

/**
 * Attach NotificationListener that can be used to listen notifications
 * emitted by MBean server.// w ww  . j  av  a  2  s. com
 * 
 * @param jmxConnector The MBean server connector.
 * @param mbeanInterface The MBean interface this instance implements.
 * @param mbeanName A custom name for the MBean.
 * @param notificationListener User provided NotificationListener instance.
 * @throws InstanceNotFoundException
 * @throws Exception
 */
static public void addNotificationListener(JMXConnector jmxConnector, Class<?> mbeanInterface, String mbeanName,
        NotificationListener notificationListener, boolean ignored)
        throws InstanceNotFoundException, Exception {
    MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection();
    ObjectName objectName = generateMBeanObjectName(mbeanInterface.getName(), mbeanName);
    mbsc.addNotificationListener(objectName, notificationListener, null, null);
}

From source file:com.vmware.springsource.hyperic.plugin.gemfire.AlertsPlugin.java

@Override
public void configure(ConfigResponse config) throws PluginException {
    log.debug("[configure] config=" + config);
    super.configure(config);
    MBeanServerConnection mServer;

    try {/* w ww. j a va  2  s .  com*/
        mServer = MxUtil.getMBeanServer(config.toProperties());
        ObjectName obj = new ObjectName("GemFire:type=MemberInfoWithStatsMBean");
        mServer.addNotificationListener(obj, this, null, null);
        log.debug("[configure] listener OK");
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    }
}

From source file:io.fabric8.spi.process.AbstractProcessHandler.java

@Override
public final Future<ManagedProcess> start() {
    State state = managedProcess.getState();
    assertNotDestroyed(state);//from w  w w .  ja  v a  2s. c o  m

    // Setup a call back notification to get the JMX connection of the started process
    final CountDownLatch latch = new CountDownLatch(1);
    String jmxAgentServiceURL = managedProcess
            .getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_SERVER_URL);
    String jmxAgentUsername = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_USERNAME);
    String jmxAgentPassword = managedProcess.getAttribute(ContainerAttributes.ATTRIBUTE_KEY_AGENT_JMX_PASSWORD);
    JMXConnector connector = ManagementUtils.getJMXConnector(jmxAgentServiceURL, jmxAgentUsername,
            jmxAgentPassword, 200, TimeUnit.MILLISECONDS);
    try {
        final MBeanServerConnection server = connector.getMBeanServerConnection();
        server.addNotificationListener(Agent.OBJECT_NAME, new NotificationListener() {
            @Override
            public void handleNotification(Notification notification, Object handback) {
                String eventType = notification.getType();
                if (NOTIFICATION_TYPE_AGENT_REGISTRATION.equals(eventType)) {
                    AgentRegistration agentReg = (AgentRegistration) notification.getSource();
                    String agentName = agentReg.getIdentity().getName();
                    String procName = (String) handback;
                    if (agentName.equals(procName)) {
                        try {
                            server.removeNotificationListener(Agent.OBJECT_NAME, this);
                        } catch (Exception ex) {
                            // ignore
                        }
                        latch.countDown();
                    }
                }
            }
        }, null, managedProcess.getIdentity().getName());
    } catch (RuntimeException rte) {
        throw rte;
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    } finally {
        IOUtils.safeClose(connector);
    }

    try {
        if (state == State.CREATED || state == State.STOPPED) {
            doStart(managedProcess);
            IllegalStateAssertion.assertNotNull(process, "No process created");
            managedProcess.setState(State.STARTED);
        }
    } catch (Exception ex) {
        throw new LifecycleException("Cannot start container", ex);
    }

    return new ProcessFuture(managedProcess); //, latch);
}

From source file:com.spotify.reaper.cassandra.JmxProxy.java

/**
 * Connect to JMX interface on the given host and port.
 *
 * @param handler  Implementation of {@link RepairStatusHandler} to process incoming
 *                 notifications//w w  w .  j  av a2s.c o  m
 *                 of repair events.
 * @param host     hostname or ip address of Cassandra node
 * @param port     port number to use for JMX connection
 * @param username username to use for JMX authentication
 * @param password password to use for JMX authentication
 */
static JmxProxy connect(Optional<RepairStatusHandler> handler, String host, int port, String username,
        String password) throws ReaperException {
    ObjectName ssMbeanName;
    ObjectName cmMbeanName;
    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(String.format(JMX_URL, host, port));
        ssMbeanName = new ObjectName(SS_OBJECT_NAME);
        cmMbeanName = new ObjectName(CompactionManager.MBEAN_OBJECT_NAME);
    } catch (MalformedURLException | MalformedObjectNameException e) {
        LOG.error(String.format("Failed to prepare the JMX connection to %s:%s", host, port));
        throw new ReaperException("Failure during preparations for JMX connection", e);
    }
    try {
        Map<String, Object> env = new HashMap<String, Object>();
        if (username != null && password != null) {
            String[] creds = { username, password };
            env.put(JMXConnector.CREDENTIALS, creds);
        }
        JMXConnector jmxConn = JMXConnectorFactory.connect(jmxUrl, env);
        MBeanServerConnection mbeanServerConn = jmxConn.getMBeanServerConnection();
        Object ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean.class);
        String cassandraVersion = ((StorageServiceMBean) ssProxy).getReleaseVersion();
        if (cassandraVersion.startsWith("2.0") || cassandraVersion.startsWith("1.")) {
            ssProxy = JMX.newMBeanProxy(mbeanServerConn, ssMbeanName, StorageServiceMBean20.class);
        }

        CompactionManagerMBean cmProxy = JMX.newMBeanProxy(mbeanServerConn, cmMbeanName,
                CompactionManagerMBean.class);
        JmxProxy proxy = new JmxProxy(handler, host, jmxUrl, jmxConn, ssProxy, ssMbeanName, mbeanServerConn,
                cmProxy);
        // registering a listener throws bunch of exceptions, so we do it here rather than in the
        // constructor
        mbeanServerConn.addNotificationListener(ssMbeanName, proxy, null, null);
        LOG.debug("JMX connection to {} properly connected: {}", host, jmxUrl.toString());
        return proxy;
    } catch (IOException | InstanceNotFoundException e) {
        LOG.error("Failed to establish JMX connection to {}:{}", host, port);
        throw new ReaperException("Failure when establishing JMX connection", e);
    }
}

From source file:org.hyperic.hq.product.jmx.MxNotificationListener.java

public void add() throws PluginException {

    MBeanServerConnection mServer;

    try {//  w ww . ja v a  2 s . c  o m
        mServer = MxUtil.getMBeanServer(this.props);
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    }

    String[] mbeans = translate(this.mbeans);

    for (int i = 0; i < mbeans.length; i++) {
        ObjectName obj;
        try {
            obj = new ObjectName(mbeans[i]);
        } catch (MalformedObjectNameException e) {
            //programmer error.
            throw new IllegalArgumentException(e.getMessage());
        }

        try {
            mServer.addNotificationListener(obj, this, getFilter(), getHandback());
            log.debug("Added listener for: " + mbeans[i]);
        } catch (Exception e) {
            throw new PluginException("addNotificationListener(" + mbeans[i] + "): " + e.getMessage(), e);
        }
    }
}

From source file:org.rhq.enterprise.server.alert.engine.CacheListener.java

private void init() {
    MyListener listener = new MyListener();
    NotificationFilterSupport filter = null;

    try {/*ww  w. ja  v a  2s. c o m*/
        // get reference to MBean server
        Context ic = new InitialContext();
        MBeanServerConnection server = (MBeanServerConnection) ic.lookup("jmx/invoker/RMIAdaptor");

        // get reference to CacheMgmtInterceptor MBean
        String cacheName = "rhq.cache:subsystem=alerts,service=cache";
        ObjectName mgmt_name = new ObjectName(cacheName);

        // configure a filter to only receive node created and removed events
        filter = new NotificationFilterSupport();
        filter.disableAllTypes();
        filter.enableType(CacheMgmtInterceptor.NOTIF_NODE_CREATED);
        filter.enableType(CacheMgmtInterceptor.NOTIF_NODE_REMOVED);
        filter.enableType(CacheMgmtInterceptor.NOTIF_NODE_MODIFIED);

        // register the listener with a filter
        // leave the filter null to receive all cache events
        server.addNotificationListener(mgmt_name, listener, filter, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.zenoss.jmxnl.NotificationListener.java

@SuppressWarnings("unchecked")
private void connect() throws IOException {
    log.info(url + ": Attempting connection (timeout in 180 seconds)");
    JMXConnector connector = JMXConnectorFactory.connect(url, environment);
    connector.addConnectionNotificationListener(this, null, "placeholder");
    MBeanServerConnection connection = connector.getMBeanServerConnection();

    log.info(url + ": Connected.");
    sendConnectionEvent("0", "JMX connection has been restored");

    Set<ObjectName> results = connection.queryNames(scope, null);
    java.util.Iterator<ObjectName> iter = results.iterator();
    while (iter.hasNext()) {
        ObjectName objName = (ObjectName) iter.next();
        String type = objName.getKeyProperty("type");
        if (type == null || !type.equals("alias")) {
            try {
                connection.addNotificationListener(objName, this, attributeFilter, zenossDevice);
                log.debug("Added notification listener: " + objName);
            } catch (IllegalArgumentException e) {
                log.debug("Can't listen to " + objName + " because it is not a notification broadcaster.");
            } catch (InstanceNotFoundException e) {
                log.debug("Can't listen to " + objName + " because it was not found on the server.");
            }/*  ww w  . j a  v a 2  s  .  com*/
        }

        // There can be a lot of listeners to add. Give other threads a
        // chance to get work done while this happens.
        Thread.yield();
    }
}