下面列出了javax.management.remote.JMXConnectorServerFactory#newJMXConnectorServer ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static void dotest(JMXServiceURL url, MBeanServer mbs)
throws Exception {
JMXConnectorServer server = null;
JMXConnector client = null;
server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
server.start();
JMXServiceURL outputAddr = server.getAddress();
System.out.println("Server started ["+ outputAddr+ "]");
client = JMXConnectorFactory.newJMXConnector(outputAddr, null);
client.connect();
System.out.println("Client connected");
MBeanServerConnection connection
= client.getMBeanServerConnection();
System.out.println(connection.getDefaultDomain());
}
public static void main(String[] args) throws Exception {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
Sender sender = new Sender();
mbs.registerMBean(sender, testObjectName);
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
try {
test(mbs, cs, cc);
} finally {
cc.close();
cs.stop();
}
}
private static void testWithException(boolean send)
throws Exception {
ClassLoader zoobyCL = new ZoobyClassLoader();
Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
Object zooby = zoobyClass.newInstance();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
Object rzooby;
if (send) {
System.out.println("Sending object...");
mbsc.setAttribute(getSetName, new Attribute("It", zooby));
rzooby = getSetInstance.getIt();
} else {
System.out.println("Receiving object...");
getSetInstance.setIt(zooby);
rzooby = mbsc.getAttribute(getSetName, "It");
}
if (!rzooby.getClass().getName().equals("Zooby")) {
throw new Exception("FAILED: remote object is not a Zooby");
}
if (rzooby.getClass().getClassLoader() ==
zooby.getClass().getClassLoader()) {
throw new Exception("FAILED: same class loader: " +
zooby.getClass().getClassLoader());
}
cc.close();
cs.stop();
}
private static void testWithException(boolean send)
throws Exception {
ClassLoader zoobyCL = new ZoobyClassLoader();
Class<?> zoobyClass = Class.forName("Zooby", false, zoobyCL);
Object zooby = zoobyClass.newInstance();
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, null, pmbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
JMXConnector cc = JMXConnectorFactory.connect(addr);
MBeanServerConnection mbsc = cc.getMBeanServerConnection();
Object rzooby;
if (send) {
System.out.println("Sending object...");
mbsc.setAttribute(getSetName, new Attribute("It", zooby));
rzooby = getSetInstance.getIt();
} else {
System.out.println("Receiving object...");
getSetInstance.setIt(zooby);
rzooby = mbsc.getAttribute(getSetName, "It");
}
if (!rzooby.getClass().getName().equals("Zooby")) {
throw new Exception("FAILED: remote object is not a Zooby");
}
if (rzooby.getClass().getClassLoader() ==
zooby.getClass().getClassLoader()) {
throw new Exception("FAILED: same class loader: " +
zooby.getClass().getClassLoader());
}
cc.close();
cs.stop();
}
private JMXServiceURL createServerSide() throws Exception {
final int NINETY_SECONDS = 90;
// We will use the platform mbean server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
cs.start();
Utils.waitReady(cs, NINETY_SECONDS);
JMXServiceURL addr = cs.getAddress();
return addr;
}
public MBeanServerConnection call() {
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(
url, null, mbs);
cs.start();
JMXServiceURL addr = cs.getAddress();
connector = JMXConnectorFactory.connect(addr);
return connector.getMBeanServerConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
JMXServiceURL inputAddr =
new JMXServiceURL("service:jmx:iiop://");
JMXConnectorServer s;
try {
s = JMXConnectorServerFactory.newJMXConnectorServer(inputAddr, null, null);
} catch (java.net.MalformedURLException x) {
try {
Class.forName("javax.management.remote.rmi._RMIConnectionImpl_Tie");
throw new RuntimeException("MalformedURLException thrown but iiop appears to be supported");
} catch (ClassNotFoundException expected) { }
System.out.println("IIOP protocol not supported, test skipped");
return;
}
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
mbs.registerMBean(s, new ObjectName("a:b=c"));
s.start();
JMXServiceURL outputAddr = s.getAddress();
if (!outputAddr.getURLPath().startsWith("/ior/IOR:")) {
throw new RuntimeException("URL path should start with \"/ior/IOR:\": " +
outputAddr);
}
System.out.println("IIOP URL path looks OK: " + outputAddr);
JMXConnector c = JMXConnectorFactory.connect(outputAddr);
System.out.println("Successfully got default domain: " +
c.getMBeanServerConnection().getDefaultDomain());
c.close();
s.stop();
}
public static void main(String[] args) {
try {
// Instantiate the MBean server
//
System.out.println("Create the MBean server");
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
// Initialize environment map to be passed to the connector server
//
System.out.println("Initialize environment map");
HashMap env = new HashMap();
CustomRMIExporter exporter = new CustomRMIExporter();
env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);
// Create an RMI connector server
//
System.out.println("Create an RMI connector server");
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
// Create an RMI connector client
//
System.out.println("Create an RMI connector client");
JMXConnector cc =
JMXConnectorFactory.connect(cs.getAddress(), null);
// Close RMI connector client
//
System.out.println("Close the RMI connector client");
cc.close();
// Stop RMI connector server
//
System.out.println("Stop the RMI connector server");
cs.stop();
// Check if remote objects were exported/unexported successfully
//
int errorCount = 0;
if (exporter.rmiServerExported) {
System.out.println("RMIServer exported OK!");
} else {
System.out.println("RMIServer exported KO!");
errorCount++;
}
if (exporter.rmiServerUnexported) {
System.out.println("RMIServer unexported OK!");
} else {
System.out.println("RMIServer unexported KO!");
errorCount++;
}
if (exporter.rmiConnectionExported) {
System.out.println("RMIConnection exported OK!");
} else {
System.out.println("RMIConnection exported KO!");
errorCount++;
}
if (exporter.rmiConnectionUnexported) {
System.out.println("RMIConnection unexported OK!");
} else {
System.out.println("RMIConnection unexported KO!");
errorCount++;
}
System.out.println("Bye! Bye!");
if (errorCount > 0) {
System.out.println("RMIExporterTest FAILED!");
System.exit(1);
} else {
System.out.println("RMIExporterTest PASSED!");
}
} catch (Exception e) {
System.out.println("Unexpected exception caught = " + e);
e.printStackTrace();
System.exit(1);
}
}
public void run(Map<String, Object> args) {
System.out.println("MXBeanInteropTest1::run: Start") ;
int errorCount = 0 ;
try {
// JMX MbeanServer used inside single VM as if remote.
// MBeanServer mbs = MBeanServerFactory.newMBeanServer();
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();
// Print out registered java.lang.management MXBeans found
// in the remote jvm.
printMBeans(mbsc) ;
// For each possible kind of JDK 5 defined MXBean, we retrieve its
// MBeanInfo and print it and we call all getters and print
// their output.
errorCount += doClassLoadingMXBeanTest(mbsc) ;
errorCount += doMemoryMXBeanTest(mbsc) ;
errorCount += doThreadMXBeanTest(mbsc) ;
errorCount += doRuntimeMXBeanTest(mbsc) ;
errorCount += doOperatingSystemMXBeanTest(mbsc) ;
errorCount += doCompilationMXBeanTest(mbsc) ;
errorCount += doGarbageCollectorMXBeanTest(mbsc) ;
errorCount += doMemoryManagerMXBeanTest(mbsc) ;
errorCount += doMemoryPoolMXBeanTest(mbsc) ;
// Terminate the JMX Client
cc.close();
} catch(Exception e) {
Utils.printThrowable(e, true) ;
throw new RuntimeException(e);
}
if ( errorCount == 0 ) {
System.out.println("MXBeanInteropTest1::run: Done without any error") ;
} else {
System.out.println("MXBeanInteropTest1::run: Done with "
+ errorCount
+ " error(s)") ;
throw new RuntimeException("errorCount = " + errorCount);
}
}
private JMXServiceURL createServerSide(Map<String, Object> serverMap)
throws Exception {
final int NINETY_SECONDS = 90;
System.out.println("AuthorizationTest::createServerSide: Start") ;
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
// Creates connection environment from server side params
HashMap<String, Object> env = new HashMap<>();
String value = null;
if ((value = (String)serverMap.get("-mapType")) != null) {
if (value.contains("x.access.file")) {
String accessFileStr = System.getProperty("test.src") +
File.separator + "access.properties";
env.put("jmx.remote.x.access.file", accessFileStr);
System.out.println("Added " + accessFileStr + " file as jmx.remote.x.access.file");
}
if (value.contains("x.password.file")) {
String passwordFileStr = System.getProperty("test.src") +
File.separator + "password.properties";
env.put("jmx.remote.x.password.file", passwordFileStr);
System.out.println("Added " + passwordFileStr + " file as jmx.remote.x.password.file");
}
}
if (serverMap.containsKey("-populate")) {
String populateClassName = "Simple";
ObjectName on =
new ObjectName("defaultDomain:class=Simple");
Utils.debug(Utils.DEBUG_STANDARD, "create and register Simple MBean") ;
mbs.createMBean(populateClassName, on);
}
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
Utils.waitReady(cs, NINETY_SECONDS);
JMXServiceURL addr = cs.getAddress();
System.out.println("AuthorizationTest::createServerSide: Done.") ;
return addr;
}
public void run(Map<String, Object> args) {
System.out.println("MXBeanInteropTest2::run: Start") ;
int errorCount = 0 ;
try {
// 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();
// Prints all MBeans whatever the domain is.
printMBeans(mbsc) ;
// Call test body
errorCount += doBasicMXBeanTest(mbsc) ;
// Terminate the JMX Client
cc.close();
} catch(Exception e) {
Utils.printThrowable(e, true) ;
throw new RuntimeException(e);
}
if ( errorCount == 0 ) {
System.out.println("MXBeanInteropTest2::run: Done without any error") ;
} else {
System.out.println("MXBeanInteropTest2::run: Done with "
+ errorCount
+ " error(s)") ;
throw new RuntimeException("errorCount = " + errorCount);
}
}
private static <T> void testInterface(Class<T> c, boolean nullTest)
throws Exception {
System.out.println("Testing " + c.getName() +
(nullTest ? " for null values" : "") + "...");
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
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();
NamedMXBeans namedMXBeans = new NamedMXBeans(mbsc);
InvocationHandler ih =
nullTest ? new MXBeanNullImplInvocationHandler(c, namedMXBeans) :
new MXBeanImplInvocationHandler(c, namedMXBeans);
T impl = c.cast(Proxy.newProxyInstance(c.getClassLoader(),
new Class[] {c},
ih));
ObjectName on = new ObjectName("test:type=" + c.getName());
mbs.registerMBean(impl, on);
System.out.println("Register any MXBeans...");
Field[] fields = c.getFields();
for (Field field : fields) {
String n = field.getName();
if (n.endsWith("ObjectName")) {
String objectNameString = (String) field.get(null);
String base = n.substring(0, n.length() - 10);
Field f = c.getField(base);
Object mxbean = f.get(null);
ObjectName objectName =
ObjectName.getInstance(objectNameString);
mbs.registerMBean(mxbean, objectName);
namedMXBeans.put(objectName, mxbean);
}
}
try {
testInterface(c, mbsc, on, namedMXBeans, nullTest);
} finally {
try {
cc.close();
} finally {
cs.stop();
}
}
}
private static void test(String proto) throws Exception {
System.out.println("\n>>> Test for protocol " + proto);
JMXServiceURL url = new JMXServiceURL(proto, null, 0);
System.out.println(">>> Create a server: "+url);
JMXConnectorServer server = null;
try {
server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbeanServer);
} catch (MalformedURLException e) {
System.out.println("System does not recognize URL: " + url +
"; ignoring");
return;
}
server.start();
url = server.getAddress();
System.out.println(">>> Creating a client connectint to: "+url);
JMXConnector conn = JMXConnectorFactory.connect(url, null);
MBeanServerConnection client = conn.getMBeanServerConnection();
// add listener from the client side
Listener listener = new Listener();
client.addNotificationListener(emitter, listener, null, null);
// ask to send one not serializable notif
Object[] params = new Object[] {new Integer(1)};
String[] signatures = new String[] {"java.lang.Integer"};
client.invoke(emitter, "sendNotserializableNotifs", params, signatures);
// listener clean
client.removeNotificationListener(emitter, listener);
listener = new Listener();
client.addNotificationListener(emitter, listener, null, null);
//ask to send serializable notifs
params = new Object[] {new Integer(sentNotifs)};
client.invoke(emitter, "sendNotifications", params, signatures);
// waiting ...
synchronized (listener) {
while (listener.received() < sentNotifs) {
listener.wait(); // either pass or test timeout (killed by test harness)
}
}
// clean
client.removeNotificationListener(emitter, listener);
conn.close();
server.stop();
}
public static void main(String[] args) throws Exception {
final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer server = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
server.start();
JMXConnector client = JMXConnectorFactory.connect(server.getAddress(), null);
final MBeanServerConnection mbsc = client.getMBeanServerConnection();
final ObjectName mbean = ObjectName.getInstance(":type=Simple");
mbsc.createMBean(Simple.class.getName(), mbean);
System.out.println("EmptyDomainNotificationTest-main: add a listener ...");
final Listener li = new Listener();
mbsc.addNotificationListener(mbean, li, null, null);
System.out.println("EmptyDomainNotificationTest-main: ask to send a notif ...");
mbsc.invoke(mbean, "emitNotification", null, null);
System.out.println("EmptyDomainNotificationTest-main: waiting notif...");
final long stopTime = System.currentTimeMillis() + 2000;
synchronized(li) {
long toWait = stopTime - System.currentTimeMillis();
while (li.received < 1 && toWait > 0) {
li.wait(toWait);
toWait = stopTime - System.currentTimeMillis();
}
}
if (li.received < 1) {
throw new RuntimeException("No notif received!");
} else if (li.received > 1) {
throw new RuntimeException("Wait one notif but got: "+li.received);
}
System.out.println("EmptyDomainNotificationTest-main: Got the expected notif!");
System.out.println("EmptyDomainNotificationTest-main: remove the listener.");
mbsc.removeNotificationListener(mbean, li);
// clean
client.close();
server.stop();
System.out.println("EmptyDomainNotificationTest-main: Bye.");
}
public static void main(String[] args) throws Exception {
System.out.println("---RMIConnectorInternalMapTest starting...");
JMXConnectorServer connectorServer = null;
JMXConnector connectorClient = null;
try {
MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
connectorServer.start();
JMXServiceURL serverAddr = connectorServer.getAddress();
connectorClient = JMXConnectorFactory.connect(serverAddr, null);
connectorClient.connect();
Field rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
rmbscMapField.setAccessible(true);
Map<Subject, WeakReference<MBeanServerConnection>> map =
(Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
if (map != null && !map.isEmpty()) { // failed
throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
}
Subject delegationSubject =
new Subject(true,
Collections.singleton(new JMXPrincipal("delegate")),
Collections.EMPTY_SET,
Collections.EMPTY_SET);
MBeanServerConnection mbsc1 =
connectorClient.getMBeanServerConnection(delegationSubject);
MBeanServerConnection mbsc2 =
connectorClient.getMBeanServerConnection(delegationSubject);
if (mbsc1 == null) {
throw new RuntimeException("Got null connection.");
}
if (mbsc1 != mbsc2) {
throw new RuntimeException("Not got same connection with a same subject.");
}
map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
if (map == null || map.isEmpty()) { // failed
throw new RuntimeException("RMIConnector's rmbscMap has wrong size "
+ "after creating a delegated connection.");
}
delegationSubject = null;
mbsc1 = null;
mbsc2 = null;
int i = 0;
while (!map.isEmpty() && i++ < 60) {
System.gc();
Thread.sleep(100);
}
System.out.println("---GC times: " + i);
if (!map.isEmpty()) {
throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
} else {
System.out.println("---RMIConnectorInternalMapTest: PASSED!");
}
} finally {
try {
connectorClient.close();
connectorServer.stop();
} catch (Exception e) {
}
}
}
public static void main(String[] args) throws Exception {
print("Create the MBean server");
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
print("Initialize environment map");
HashMap env = new HashMap();
print("Specify a client socket factory to control socket creation.");
env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
clientFactory);
print("Specify a server idle timeout to make a server close an idle connection.");
env.put("jmx.remote.x.server.connection.timeout", serverTimeout);
print("Disable client heartbeat.");
env.put("jmx.remote.x.client.connection.check.period", 0);
env.put("jmx.remote.x.notification.fetch.timeout", serverTimeout);
print("Create an RMI server");
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
JMXConnectorServer server =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
server.start();
url = server.getAddress();
print("Create jmx client on "+url);
StateMachine.setState(CREATE_SOCKET); // allow to create client socket
client = JMXConnectorFactory.connect(url, env);
Thread.sleep(100);
totoName = new ObjectName("default:name=toto");
mbs.registerMBean(toto, totoName);
print("Register the mbean: " + totoName);
print("Add listener to toto MBean");
client.getMBeanServerConnection().addNotificationListener(
totoName, myListener, null, null);
Thread.sleep(10);
print("send notif, listener will block the fetcher");
toto.sendNotif();
Thread.sleep(100);
StateMachine.setState(NO_OP);
print("Sleep 3 times of server idle timeout: "+serverTimeout+
", the sever should close the idle connection.");
Thread.sleep(serverTimeout*3);
print("start the user thread to call mbean method, it will get IOexception" +
" and start the reconnection, the socket factory will block the" +
" socket creation.");
UserThread ut = new UserThread();
ut.start();
Thread.sleep(10);
print("Free the listener, the fetcher will get IO and makes " +
"a deadlock if the bug is not fixed.");
StateMachine.setState(FREE_LISTENER);
Thread.sleep(100);
print("Allow to create new socket for the reconnection");
StateMachine.setState(CREATE_SOCKET);
print("Check whether the user thread gets free to call the mbean.");
if (!ut.waitDone(5000)) {
throw new RuntimeException("Possible deadlock!");
}
print("Remove the listener.");
client.getMBeanServerConnection().removeNotificationListener(
totoName, myListener, null, null);
Thread.sleep(serverTimeout*3);
print("\nWell passed, bye!");
client.close();
Thread.sleep(10);
server.stop();
}
private int jmxConnectorFactoryTests() {
int errorCount = 0;
echo("");
echo(dashedMessage("Run JMXConnectorFactory Tests"));
for (int i = 0; i < maps.length - 1; i++) {
echo("\n>>> JMXConnectorFactory Test [" + i + "]");
try {
echo("\tMap = " + maps[i]);
echo("\tCreate the MBean server");
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
echo("\tCreate the RMI connector server");
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" +
port + "/JMXConnectorFactory" + i);
JMXConnectorServer jmxcs =
JMXConnectorServerFactory.newJMXConnectorServer(url,
null,
mbs);
echo("\tStart the RMI connector server");
jmxcs.start();
echo("\tCreate and connect the RMI connector");
JMXConnector jmxc =
JMXConnectorFactory.connect(jmxcs.getAddress(), maps[i]);
echo("\tClose the RMI connector");
jmxc.close();
echo("\tTest [" + i + "] PASSED!");
} catch (Exception e) {
errorCount++;
echo("\tTest [" + i + "] FAILED!");
e.printStackTrace(System.out);
}
}
if (errorCount == 0) {
echo("");
echo(dashedMessage("JMXConnectorFactory Tests PASSED!"));
} else {
echo("");
echo(dashedMessage("JMXConnectorFactory Tests FAILED!"));
}
return errorCount;
}
public static void main(String[] args) {
try {
// Instantiate the MBean server
//
System.out.println("Create the MBean server");
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
// Initialize environment map to be passed to the connector server
//
System.out.println("Initialize environment map");
HashMap env = new HashMap();
CustomRMIExporter exporter = new CustomRMIExporter();
env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);
// Create an RMI connector server
//
System.out.println("Create an RMI connector server");
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
// Create an RMI connector client
//
System.out.println("Create an RMI connector client");
JMXConnector cc =
JMXConnectorFactory.connect(cs.getAddress(), null);
// Close RMI connector client
//
System.out.println("Close the RMI connector client");
cc.close();
// Stop RMI connector server
//
System.out.println("Stop the RMI connector server");
cs.stop();
// Check if remote objects were exported/unexported successfully
//
int errorCount = 0;
if (exporter.rmiServerExported) {
System.out.println("RMIServer exported OK!");
} else {
System.out.println("RMIServer exported KO!");
errorCount++;
}
if (exporter.rmiServerUnexported) {
System.out.println("RMIServer unexported OK!");
} else {
System.out.println("RMIServer unexported KO!");
errorCount++;
}
if (exporter.rmiConnectionExported) {
System.out.println("RMIConnection exported OK!");
} else {
System.out.println("RMIConnection exported KO!");
errorCount++;
}
if (exporter.rmiConnectionUnexported) {
System.out.println("RMIConnection unexported OK!");
} else {
System.out.println("RMIConnection unexported KO!");
errorCount++;
}
System.out.println("Bye! Bye!");
if (errorCount > 0) {
System.out.println("RMIExporterTest FAILED!");
System.exit(1);
} else {
System.out.println("RMIExporterTest PASSED!");
}
} catch (Exception e) {
System.out.println("Unexpected exception caught = " + e);
e.printStackTrace();
System.exit(1);
}
}
/**
* Run test
*/
public int runTest(boolean setBeforeStart) throws Exception {
echo("=-=-= MBSFPreStartPostStartTest: Set MBSF " +
(setBeforeStart ? "before" : "after") +
" starting the connector server =-=-=");
JMXConnectorServer server = null;
JMXConnector client = null;
// Create a new MBeanServer
//
final MBeanServer mbs = MBeanServerFactory.createMBeanServer();
try {
// Create the JMXServiceURL
//
final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
// Create a JMXConnectorServer
//
server = JMXConnectorServerFactory.newJMXConnectorServer(url,
null,
mbs);
// Create MBeanServerForwarder
//
MBeanServerForwarder mbsf =
MBSFInvocationHandler.newProxyInstance();
// Set MBeanServerForwarder before start()
//
if (setBeforeStart)
server.setMBeanServerForwarder(mbsf);
// Start the JMXConnectorServer
//
server.start();
// Set MBeanServerForwarder after start()
//
if (!setBeforeStart)
server.setMBeanServerForwarder(mbsf);
// Create a JMXConnector
//
client = server.toJMXConnector(null);
// Connect to the connector server
//
client.connect(null);
// Get non-secure MBeanServerConnection
//
final MBeanServerConnection mbsc =
client.getMBeanServerConnection();
// Run method
//
mbsc.getDefaultDomain();
// Check flag in MBeanServerForwarder
//
MBSFInvocationHandler mbsfih =
(MBSFInvocationHandler) Proxy.getInvocationHandler(mbsf);
if (mbsfih.getFlag() == true) {
echo("OK: Did go into MBeanServerForwarder!");
} else {
echo("KO: Didn't go into MBeanServerForwarder!");
return 1;
}
} catch (Exception e) {
echo("Failed to perform operation: " + e);
return 1;
} finally {
// Close the connection
//
if (client != null)
client.close();
// Stop the connector server
//
if (server != null)
server.stop();
// Release the MBeanServer
//
if (mbs != null)
MBeanServerFactory.releaseMBeanServer(mbs);
}
return 0;
}
public static void main(String[] args) throws Exception {
System.out.println("---RMIConnectorInternalMapTest starting...");
JMXConnectorServer connectorServer = null;
JMXConnector connectorClient = null;
try {
MBeanServer mserver = ManagementFactory.getPlatformMBeanServer();
JMXServiceURL serverURL = new JMXServiceURL("rmi", "localhost", 0);
connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(serverURL, null, mserver);
connectorServer.start();
JMXServiceURL serverAddr = connectorServer.getAddress();
connectorClient = JMXConnectorFactory.connect(serverAddr, null);
connectorClient.connect();
Field rmbscMapField = RMIConnector.class.getDeclaredField("rmbscMap");
rmbscMapField.setAccessible(true);
Map<Subject, WeakReference<MBeanServerConnection>> map =
(Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
if (map != null && !map.isEmpty()) { // failed
throw new RuntimeException("RMIConnector's rmbscMap must be empty at the initial time.");
}
Subject delegationSubject =
new Subject(true,
Collections.singleton(new JMXPrincipal("delegate")),
Collections.EMPTY_SET,
Collections.EMPTY_SET);
MBeanServerConnection mbsc1 =
connectorClient.getMBeanServerConnection(delegationSubject);
MBeanServerConnection mbsc2 =
connectorClient.getMBeanServerConnection(delegationSubject);
if (mbsc1 == null) {
throw new RuntimeException("Got null connection.");
}
if (mbsc1 != mbsc2) {
throw new RuntimeException("Not got same connection with a same subject.");
}
map = (Map<Subject, WeakReference<MBeanServerConnection>>) rmbscMapField.get(connectorClient);
if (map == null || map.isEmpty()) { // failed
throw new RuntimeException("RMIConnector's rmbscMap has wrong size "
+ "after creating a delegated connection.");
}
delegationSubject = null;
mbsc1 = null;
mbsc2 = null;
int i = 0;
while (!map.isEmpty() && i++ < 60) {
System.gc();
Thread.sleep(100);
}
System.out.println("---GC times: " + i);
if (!map.isEmpty()) {
throw new RuntimeException("Failed to clean RMIConnector's rmbscMap");
} else {
System.out.println("---RMIConnectorInternalMapTest: PASSED!");
}
} finally {
try {
connectorClient.close();
connectorServer.stop();
} catch (Exception e) {
}
}
}