下面列出了怎么用javax.management.remote.JMXServiceURL的API类实例代码及写法,或者点击链接到github查看源代码。
private JMXServiceURL createServerSide(Map<String, Object> serverMap)
throws Exception {
final int NINETY_SECONDS = 90;
System.out.println("SecurityTest::createServerSide: Start") ;
// Prepare server side security env
HashMap<String, Object> env = setServerSecurityEnv(serverMap);
// Create and start mbean server and connector server
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
// Waits availibility of connector server
Utils.waitReady(cs, NINETY_SECONDS);
JMXServiceURL addr = cs.getAddress();
System.out.println("SecurityTest::createServerSide: Done.") ;
return addr;
}
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());
}
private RMIServer findRMIServer(JMXServiceURL directoryURL,
Map<String, Object> environment)
throws NamingException, IOException {
final boolean isIiop = RMIConnectorServer.isIiopURL(directoryURL,true);
if (isIiop) {
// Make sure java.naming.corba.orb is in the Map.
environment.put(EnvHelp.DEFAULT_ORB,resolveOrb(environment));
}
String path = directoryURL.getURLPath();
int end = path.indexOf(';');
if (end < 0) end = path.length();
if (path.startsWith("/jndi/"))
return findRMIServerJNDI(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/stub/"))
return findRMIServerJRMP(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/ior/")) {
if (!IIOPHelper.isAvailable())
throw new IOException("iiop protocol not available");
return findRMIServerIIOP(path.substring(5,end), environment, isIiop);
} else {
final String msg = "URL path must begin with /jndi/ or /stub/ " +
"or /ior/: " + path;
throw new MalformedURLException(msg);
}
}
/**
* Jmx connection.
*
* @param nodeIp
* the node ip
* @param jmxPort
* the jmx port
* @return the jMX connector
* @throws Exception
*/
private JMXConnector jmxConnection(String nodeIp, int jmxPort) {
JMXConnector connector = null;
try {
JMXServiceURL address = new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://" + nodeIp + ":" + jmxPort
+ "/jmxrmi");
connector = JMXConnectorFactory.connect(address);
} catch (Exception e) {
if (e.getMessage().contains("java.net.ConnectException")) {
logger.info("Host unavailable at Node..." + nodeIp);
logger.error(e.getMessage());
// throw new AnkushException("Host unavailable-" + nodeIp);
}
}
return connector;
}
private RMIServer findRMIServer(JMXServiceURL directoryURL,
Map<String, Object> environment)
throws NamingException, IOException {
final boolean isIiop = RMIConnectorServer.isIiopURL(directoryURL,true);
if (isIiop) {
// Make sure java.naming.corba.orb is in the Map.
environment.put(EnvHelp.DEFAULT_ORB,resolveOrb(environment));
}
String path = directoryURL.getURLPath();
int end = path.indexOf(';');
if (end < 0) end = path.length();
if (path.startsWith("/jndi/"))
return findRMIServerJNDI(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/stub/"))
return findRMIServerJRMP(path.substring(6,end), environment, isIiop);
else if (path.startsWith("/ior/")) {
if (!IIOPHelper.isAvailable())
throw new IOException("iiop protocol not available");
return findRMIServerIIOP(path.substring(5,end), environment, isIiop);
} else {
final String msg = "URL path must begin with /jndi/ or /stub/ " +
"or /ior/: " + path;
throw new MalformedURLException(msg);
}
}
/** optionally starts a normal JMXRMI connector in addition */
public JMXConnectorServer startNormalJmxRmiConnectorIfRequested(Properties properties) {
try {
String rmiPortS = properties.getProperty(RMI_REGISTRY_PORT_PROPERTY);
if (rmiPortS==null || rmiPortS.length()==0)
return null;
int rmiPort = Integer.parseInt(rmiPortS);
LocateRegistry.createRegistry(rmiPort);
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
String svc =
"service:jmx:rmi:///jndi/rmi://localhost:"+rmiPort+"/jmxrmi";
JMXServiceURL url = new JMXServiceURL(svc);
RMIConnectorServer rmiServer = new RMIConnectorServer(url, null, mbeanServer);
rmiServer.start();
return rmiServer;
} catch (Exception e) {
System.err.println("Unable to start JmxmpAgent: "+e);
throw new RuntimeException(e);
}
}
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 Map<String, Long> fetch(String pid) {
if (pid == null) {
return Collections.emptyMap();
}
try {
VirtualMachine vm = VirtualMachine.attach(pid);
vm.startLocalManagementAgent();
String connectorAddress = vm.getAgentProperties()
.getProperty(CONNECTOR_ADDRESS);
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector connector = JMXConnectorFactory.connect(url);
MBeanServerConnection connection = connector.getMBeanServerConnection();
gc(connection);
Map<String, Long> metrics = new HashMap<>(
new BufferPools(connection).getMetrics());
metrics.putAll(new Threads(connection).getMetrics());
metrics.putAll(new Classes(connection).getMetrics());
vm.detach();
return metrics;
}
catch (Exception e) {
return Collections.emptyMap();
}
}
private JMXConnectorServer startServer(int rmiPort) throws Exception {
System.out.println("DEBUG: Create RMI registry on port " + rmiPort);
LocateRegistry.createRegistry(rmiPort);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
HashMap<String,Object> env = new HashMap<String,Object>();
JMXServiceURL url =
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + rmiPort + "/jmxrmi");
JMXConnectorServer cs =
JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
cs.start();
System.out.println("DEBUG: Started the RMI connector server");
return cs;
}
private static void connect(String pid, String address) throws Exception {
if (address == null) {
throw new RuntimeException("Local connector address for " +
pid + " is null");
}
System.out.println("Connect to process " + pid + " via: " + address);
JMXServiceURL url = new JMXServiceURL(address);
JMXConnector c = JMXConnectorFactory.connect(url);
MBeanServerConnection server = c.getMBeanServerConnection();
System.out.println("Connected.");
RuntimeMXBean rt = newPlatformMXBeanProxy(server,
RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
System.out.println(rt.getName());
// close the connection
c.close();
}
private void jmxAuthInvalidCreds(JMXServiceURL jmxRmiServiceURL) {
RMTHelper.log("Test invalid JMX auth without creds (expect SecurityException)");
try {
JMXConnectorFactory.connect(jmxRmiServiceURL, new HashMap<String, Object>(0));
} catch (Exception e) {
assertTrue("JMX auth must throw SecurityException if a client tries to connect without creds in the " +
"env", e instanceof SecurityException);
}
}
/**
* Connect to the profiler on the attached VM.
*
* @throws MalformedURLException
*/
private void connectToProfiler() throws IOException {
Properties props = this.vm.getAgentProperties();
String connectorAddress = props.getProperty(JCozClient.CONNECTOR_ADDR_PROPERTY);
JMXServiceURL url = new JMXServiceURL(connectorAddress);
this.connector = JMXConnectorFactory.connect(url);
MBeanServerConnection mbeanConn = this.connector.getMBeanServerConnection();
this.mxbeanProxy = JMX.newMXBeanProxy(mbeanConn,
JCozProfiler.getMBeanName(), JCozProfilerMBean.class);
}
private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
this.jmxServiceURL = address;
if (environment == null) {
this.env = Collections.emptyMap();
} else {
EnvHelp.checkAttributes(environment);
this.env = Collections.unmodifiableMap(environment);
}
}
private JMXConnector connectToServer(JMXConnectorServer server) throws IOException, MalformedObjectNameException, NullPointerException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, ReflectionException, MBeanException {
JMXServiceURL url = server.getAddress();
Map<String, Object> env = new HashMap<String, Object>();
JMXConnector connector = JMXConnectorFactory.connect(url, env);
System.out.println("DEBUG: Client connected to RMI at: " + url);
return connector;
}
/**
* Connects to the JMX agent in the local process.
*
* @throws ConnectionFailedException if there was a failure to connect to the local JMX connector in the process
* @throws IOException if the JDK management agent cannot be found and loaded
*/
void connect() throws ConnectionFailedException, IOException {
try {
final JMXServiceURL jmxUrl = getJMXServiceURL();
this.jmxc = JMXConnectorFactory.connect(jmxUrl);
this.server = this.jmxc.getMBeanServerConnection();
} catch (AttachNotSupportedException e) {
throw new ConnectionFailedException("Failed to connect to process '" + this.pid + "'", e);
}
}
public static void main(String[] args) throws Exception
{
prepareUsersFile();
// The address of the connector server
JMXServiceURL url = new JMXServiceURL("rmi", "localhost", 0, "/jndi/jmx");
// Specify the authenticator in the environment Map, using the
// standard property JMXConnector.AUTHENTICATOR
Map environment = new HashMap();
JMXAuthenticator authenticator = new PasswordAuthenticator(new File(PASSWORD_FILE));
environment.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
// Create and register the connector server
JMXConnectorServer cntorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, null);
ObjectName cntorServerName = ObjectName.getInstance(":service=" + JMXConnectorServer.class.getName() + ",protocol=" + url.getProtocol());
MBeanServer server = MBeanServerFactory.createMBeanServer("remote.security.example");
server.registerMBean(cntorServer, cntorServerName);
// Setup the rmiregistry to bind in JNDI the RMIConnectorServer stub.
NamingService naming = new NamingService();
ObjectName namingName = ObjectName.getInstance(":service=" + NamingService.class.getName());
server.registerMBean(naming, namingName);
naming.start();
// Setup the interception
SubjectTrackingMBeanServer interceptor = new SubjectTrackingMBeanServer();
cntorServer.setMBeanServerForwarder(interceptor);
// Start the connector server
cntorServer.start();
System.out.println("Server up and running");
}
/**
* Connects to a child JVM process
*
* @param p the process to which to connect
* @param startAgent whether to installed the JMX agent in the target process if not already in place
* @return an {@link MBeanServerConnection} to the process's MBean server
*/
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) {
try {
final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent);
final JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
final MBeanServerConnection mbsc = connector.getMBeanServerConnection();
return mbsc;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
if (!serviceURL.getProtocol().equals("iiop")) {
throw new MalformedURLException("Protocol not iiop: " +
serviceURL.getProtocol());
}
return new RMIConnectorServer(serviceURL, environment, mbeanServer);
}
private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
this.jmxServiceURL = address;
if (environment == null) {
this.env = Collections.emptyMap();
} else {
EnvHelp.checkAttributes(environment);
this.env = Collections.unmodifiableMap(environment);
}
}
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
if (!serviceURL.getProtocol().equals("rmi")) {
throw new MalformedURLException("Protocol not rmi: " +
serviceURL.getProtocol());
}
return new RMIConnectorServer(serviceURL, environment, mbeanServer);
}
private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
this.jmxServiceURL = address;
if (environment == null) {
this.env = Collections.emptyMap();
} else {
EnvHelp.checkAttributes(environment);
this.env = Collections.unmodifiableMap(environment);
}
}
public JMXConnector newJMXConnector(JMXServiceURL url,
Map<String,?> map)
throws IOException {
final String protocol = url.getProtocol();
called = true;
System.out.println("JMXConnectorProviderImpl called");
if(protocol.equals("rmi"))
return new RMIConnector(url, map);
if(protocol.equals("throw-provider-exception"))
throw new JMXProviderException("I have been asked to throw");
throw new IllegalArgumentException("UNKNOWN PROTOCOL");
}
private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
this.jmxServiceURL = address;
if (environment == null) {
this.env = Collections.emptyMap();
} else {
EnvHelp.checkAttributes(environment);
this.env = Collections.unmodifiableMap(environment);
}
}
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
if (!serviceURL.getProtocol().equals("rmi")) {
throw new MalformedURLException("Protocol not rmi: " +
serviceURL.getProtocol());
}
return new RMIConnectorServer(serviceURL, environment, mbeanServer);
}
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
if (!serviceURL.getProtocol().equals("rmi")) {
throw new MalformedURLException("Protocol not rmi: " +
serviceURL.getProtocol());
}
return new RMIConnectorServer(serviceURL, environment, mbeanServer);
}
public static String start() throws Exception {
int serverPort = 12345;
ObjectName name = new ObjectName("test", "foo", "bar");
MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
SteMBean bean = new Ste();
jmxServer.registerMBean(bean, name);
boolean exported = false;
Random rnd = new Random(System.currentTimeMillis());
do {
try {
LocateRegistry.createRegistry(serverPort);
exported = true;
} catch (ExportException ee) {
if (ee.getCause() instanceof BindException) {
serverPort = rnd.nextInt(10000) + 4096;
} else {
throw ee;
}
}
} while (!exported);
JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
jmxConnector.start();
return serverUrl.toString();
}
public JMXConnector newJMXConnector(JMXServiceURL serviceURL,
Map<String,?> environment)
throws IOException {
if (!serviceURL.getProtocol().equals("iiop")) {
throw new MalformedURLException("Protocol not iiop: " +
serviceURL.getProtocol());
}
return new RMIConnector(serviceURL, environment);
}
public void run(Map<String, Object> serverArgs, String clientArgs[]) {
System.out.println("SecurityTest::run: Start") ;
int errorCount = 0;
try {
// Initialise the server side
JMXServiceURL urlToUse = createServerSide(serverArgs);
// Run client side
errorCount = runClientSide(clientArgs, urlToUse.toString());
if ( errorCount == 0 ) {
System.out.println("SecurityTest::run: Done without any error") ;
} else {
System.out.println(
"SecurityTest::run: Done with " + errorCount + " error(s)");
throw new RuntimeException("errorCount = " + errorCount);
}
cs.stop();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public JMXConnectorServer newJMXConnectorServer(JMXServiceURL serviceURL,
Map<String,?> environment,
MBeanServer mbeanServer)
throws IOException {
if (!serviceURL.getProtocol().equals("iiop")) {
throw new MalformedURLException("Protocol not iiop: " +
serviceURL.getProtocol());
}
return new RMIConnectorServer(serviceURL, environment, mbeanServer);
}
public static String start() throws Exception {
int serverPort = 12345;
ObjectName name = new ObjectName("test", "foo", "bar");
MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
SteMBean bean = new Ste();
jmxServer.registerMBean(bean, name);
boolean exported = false;
Random rnd = new Random(System.currentTimeMillis());
do {
try {
LocateRegistry.createRegistry(serverPort);
exported = true;
} catch (ExportException ee) {
if (ee.getCause() instanceof BindException) {
serverPort = rnd.nextInt(10000) + 4096;
} else {
throw ee;
}
}
} while (!exported);
JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
jmxConnector.start();
return serverUrl.toString();
}