use of javax.management.NotificationFilterSupport in project jdk8u_jdk by JetBrains.
the class NotificationBufferTest method test.
private static boolean test() throws Exception {
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
Integer queuesize = new Integer(10);
HashMap env = new HashMap();
env.put(com.sun.jmx.remote.util.EnvHelp.BUFFER_SIZE_PROPERTY, queuesize);
final NotificationBuffer nb = ArrayNotificationBuffer.getNotificationBuffer(mbs, env);
final ObjectName senderName = new ObjectName("dom:type=sender");
final ObjectName wildcardName = new ObjectName("*:*");
final String notifType = MBeanServerNotification.REGISTRATION_NOTIFICATION;
Integer allListenerId = new Integer(99);
NotificationBufferFilter allListenerFilter = makeFilter(allListenerId, wildcardName, null);
NotificationFilterSupport regFilter = new NotificationFilterSupport();
regFilter.enableType(notifType);
// Get initial sequence number
NotificationResult nr = nb.fetchNotifications(allListenerFilter, 0, 0L, 0);
int nnotifs = nr.getTargetedNotifications().length;
if (nnotifs > 0) {
System.out.println("Expected 0 notifs for initial fetch, " + "got " + nnotifs);
return false;
}
System.out.println("Got 0 notifs for initial fetch, OK");
long earliest = nr.getEarliestSequenceNumber();
long next = nr.getNextSequenceNumber();
if (earliest != next) {
System.out.println("Expected earliest==next in initial fetch, " + "earliest=" + earliest + "; next=" + next);
return false;
}
System.out.println("Got earliest==next in initial fetch, OK");
mbs.createMBean(MLet.class.getName(), null);
mbs.createMBean(NotificationSender.class.getName(), senderName);
NotificationSenderMBean sender = (NotificationSenderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, senderName, NotificationSenderMBean.class, false);
/* We test here that MBeans already present when the
NotificationBuffer was created get a listener for the
buffer, as do MBeans created later. The
MBeanServerDelegate was already present, while the
NotificationSender was created later. */
// Check that the NotificationSender does indeed have a listener
/* Note we are dependent on the specifics of our JMX
implementation here. There is no guarantee that the MBean
creation listeners will have run to completion when
creation of the MBean returns. */
int nlisteners = sender.getListenerCount();
if (nlisteners != 1) {
System.out.println("Notification sender should have 1 listener, " + "has " + nlisteners);
return false;
}
System.out.println("Notification sender has 1 listener, OK");
// Now we should see two creation notifications
nr = nb.fetchNotifications(allListenerFilter, next, 0L, Integer.MAX_VALUE);
TargetedNotification[] tns = nr.getTargetedNotifications();
if (tns.length != 2) {
System.out.println("Expected 2 notifs, got: " + Arrays.asList(tns));
return false;
}
if (!(tns[0].getNotification() instanceof MBeanServerNotification) || !(tns[1].getNotification() instanceof MBeanServerNotification)) {
System.out.println("Expected 2 MBeanServerNotifications, got: " + Arrays.asList(tns));
return false;
}
if (!tns[0].getListenerID().equals(tns[1].getListenerID()) || !tns[0].getListenerID().equals(allListenerId)) {
System.out.println("Bad listener IDs: " + Arrays.asList(tns));
return false;
}
System.out.println("Got 2 different MBeanServerNotifications, OK");
// If we ask for max 1 notifs, we should only get one
nr = nb.fetchNotifications(allListenerFilter, next, 0L, 1);
tns = nr.getTargetedNotifications();
if (tns.length != 1) {
System.out.println("Expected 1 notif, got: " + Arrays.asList(tns));
return false;
}
TargetedNotification tn1 = tns[0];
System.out.println("Got 1 notif when asked for 1, OK");
// Now we should get the other one
nr = nb.fetchNotifications(allListenerFilter, nr.getNextSequenceNumber(), 0L, 1);
tns = nr.getTargetedNotifications();
if (tns.length != 1) {
System.out.println("Expected 1 notif, got: " + Arrays.asList(tns));
return false;
}
TargetedNotification tn2 = tns[0];
System.out.println("Got 1 notif when asked for 1 again, OK");
if (tn1.getNotification() == tn2.getNotification()) {
System.out.println("Returned same notif twice: " + tn1);
return false;
}
System.out.println("2 creation notifs are different, OK");
// Now we should get none (timeout is 0)
long oldNext = nr.getNextSequenceNumber();
nr = nb.fetchNotifications(allListenerFilter, oldNext, 0L, Integer.MAX_VALUE);
tns = nr.getTargetedNotifications();
if (tns.length != 0) {
System.out.println("Expected 0 notifs, got: " + Arrays.asList(tns));
return false;
}
System.out.println("Got 0 notifs with 0 timeout, OK");
if (nr.getNextSequenceNumber() != oldNext) {
System.out.println("Sequence number changed: " + oldNext + " -> " + nr.getNextSequenceNumber());
return false;
}
System.out.println("Next seqno unchanged with 0 timeout, OK");
// Check that timeouts work
long startTime = System.currentTimeMillis();
nr = nb.fetchNotifications(allListenerFilter, oldNext, 250L, Integer.MAX_VALUE);
tns = nr.getTargetedNotifications();
if (tns.length != 0) {
System.out.println("Expected 0 notifs, got: " + Arrays.asList(tns));
return false;
}
long endTime = System.currentTimeMillis();
long elapsed = endTime - startTime;
if (elapsed < 250L) {
System.out.println("Elapsed time shorter than timeout: " + elapsed);
return false;
}
System.out.println("Timeout worked, OK");
// Check that notification filtering works
NotificationFilter senderFilter = new NotificationFilter() {
public boolean isNotificationEnabled(Notification n) {
if (!(n instanceof MBeanServerNotification))
return false;
MBeanServerNotification mbsn = (MBeanServerNotification) n;
return (mbsn.getMBeanName().equals(senderName));
}
};
Integer senderListenerId = new Integer(88);
NotificationBufferFilter senderListenerFilter = makeFilter(senderListenerId, wildcardName, senderFilter);
nr = nb.fetchNotifications(senderListenerFilter, 0, 1000L, Integer.MAX_VALUE);
tns = nr.getTargetedNotifications();
if (tns.length != 1) {
System.out.println("Expected 1 notif, got: " + Arrays.asList(tns));
return false;
}
MBeanServerNotification mbsn = (MBeanServerNotification) tns[0].getNotification();
if (!mbsn.getMBeanName().equals(senderName)) {
System.out.println("Expected notif with senderName, got: " + mbsn + " (" + mbsn.getMBeanName() + ")");
return false;
}
System.out.println("Successfully applied NotificationFilter, OK");
// Now send 8 notifs to fill up our 10-element buffer
sender.sendNotifs("tiddly.pom", 8);
nr = nb.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
tns = nr.getTargetedNotifications();
if (tns.length != 10) {
System.out.println("Expected 10 notifs, got: " + Arrays.asList(tns));
return false;
}
System.out.println("Got full buffer of 10 notifications, OK");
// Check that the 10 notifs are the ones we expected
for (int i = 0; i < 10; i++) {
String expected = (i < 2) ? notifType : "tiddly.pom";
String found = tns[i].getNotification().getType();
if (!found.equals(expected)) {
System.out.println("Notif " + i + " bad type: expected <" + expected + ">, found <" + found + ">");
return false;
}
}
System.out.println("Notifs have right types, OK");
// Check that ObjectName filtering works
NotificationBufferFilter senderNameFilter = makeFilter(new Integer(66), senderName, null);
nr = nb.fetchNotifications(senderNameFilter, 0, 0L, Integer.MAX_VALUE);
tns = nr.getTargetedNotifications();
if (tns.length != 8) {
System.out.println("Bad result from ObjectName filtering: " + Arrays.asList(tns));
return false;
}
System.out.println("ObjectName filtering works, OK");
// Send one more notif, which should cause the oldest one to drop
sender.sendNotifs("foo.bar", 1);
nr = nb.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
if (nr.getEarliestSequenceNumber() <= earliest) {
System.out.println("Expected earliest to increase: " + nr.getEarliestSequenceNumber() + " should be > " + earliest);
return false;
}
System.out.println("Earliest notif dropped, OK");
// Check that the 10 notifs are the ones we expected
tns = nr.getTargetedNotifications();
for (int i = 0; i < 10; i++) {
String expected = (i < 1) ? notifType : (i < 9) ? "tiddly.pom" : "foo.bar";
String found = tns[i].getNotification().getType();
if (!found.equals(expected)) {
System.out.println("Notif " + i + " bad type: expected <" + expected + ">, found <" + found + ">");
return false;
}
}
System.out.println("Notifs have right types, OK");
// Apply a filter that only selects the first notif, with max notifs 1,
// then check that it skipped past the others even though it already
// had its 1 notif
NotificationBufferFilter firstFilter = makeFilter(new Integer(55), wildcardName, regFilter);
nr = nb.fetchNotifications(firstFilter, 0, 1000L, 1);
tns = nr.getTargetedNotifications();
if (tns.length != 1 || !tns[0].getNotification().getType().equals(notifType)) {
System.out.println("Unexpected return from filtered call: " + Arrays.asList(tns));
return false;
}
nr = nb.fetchNotifications(allListenerFilter, nr.getNextSequenceNumber(), 0L, 1000);
tns = nr.getTargetedNotifications();
if (tns.length != 0) {
System.out.println("Expected 0 notifs, got: " + Arrays.asList(tns));
return false;
}
// Create a second, larger buffer, which should share the same notifs
nr = nb.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
queuesize = new Integer(20);
env.put(com.sun.jmx.remote.util.EnvHelp.BUFFER_SIZE_PROPERTY, queuesize);
NotificationBuffer nb2 = ArrayNotificationBuffer.getNotificationBuffer(mbs, env);
NotificationResult nr2 = nb2.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
if (nr.getEarliestSequenceNumber() != nr2.getEarliestSequenceNumber() || nr.getNextSequenceNumber() != nr2.getNextSequenceNumber() || !sameTargetedNotifs(nr.getTargetedNotifications(), nr2.getTargetedNotifications()))
return false;
System.out.println("Adding second buffer preserved notif list, OK");
// Check that the capacity is now 20
sender.sendNotifs("propter.hoc", 10);
nr2 = nb2.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
if (nr.getEarliestSequenceNumber() != nr2.getEarliestSequenceNumber()) {
System.out.println("Earliest seq number changed after notifs " + "that should have fit");
return false;
}
TargetedNotification[] tns2 = new TargetedNotification[10];
Arrays.asList(nr2.getTargetedNotifications()).subList(0, 10).toArray(tns2);
if (!sameTargetedNotifs(nr.getTargetedNotifications(), tns2)) {
System.out.println("Early notifs changed after notifs " + "that should have fit");
return false;
}
System.out.println("New notifications fit in now-larger buffer, OK");
// Drop the second buffer and check that the capacity shrinks
nb2.dispose();
NotificationResult nr3 = nb.fetchNotifications(allListenerFilter, 0, 1000L, Integer.MAX_VALUE);
if (nr3.getEarliestSequenceNumber() != nr.getNextSequenceNumber()) {
System.out.println("After shrink, notifs not dropped as expected");
return false;
}
if (nr3.getNextSequenceNumber() != nr2.getNextSequenceNumber()) {
System.out.println("After shrink, next seq no does not match");
return false;
}
tns2 = new TargetedNotification[10];
Arrays.asList(nr2.getTargetedNotifications()).subList(10, 20).toArray(tns2);
if (!sameTargetedNotifs(nr3.getTargetedNotifications(), tns2)) {
System.out.println("Later notifs not preserved after shrink");
return false;
}
System.out.println("Dropping second buffer shrank capacity, OK");
// Final test: check that destroying the final shared buffer
// removes its listeners
nb.dispose();
nlisteners = sender.getListenerCount();
if (nlisteners != 0) {
System.out.println("Disposing buffer should leave 0 listeners, " + "but notification sender has " + nlisteners);
return false;
}
System.out.println("Dropping first buffer drops listeners, OK");
return true;
}
use of javax.management.NotificationFilterSupport in project logging-log4j2 by apache.
the class ClientGui method registerListeners.
private void registerListeners(final StatusLoggerAdminMBean status) throws InstanceNotFoundException, MalformedObjectNameException, IOException {
final NotificationFilterSupport filter = new NotificationFilterSupport();
filter.enableType(StatusLoggerAdminMBean.NOTIF_TYPE_MESSAGE);
final ObjectName objName = status.getObjectName();
// System.out.println("Add listener for " + objName);
client.getConnection().addNotificationListener(objName, this, filter, status.getContextName());
}
use of javax.management.NotificationFilterSupport in project jdk8u_jdk by JetBrains.
the class RMINotifTest method main.
public static void main(String[] args) {
try {
// create a rmi registry
Registry reg = null;
int port = 6666;
final Random r = new Random();
while (port++ < 7000) {
try {
reg = LocateRegistry.createRegistry(++port);
System.out.println("Creation of rmi registry succeeded. Running on port " + port);
break;
} catch (RemoteException re) {
// no problem
}
}
if (reg == null) {
System.out.println("Failed to create a RMI registry, " + "the ports from 6666 to 6999 are all occupied.");
System.exit(1);
}
// create a MBeanServer
MBeanServer server = MBeanServerFactory.createMBeanServer();
// create a notif emitter mbean
ObjectName mbean = new ObjectName("Default:name=NotificationEmitter");
server.registerMBean(new NotificationEmitter(), mbean);
// create a rmi server
JMXServiceURL url = new JMXServiceURL("rmi", null, port, "/jndi/rmi://:" + port + "/server" + port);
System.out.println("RMIConnectorServer address " + url);
JMXConnectorServer sServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, null);
ObjectInstance ss = server.registerMBean(sServer, new ObjectName("Default:name=RmiConnectorServer"));
sServer.start();
// create a rmi client
JMXConnector rmiConnection = JMXConnectorFactory.newJMXConnector(url, null);
rmiConnection.connect(null);
MBeanServerConnection client = rmiConnection.getMBeanServerConnection();
// add listener at the client side
client.addNotificationListener(mbean, listener, null, null);
//ask to send notifs
Object[] params = new Object[1];
String[] signatures = new String[1];
params[0] = new Integer(nb);
signatures[0] = "java.lang.Integer";
client.invoke(mbean, "sendNotifications", params, signatures);
// waiting ...
synchronized (lock) {
if (receivedNotifs != nb) {
lock.wait(10000);
System.out.println(">>> Received notifications..." + receivedNotifs);
}
}
// check
if (receivedNotifs != nb) {
System.exit(1);
} else {
System.out.println("The client received all notifications.");
}
// remove listener
client.removeNotificationListener(mbean, listener);
// more test
NotificationFilterSupport filter = new NotificationFilterSupport();
Object o = new Object();
client.addNotificationListener(mbean, listener, filter, o);
client.removeNotificationListener(mbean, listener, filter, o);
sServer.stop();
// // clean
// client.unregisterMBean(mbean);
// rmiConnection.close();
// Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
use of javax.management.NotificationFilterSupport in project jdk8u_jdk by JetBrains.
the class DeadListenerTest method main.
public static void main(String[] args) throws Exception {
final ObjectName delegateName = MBeanServerDelegate.DELEGATE_NAME;
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Noddy mbean = new Noddy();
ObjectName name = new ObjectName("d:k=v");
mbs.registerMBean(mbean, name);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
SnoopRMIServerImpl rmiServer = new SnoopRMIServerImpl();
RMIConnectorServer cs = new RMIConnectorServer(url, null, rmiServer, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
assertTrue("No connections in new connector server", rmiServer.connections.isEmpty());
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
assertTrue("One connection on server after client connect", rmiServer.connections.size() == 1);
RMIConnectionImpl connection = rmiServer.connections.get(0);
Method getServerNotifFwdM = RMIConnectionImpl.class.getDeclaredMethod("getServerNotifFwd");
getServerNotifFwdM.setAccessible(true);
ServerNotifForwarder serverNotifForwarder = (ServerNotifForwarder) getServerNotifFwdM.invoke(connection);
Field listenerMapF = ServerNotifForwarder.class.getDeclaredField("listenerMap");
listenerMapF.setAccessible(true);
@SuppressWarnings("unchecked") Map<ObjectName, Set<?>> listenerMap = (Map<ObjectName, Set<?>>) listenerMapF.get(serverNotifForwarder);
assertTrue("Server listenerMap initially empty", mapWithoutKey(listenerMap, delegateName).isEmpty());
final AtomicInteger count1Val = new AtomicInteger();
CountListener count1 = new CountListener(count1Val);
mbsc.addNotificationListener(name, count1, null, null);
WeakReference<CountListener> count1Ref = new WeakReference<>(count1);
count1 = null;
final AtomicInteger count2Val = new AtomicInteger();
CountListener count2 = new CountListener(count2Val);
NotificationFilterSupport dummyFilter = new NotificationFilterSupport();
dummyFilter.enableType("");
mbsc.addNotificationListener(name, count2, dummyFilter, "noddy");
WeakReference<CountListener> count2Ref = new WeakReference<>(count2);
count2 = null;
assertTrue("One entry in listenerMap for two listeners on same MBean", mapWithoutKey(listenerMap, delegateName).size() == 1);
Set<?> set = listenerMap.get(name);
assertTrue("Set in listenerMap for MBean has two elements", set != null && set.size() == 2);
assertTrue("Initial value of count1 == 0", count1Val.get() == 0);
assertTrue("Initial value of count2 == 0", count2Val.get() == 0);
Notification notif = new Notification("type", name, 0);
mbean.sendNotification(notif);
// Make sure notifs are working normally.
long deadline = System.currentTimeMillis() + 2000;
while ((count1Val.get() != 1 || count2Val.get() != 1) && System.currentTimeMillis() < deadline) {
Thread.sleep(10);
}
assertTrue("New value of count1 == 1", count1Val.get() == 1);
assertTrue("Initial value of count2 == 1", count2Val.get() == 1);
// Make sure that removing a nonexistent listener from an existent MBean produces ListenerNotFoundException
CountListener count3 = new CountListener();
try {
mbsc.removeNotificationListener(name, count3);
assertTrue("Remove of nonexistent listener succeeded but should not have", false);
} catch (ListenerNotFoundException e) {
// OK: expected
}
// Make sure that removing a nonexistent listener from a nonexistent MBean produces ListenerNotFoundException
ObjectName nonexistent = new ObjectName("foo:bar=baz");
assertTrue("Nonexistent is nonexistent", !mbs.isRegistered(nonexistent));
try {
mbsc.removeNotificationListener(nonexistent, count3);
assertTrue("Remove of listener from nonexistent MBean succeeded but should not have", false);
} catch (ListenerNotFoundException e) {
// OK: expected
}
// Now unregister our MBean, and check that notifs it sends no longer go anywhere.
mbs.unregisterMBean(name);
mbean.sendNotification(notif);
Thread.sleep(200);
assertTrue("New value of count1 == 1", count1Val.get() == 1);
assertTrue("Initial value of count2 == 1", count2Val.get() == 1);
// wait for the listener cleanup to take place upon processing notifications
// waiting max. 5 secs
int countdown = 50;
while (countdown-- > 0 && (count1Ref.get() != null || count2Ref.get() != null)) {
System.gc();
Thread.sleep(100);
System.gc();
}
// listener has been removed or the wait has timed out
assertTrue("count1 notification listener has not been cleaned up", count1Ref.get() == null);
assertTrue("count2 notification listener has not been cleaned up", count2Ref.get() == null);
// Check that there is no trace of the listeners any more in ServerNotifForwarder.listenerMap.
// THIS DEPENDS ON JMX IMPLEMENTATION DETAILS.
// If the JMX implementation changes, the code here may have to change too.
Set<?> setForUnreg = listenerMap.get(name);
assertTrue("No trace of unregistered MBean: " + setForUnreg, setForUnreg == null);
}
Aggregations