use of javax.management.Notification in project jdk8u_jdk by JetBrains.
the class RMIAltAuthTest method main.
public static void main(String[] args) {
try {
// Override the default JAAS configuration
//
final String loginConfig = System.getProperty("test.src") + File.separator + "jmxremote.login";
System.out.println("JAAS configuration file = " + loginConfig);
System.setProperty("java.security.auth.login.config", "file:" + loginConfig);
// 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 username/password entries
//
Properties props = new Properties();
props.setProperty("jmx.remote.x.login.config", "PasswordFileAuthentication");
// 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", "pwd1" };
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);
}
}
use of javax.management.Notification in project jdk8u_jdk by JetBrains.
the class MXBeanNotifTest method run.
public void run(Map<String, Object> args) {
System.out.println("MXBeanNotifTest::run: Start");
int errorCount = 0;
try {
parseArgs(args);
notifList = new ArrayBlockingQueue<Notification>(numOfNotifications);
// JMX MbeanServer used inside single VM as if remote.
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
// ----
System.out.println("MXBeanNotifTest::run: Create and register the MBean");
ObjectName objName = new ObjectName("sqe:type=Basic,protocol=rmi");
mbsc.createMBean(BASIC_MXBEAN_CLASS_NAME, objName);
System.out.println("---- OK\n");
// ----
System.out.println("MXBeanNotifTest::run: Add me as notification listener");
mbsc.addNotificationListener(objName, this, null, null);
// ----
System.out.println("MXBeanNotifTest::run: Retrieve the Descriptor" + " that should be in MBeanNotificationInfo");
TabularData tabData = (TabularData) mbsc.getAttribute(objName, "NotifDescriptorAsMapAtt");
Map<String, String> descrMap = new HashMap<>();
for (Iterator<?> it = tabData.values().iterator(); it.hasNext(); ) {
CompositeData compData = (CompositeData) it.next();
descrMap.put((String) compData.get("key"), (String) compData.get("value"));
}
Descriptor refNotifDescriptor = new ImmutableDescriptor(descrMap);
System.out.println("---- OK\n");
// ----
// Because the MBean holding the targeted attribute is MXBean, we
// should use for the setAttribute a converted form for the
// attribute value as described by the MXBean mapping rules.
// This explains all that lovely stuff for creating a
// TabularDataSupport.
//
// WARNING : the MBeanInfo of the MXBean used on opposite side
// is computed when the MBean is registered.
// It means the Descriptor considered for the MBeanNotificationInfo
// is not the one we set in the lines below, it is too late.
// However, we check that set is harmless when we check
// the MBeanNotificationInfo.
//
System.out.println("MXBeanNotifTest::run: Set a Map<String, String>" + " attribute");
String typeName = "java.util.Map<java.lang.String,java.lang.String>";
String[] keyValue = new String[] { "key", "value" };
OpenType<?>[] openTypes = new OpenType<?>[] { SimpleType.STRING, SimpleType.STRING };
CompositeType rowType = new CompositeType(typeName, typeName, keyValue, keyValue, openTypes);
TabularType tabType = new TabularType(typeName, typeName, rowType, new String[] { "key" });
TabularDataSupport convertedDescrMap = new TabularDataSupport(tabType);
for (int i = 0; i < numOfNotifDescriptorElements; i++) {
Object[] descrValue = { "field" + i, "value" + i };
CompositeData data = new CompositeDataSupport(rowType, keyValue, descrValue);
convertedDescrMap.put(data);
}
Attribute descrAtt = new Attribute("NotifDescriptorAsMapAtt", convertedDescrMap);
mbsc.setAttribute(objName, descrAtt);
System.out.println("---- OK\n");
// ----
System.out.println("MXBeanNotifTest::run: Compare the Descriptor from" + " the MBeanNotificationInfo against a reference");
MBeanInfo mbInfo = mbsc.getMBeanInfo(objName);
errorCount += checkMBeanInfo(mbInfo, refNotifDescriptor);
System.out.println("---- DONE\n");
// ----
System.out.println("Check isInstanceOf(Basic)");
if (!mbsc.isInstanceOf(objName, BASIC_MXBEAN_CLASS_NAME)) {
errorCount++;
System.out.println("---- ERROR isInstanceOf returned false\n");
} else {
System.out.println("---- OK\n");
}
// ----
System.out.println("Check isInstanceOf(BasicMXBean)");
if (!mbsc.isInstanceOf(objName, BASIC_MXBEAN_INTERFACE_NAME)) {
errorCount++;
System.out.println("---- ERROR isInstanceOf returned false\n");
} else {
System.out.println("---- OK\n");
}
// ----
System.out.println("MXBeanNotifTest::run: Ask for " + numOfNotifications + " notification(s)");
Object[] sendNotifParam = new Object[1];
String[] sendNotifSig = new String[] { "java.lang.String" };
for (int i = 0; i < numOfNotifications; i++) {
// Select which type of notification we ask for
if (i % 2 == 0) {
sendNotifParam[0] = Basic.NOTIF_TYPE_0;
} else {
sendNotifParam[0] = Basic.NOTIF_TYPE_1;
}
// Trigger notification emission
mbsc.invoke(objName, "sendNotification", sendNotifParam, sendNotifSig);
// Wait for it then check it when it comes early enough
Notification notif = notifList.poll(timeForNotificationInSeconds, TimeUnit.SECONDS);
// notifications are delivered with, we prefer to secure it.
if (i == 0 && notif == null) {
System.out.println("MXBeanNotifTest::run: Wait extra " + timeForNotificationInSeconds + " second(s) the " + " very first notification");
notif = notifList.poll(timeForNotificationInSeconds, TimeUnit.SECONDS);
}
if (notif == null) {
errorCount++;
System.out.println("---- ERROR No notification received" + " within allocated " + timeForNotificationInSeconds + " second(s) !");
} else {
errorCount += checkNotification(notif, (String) sendNotifParam[0], Basic.NOTIFICATION_MESSAGE, objName);
}
}
int toc = 0;
while (notifList.size() < 2 && toc < 10) {
Thread.sleep(499);
toc++;
}
System.out.println("---- DONE\n");
} catch (Exception e) {
Utils.printThrowable(e, true);
throw new RuntimeException(e);
}
if (errorCount == 0) {
System.out.println("MXBeanNotifTest::run: Done without any error");
} else {
System.out.println("MXBeanNotifTest::run: Done with " + errorCount + " error(s)");
throw new RuntimeException("errorCount = " + errorCount);
}
}
use of javax.management.Notification 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);
}
use of javax.management.Notification in project jdk8u_jdk by JetBrains.
the class ConnectionTest method test.
private static boolean test(String proto) throws Exception {
ObjectName serverName = ObjectName.getInstance("d:type=server");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
JMXAuthenticator authenticator = new BogusAuthenticator();
Map env = Collections.singletonMap("jmx.remote.authenticator", authenticator);
JMXServiceURL url = new JMXServiceURL("service:jmx:" + proto + "://");
JMXConnectorServer server;
try {
server = JMXConnectorServerFactory.newJMXConnectorServer(url, env, null);
} catch (MalformedURLException e) {
System.out.println("Protocol " + proto + " not supported, ignoring");
return true;
}
System.out.println("Created connector server");
mbs.registerMBean(server, serverName);
System.out.println("Registered connector server in MBean server");
mbs.addNotificationListener(serverName, logListener, null, null);
mbs.invoke(serverName, "start", null, null);
System.out.println("Started connector server");
JMXServiceURL address = (JMXServiceURL) mbs.getAttribute(serverName, "Address");
System.out.println("Retrieved address: " + address);
if (address.getHost().length() == 0) {
System.out.println("Generated address has empty hostname");
return false;
}
JMXConnector client = JMXConnectorFactory.connect(address);
System.out.println("Client connected");
String clientConnId = client.getConnectionId();
System.out.println("Got connection ID on client: " + clientConnId);
boolean ok = checkConnectionId(proto, clientConnId);
if (!ok)
return false;
System.out.println("Connection ID is OK");
// 4901826: connection ids need some time to be updated using jmxmp
// we don't get the notif immediately either
// this was originally timeout 1ms, which was not enough
Notification notif = waitForNotification(1000);
System.out.println("Server got notification: " + notif);
ok = mustBeConnectionNotification(notif, clientConnId, JMXConnectionNotification.OPENED);
if (!ok)
return false;
client.close();
System.out.println("Closed client");
notif = waitForNotification(1000);
System.out.println("Got notification: " + notif);
ok = mustBeConnectionNotification(notif, clientConnId, JMXConnectionNotification.CLOSED);
if (!ok)
return false;
client = JMXConnectorFactory.connect(address);
System.out.println("Second client connected");
String clientConnId2 = client.getConnectionId();
if (clientConnId.equals(clientConnId2)) {
System.out.println("Same connection ID for two connections: " + clientConnId2);
return false;
}
System.out.println("Second client connection ID is different");
notif = waitForNotification(1);
ok = mustBeConnectionNotification(notif, clientConnId2, JMXConnectionNotification.OPENED);
if (!ok)
return false;
MBeanServerConnection mbsc = client.getMBeanServerConnection();
Map attrs = (Map) mbsc.getAttribute(serverName, "Attributes");
System.out.println("Server attributes received by client: " + attrs);
server.stop();
System.out.println("Server stopped");
notif = waitForNotification(1000);
System.out.println("Server got connection-closed notification: " + notif);
ok = mustBeConnectionNotification(notif, clientConnId2, JMXConnectionNotification.CLOSED);
if (!ok)
return false;
try {
mbsc.getDefaultDomain();
System.out.println("Connection still working but should not be");
return false;
} catch (IOException e) {
System.out.println("Connection correctly got exception: " + e);
}
try {
client = JMXConnectorFactory.connect(address);
System.out.println("Connector server still working but should " + "not be");
return false;
} catch (IOException e) {
System.out.println("New connection correctly got exception: " + e);
}
return true;
}
use of javax.management.Notification in project jdk8u_jdk by JetBrains.
the class MBS_Light method sendNotification.
// Send a notification
public void sendNotification() {
Notification notification = new Notification("JSR160-TCK-NOTIFICATION", this, count++);
sendNotification(notification);
}
Aggregations