Search in sources :

Example 31 with NotificationListener

use of javax.management.NotificationListener in project jdk8u_jdk by JetBrains.

the class DirectoryScannerTest method doTestOperation.

private void doTestOperation(DirectoryScannerMXBean proxy, Call op, EnumSet<ScanState> after, String testName) throws Exception {
    System.out.println("doTestOperation: " + testName);
    final LinkedBlockingQueue<Notification> queue = new LinkedBlockingQueue<Notification>();
    NotificationListener listener = new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            try {
                queue.put(notification);
            } catch (Exception x) {
                System.err.println("Failed to queue notif: " + x);
            }
        }
    };
    NotificationFilter filter = null;
    Object handback = null;
    final ScanState before;
    final NotificationEmitter emitter = (NotificationEmitter) makeNotificationEmitter(proxy, DirectoryScannerMXBean.class);
    emitter.addNotificationListener(listener, filter, handback);
    before = proxy.getState();
    op.call();
    try {
        final Notification notification = queue.poll(3000, TimeUnit.MILLISECONDS);
        assertEquals(AttributeChangeNotification.ATTRIBUTE_CHANGE, notification.getType());
        assertEquals(AttributeChangeNotification.class, notification.getClass());
        assertEquals(getObjectName(proxy), notification.getSource());
        AttributeChangeNotification acn = (AttributeChangeNotification) notification;
        assertEquals("State", acn.getAttributeName());
        assertEquals(ScanState.class.getName(), acn.getAttributeType());
        assertEquals(before, ScanState.valueOf((String) acn.getOldValue()));
        assertContained(after, ScanState.valueOf((String) acn.getNewValue()));
        emitter.removeNotificationListener(listener, filter, handback);
    } finally {
        try {
            op.cancel();
        } catch (Exception x) {
            System.err.println("Failed to cleanup: " + x);
        }
    }
}
Also used : NotificationEmitter(javax.management.NotificationEmitter) AttributeChangeNotification(javax.management.AttributeChangeNotification) ScanState(com.sun.jmx.examples.scandir.ScanManagerMXBean.ScanState) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) NotificationFilter(javax.management.NotificationFilter) Notification(javax.management.Notification) AttributeChangeNotification(javax.management.AttributeChangeNotification) NotificationListener(javax.management.NotificationListener)

Example 32 with NotificationListener

use of javax.management.NotificationListener in project jdk8u_jdk by JetBrains.

the class DirectoryScannerTest method testScan.

/**
     * Test of scan method, of class com.sun.jmx.examples.scandir.DirectoryScanner.
     */
public void testScan() throws Exception {
    System.out.println("scan");
    final ScanManagerMXBean manager = ScanManager.register();
    try {
        final String tmpdir = System.getProperty("java.io.tmpdir");
        final ScanDirConfigMXBean config = manager.getConfigurationMBean();
        final DirectoryScannerConfig bean = config.addDirectoryScanner("test1", tmpdir, ".*", 0, 0);
        config.addDirectoryScanner("test2", tmpdir, ".*", 0, 0);
        config.addDirectoryScanner("test3", tmpdir, ".*", 0, 0);
        manager.applyConfiguration(true);
        final DirectoryScannerMXBean proxy = manager.getDirectoryScanners().get("test1");
        final Call op = new Call() {

            public void call() throws Exception {
                final BlockingQueue<Notification> queue = new LinkedBlockingQueue<Notification>();
                final NotificationListener listener = new NotificationListener() {

                    public void handleNotification(Notification notification, Object handback) {
                        try {
                            queue.put(notification);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                manager.start();
                while (true) {
                    final Notification n = queue.poll(10, TimeUnit.SECONDS);
                    if (n == null)
                        break;
                    final AttributeChangeNotification at = (AttributeChangeNotification) n;
                    if (RUNNING == ScanState.valueOf((String) at.getNewValue()))
                        break;
                    else {
                        System.err.println("New state: " + (String) at.getNewValue() + " isn't " + RUNNING);
                    }
                }
                assertContained(EnumSet.of(SCHEDULED, RUNNING, COMPLETED), proxy.getState());
            }

            public void cancel() throws Exception {
                manager.stop();
            }
        };
        doTestOperation(proxy, op, EnumSet.of(RUNNING, SCHEDULED, COMPLETED), "scan");
    } catch (Exception x) {
        x.printStackTrace();
        throw x;
    } finally {
        try {
            manager.stop();
        } catch (Exception x) {
            System.err.println("Failed to stop: " + x);
        }
        try {
            ManagementFactory.getPlatformMBeanServer().unregisterMBean(ScanManager.SCAN_MANAGER_NAME);
        } catch (Exception x) {
            System.err.println("Failed to cleanup: " + x);
        }
    }
}
Also used : Call(com.sun.jmx.examples.scandir.ScanManagerTest.Call) AttributeChangeNotification(javax.management.AttributeChangeNotification) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Notification(javax.management.Notification) AttributeChangeNotification(javax.management.AttributeChangeNotification) DirectoryScannerConfig(com.sun.jmx.examples.scandir.config.DirectoryScannerConfig) NotificationListener(javax.management.NotificationListener)

Example 33 with NotificationListener

use of javax.management.NotificationListener in project jdk8u_jdk by JetBrains.

the class Client method run.

public static void run(String url) throws Exception {
    final int notifEmittedCnt = 10;
    final CountDownLatch counter = new CountDownLatch(notifEmittedCnt);
    final Set<Long> seqSet = Collections.synchronizedSet(new HashSet<Long>());
    final AtomicBoolean duplNotification = new AtomicBoolean();
    JMXServiceURL serverUrl = new JMXServiceURL(url);
    ObjectName name = new ObjectName("test", "foo", "bar");
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serverUrl);
    System.out.println("client connected");
    jmxConnector.addConnectionNotificationListener(new NotificationListener() {

        @Override
        public void handleNotification(Notification notification, Object handback) {
            System.out.println("connection notification: " + notification);
            if (!seqSet.add(notification.getSequenceNumber())) {
                duplNotification.set(true);
            }
            if (notification.getType().equals(JMXConnectionNotification.NOTIFS_LOST)) {
                long lostNotifs = ((Long) ((JMXConnectionNotification) notification).getUserData()).longValue();
                for (int i = 0; i < lostNotifs; i++) {
                    counter.countDown();
                }
            }
        }
    }, null, null);
    MBeanServerConnection jmxServer = jmxConnector.getMBeanServerConnection();
    jmxServer.addNotificationListener(name, new NotificationListener() {

        @Override
        public void handleNotification(Notification notification, Object handback) {
            System.out.println("client got: " + notification);
            if (!seqSet.add(notification.getSequenceNumber())) {
                duplNotification.set(true);
            }
            counter.countDown();
        }
    }, null, null);
    System.out.println("client invoking foo (" + notifEmittedCnt + " times)");
    for (int i = 0; i < notifEmittedCnt; i++) {
        System.out.print(".");
        jmxServer.invoke(name, "foo", new Object[] {}, new String[] {});
    }
    System.out.println();
    try {
        System.out.println("waiting for " + notifEmittedCnt + " notifications to arrive");
        if (!counter.await(30, TimeUnit.SECONDS)) {
            throw new InterruptedException();
        }
        if (duplNotification.get()) {
            System.out.println("ERROR: received duplicated notifications");
            throw new Error("received duplicated notifications");
        }
        System.out.println("\nshutting down client");
    } catch (InterruptedException e) {
        System.out.println("ERROR: notification processing thread interrupted");
        throw new Error("notification thread interrupted unexpectedly");
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) CountDownLatch(java.util.concurrent.CountDownLatch) Notification(javax.management.Notification) JMXConnectionNotification(javax.management.remote.JMXConnectionNotification) ObjectName(javax.management.ObjectName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) JMXConnector(javax.management.remote.JMXConnector) JMXConnectionNotification(javax.management.remote.JMXConnectionNotification) MBeanServerConnection(javax.management.MBeanServerConnection) NotificationListener(javax.management.NotificationListener)

Example 34 with NotificationListener

use of javax.management.NotificationListener in project jdk8u_jdk by JetBrains.

the class RelationNotificationSeqNoTest method main.

public static void main(String[] args) throws Exception {
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    ObjectName relSvcName = new ObjectName("a:type=relationService");
    RelationServiceMBean relSvc = JMX.newMBeanProxy(mbs, relSvcName, RelationServiceMBean.class);
    mbs.createMBean("javax.management.relation.RelationService", relSvcName, new Object[] { Boolean.TRUE }, new String[] { "boolean" });
    final BlockingQueue<Notification> q = new ArrayBlockingQueue<Notification>(100);
    NotificationListener qListener = new NotificationListener() {

        public void handleNotification(Notification notification, Object handback) {
            q.add(notification);
        }
    };
    mbs.addNotificationListener(relSvcName, qListener, null, null);
    RoleInfo leftInfo = new RoleInfo("left", "javax.management.timer.TimerMBean");
    RoleInfo rightInfo = new RoleInfo("right", "javax.management.timer.Timer");
    relSvc.createRelationType("typeName", new RoleInfo[] { leftInfo, rightInfo });
    ObjectName timer1 = new ObjectName("a:type=timer,number=1");
    ObjectName timer2 = new ObjectName("a:type=timer,number=2");
    mbs.createMBean("javax.management.timer.Timer", timer1);
    mbs.createMBean("javax.management.timer.Timer", timer2);
    Role leftRole = new Role("left", Arrays.asList(new ObjectName[] { timer1 }));
    Role rightRole = new Role("right", Arrays.asList(new ObjectName[] { timer2 }));
    RoleList roles = new RoleList(Arrays.asList(new Role[] { leftRole, rightRole }));
    final int NREPEAT = 10;
    for (int i = 0; i < NREPEAT; i++) {
        relSvc.createRelation("relationName", "typeName", roles);
        relSvc.removeRelation("relationName");
    }
    Notification firstNotif = q.remove();
    long seqNo = firstNotif.getSequenceNumber();
    for (int i = 0; i < NREPEAT * 2 - 1; i++) {
        Notification n = q.remove();
        long nSeqNo = n.getSequenceNumber();
        if (nSeqNo != seqNo + 1) {
            throw new Exception("TEST FAILED: expected seqNo " + (seqNo + 1) + "; got " + nSeqNo);
        }
        seqNo++;
    }
    System.out.println("TEST PASSED: got " + (NREPEAT * 2) + " notifications " + "with contiguous sequence numbers");
}
Also used : RoleList(javax.management.relation.RoleList) Notification(javax.management.Notification) ObjectName(javax.management.ObjectName) Role(javax.management.relation.Role) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) RoleInfo(javax.management.relation.RoleInfo) RelationServiceMBean(javax.management.relation.RelationServiceMBean) MBeanServer(javax.management.MBeanServer) NotificationListener(javax.management.NotificationListener)

Example 35 with NotificationListener

use of javax.management.NotificationListener in project jdk8u_jdk by JetBrains.

the class RMIPasswdAuthTest method main.

public static void main(String[] args) {
    try {
        // Set the default password file
        //
        final String passwordFile = System.getProperty("test.src") + File.separator + "jmxremote.password";
        System.out.println("Password file = " + passwordFile);
        // Create an RMI registry
        //
        System.out.println("Start RMI registry...");
        Registry reg = null;
        int port = 5800;
        while (port++ < 6000) {
            try {
                reg = LocateRegistry.createRegistry(port);
                System.out.println("RMI registry running on port " + port);
                break;
            } catch (RemoteException e) {
                // Failed to create RMI registry...
                System.out.println("Failed to create RMI registry " + "on port " + port);
            }
        }
        if (reg == null) {
            System.exit(1);
        }
        // Instantiate the MBean server
        //
        System.out.println("Create the MBean server");
        MBeanServer mbs = MBeanServerFactory.createMBeanServer();
        // Register the ClassPathClassLoaderMBean
        //
        System.out.println("Create ClassPathClassLoader MBean");
        ObjectName cpcl = new ObjectName("ClassLoader:name=ClassPathClassLoader");
        mbs.createMBean("javax.management.loading.MLet", cpcl);
        // Register the SimpleStandardMBean
        //
        System.out.println("Create SimpleStandard MBean");
        mbs.createMBean("SimpleStandard", new ObjectName("MBeans:name=SimpleStandard"));
        // Create Properties containing the location of the password file
        //
        Properties props = new Properties();
        props.setProperty("jmx.remote.x.password.file", passwordFile);
        // Initialize environment map to be passed to the connector server
        //
        System.out.println("Initialize environment map");
        HashMap env = new HashMap();
        env.put("jmx.remote.authenticator", new JMXPluggableAuthenticator(props));
        // Create an RMI connector server
        //
        System.out.println("Create an RMI connector server");
        JMXServiceURL url = new JMXServiceURL("rmi", null, 0, "/jndi/rmi://:" + port + "/server" + port);
        JMXConnectorServer rcs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        rcs.start();
        // Create an RMI connector client
        //
        System.out.println("Create an RMI connector client");
        HashMap cli_env = new HashMap();
        // These credentials must match those in the supplied password file
        //
        String[] credentials = new String[] { "monitorRole", "QED" };
        cli_env.put("jmx.remote.credentials", credentials);
        JMXConnector jmxc = JMXConnectorFactory.connect(url, cli_env);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        // Get domains from MBeanServer
        //
        System.out.println("Domains:");
        String[] domains = mbsc.getDomains();
        for (int i = 0; i < domains.length; i++) {
            System.out.println("\tDomain[" + i + "] = " + domains[i]);
        }
        // Get MBean count
        //
        System.out.println("MBean count = " + mbsc.getMBeanCount());
        // Get State attribute
        //
        String oldState = (String) mbsc.getAttribute(new ObjectName("MBeans:name=SimpleStandard"), "State");
        System.out.println("Old State = \"" + oldState + "\"");
        // Set State attribute
        //
        System.out.println("Set State to \"changed state\"");
        mbsc.setAttribute(new ObjectName("MBeans:name=SimpleStandard"), new Attribute("State", "changed state"));
        // Get State attribute
        //
        String newState = (String) mbsc.getAttribute(new ObjectName("MBeans:name=SimpleStandard"), "State");
        System.out.println("New State = \"" + newState + "\"");
        if (!newState.equals("changed state")) {
            System.out.println("Invalid State = \"" + newState + "\"");
            System.exit(1);
        }
        // Add notification listener on SimpleStandard MBean
        //
        System.out.println("Add notification listener...");
        mbsc.addNotificationListener(new ObjectName("MBeans:name=SimpleStandard"), new NotificationListener() {

            public void handleNotification(Notification notification, Object handback) {
                System.out.println("Received notification: " + notification);
            }
        }, null, null);
        // Unregister SimpleStandard MBean
        //
        System.out.println("Unregister SimpleStandard MBean...");
        mbsc.unregisterMBean(new ObjectName("MBeans:name=SimpleStandard"));
        // Close MBeanServer connection
        //
        jmxc.close();
        System.out.println("Bye! Bye!");
    } catch (Exception e) {
        System.out.println("Unexpected exception caught = " + e);
        e.printStackTrace();
        System.exit(1);
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JMXPluggableAuthenticator(com.sun.jmx.remote.security.JMXPluggableAuthenticator) HashMap(java.util.HashMap) Attribute(javax.management.Attribute) Registry(java.rmi.registry.Registry) LocateRegistry(java.rmi.registry.LocateRegistry) Properties(java.util.Properties) Notification(javax.management.Notification) RemoteException(java.rmi.RemoteException) ObjectName(javax.management.ObjectName) JMXConnectorServer(javax.management.remote.JMXConnectorServer) JMXConnector(javax.management.remote.JMXConnector) RemoteException(java.rmi.RemoteException) MBeanServerConnection(javax.management.MBeanServerConnection) MBeanServer(javax.management.MBeanServer) NotificationListener(javax.management.NotificationListener)

Aggregations

NotificationListener (javax.management.NotificationListener)52 Notification (javax.management.Notification)36 ObjectName (javax.management.ObjectName)18 MBeanServer (javax.management.MBeanServer)11 NotificationFilter (javax.management.NotificationFilter)10 JMXConnector (javax.management.remote.JMXConnector)10 JMXServiceURL (javax.management.remote.JMXServiceURL)10 AttributeChangeNotification (javax.management.AttributeChangeNotification)9 MBeanServerConnection (javax.management.MBeanServerConnection)9 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)8 NotificationEmitter (javax.management.NotificationEmitter)8 JMXConnectorServer (javax.management.remote.JMXConnectorServer)8 Attribute (javax.management.Attribute)7 Test (org.junit.Test)6 JMXPluggableAuthenticator (com.sun.jmx.remote.security.JMXPluggableAuthenticator)5 RemoteException (java.rmi.RemoteException)5 LocateRegistry (java.rmi.registry.LocateRegistry)5 Registry (java.rmi.registry.Registry)5 Properties (java.util.Properties)5