1. /*
  2. * @(#)JMXConnectorFactory.java 1.42 04/05/05
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.management.remote;
  8. import java.io.IOException;
  9. import java.net.MalformedURLException;
  10. import java.util.Collections;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. import java.util.Iterator;
  14. import java.util.StringTokenizer;
  15. import java.security.AccessController;
  16. import java.security.PrivilegedAction;
  17. import com.sun.jmx.remote.util.ClassLogger;
  18. import com.sun.jmx.remote.util.EnvHelp;
  19. import com.sun.jmx.remote.util.Service;
  20. /**
  21. * <p>Factory to create JMX API connector clients. There
  22. * are no instances of this class.</p>
  23. *
  24. * <p>Connections are usually made using the {@link
  25. * #connect(JMXServiceURL) connect} method of this class. More
  26. * advanced applications can separate the creation of the connector
  27. * client, using {@link #newJMXConnector(JMXServiceURL, Map)
  28. * newJMXConnector} and the establishment of the connection itself, using
  29. * {@link JMXConnector#connect(Map)}.</p>
  30. *
  31. * <p>Each client is created by an instance of {@link
  32. * JMXConnectorProvider}. This instance is found as follows. Suppose
  33. * the given {@link JMXServiceURL} looks like
  34. * <code>"service:jmx:<em>protocol</em>:<em>remainder</em>"</code>.
  35. * Then the factory will attempt to find the appropriate {@link
  36. * JMXConnectorProvider} for <code><em>protocol</em></code>. Each
  37. * occurrence of the character <code>+</code> or <code>-</code> in
  38. * <code><em>protocol</em></code> is replaced by <code>.</code> or
  39. * <code>_</code>, respectively.</p>
  40. *
  41. * <p>A <em>provider package list</em> is searched for as follows:</p>
  42. *
  43. * <ol>
  44. *
  45. * <li>If the <code>environment</code> parameter to {@link
  46. * #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
  47. * key <code>jmx.remote.protocol.provider.pkgs</code> then the
  48. * associated value is the provider package list.
  49. *
  50. * <li>Otherwise, if the system property
  51. * <code>jmx.remote.protocol.provider.pkgs</code> exists, then its value
  52. * is the provider package list.
  53. *
  54. * <li>Otherwise, there is no provider package list.
  55. *
  56. * </ol>
  57. *
  58. * <p>The provider package list is a string that is interpreted as a
  59. * list of non-empty Java package names separated by vertical bars
  60. * (<code>|</code>). If the string is empty, then so is the provider
  61. * package list. If the provider package list is not a String, or if
  62. * it contains an element that is an empty string, a {@link
  63. * JMXProviderException} is thrown.</p>
  64. *
  65. * <p>If the provider package list exists and is not empty, then for
  66. * each element <code><em>pkg</em></code> of the list, the factory
  67. * will attempt to load the class
  68. *
  69. * <blockquote>
  70. * <code><em>pkg</em>.<em>protocol</em>.ClientProvider</code>
  71. * </blockquote>
  72. * <p>If the <code>environment</code> parameter to {@link
  73. * #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
  74. * key <code>jmx.remote.protocol.provider.class.loader</code> then the
  75. * associated value is the class loader to use to load the provider.
  76. * If the associated value is not an instance of {@link
  77. * java.lang.ClassLoader}, an {@link
  78. * java.lang.IllegalArgumentException} is thrown.</p>
  79. *
  80. * <p>If the <code>jmx.remote.protocol.provider.class.loader</code>
  81. * key is not present in the <code>environment</code> parameter, the
  82. * calling thread's context class loader is used.</p>
  83. *
  84. * <p>If the attempt to load this class produces a {@link
  85. * ClassNotFoundException}, the search for a handler continues with
  86. * the next element of the list.</p>
  87. *
  88. * <p>Otherwise, a problem with the provider found is signalled by a
  89. * {@link JMXProviderException} whose {@link
  90. * JMXProviderException#getCause() <em>cause</em>} indicates the underlying
  91. * exception, as follows:</p>
  92. *
  93. * <ul>
  94. *
  95. * <li>if the attempt to load the class produces an exception other
  96. * than <code>ClassNotFoundException</code>, that is the
  97. * <em>cause</em>
  98. *
  99. * <li>if {@link Class#newInstance()} for the class produces an
  100. * exception, that is the <em>cause</em>.
  101. *
  102. * </ul>
  103. *
  104. * <p>If no provider is found by the above steps, including the
  105. * default case where there is no provider package list, then the
  106. * implementation will use its own provider for
  107. * <code><em>protocol</em></code>, or it will throw a
  108. * <code>MalformedURLException</code> if there is none. An
  109. * implementation may choose to find providers by other means. For
  110. * example, it may support the <a
  111. * href="http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Service Provider">
  112. * JAR conventions for service providers</a>, where the service
  113. * interface is <code>JMXConnectorProvider</code>.</p>
  114. *
  115. * <p>Every implementation must support the RMI connector protocols,
  116. * specified with the string <code>rmi</code> or
  117. * <code>iiop</code>.</p>
  118. *
  119. * <p>Once a provider is found, the result of the
  120. * <code>newJMXConnector</code> method is the result of calling {@link
  121. * JMXConnectorProvider#newJMXConnector(JMXServiceURL,Map) newJMXConnector}
  122. * on the provider.</p>
  123. *
  124. * <p>The <code>Map</code> parameter passed to the
  125. * <code>JMXConnectorProvider</code> is a new read-only
  126. * <code>Map</code> that contains all the entries that were in the
  127. * <code>environment</code> parameter to {@link
  128. * #newJMXConnector(JMXServiceURL,Map)
  129. * JMXConnectorFactory.newJMXConnector}, if there was one.
  130. * Additionally, if the
  131. * <code>jmx.remote.protocol.provider.class.loader</code> key is not
  132. * present in the <code>environment</code> parameter, it is added to
  133. * the new read-only <code>Map</code>. The associated value is the
  134. * calling thread's context class loader.</p>
  135. *
  136. * @since 1.5
  137. * @since.unbundled 1.0
  138. */
  139. public class JMXConnectorFactory {
  140. /**
  141. * <p>Name of the attribute that specifies the default class
  142. * loader. This class loader is used to deserialize return values and
  143. * exceptions from remote <code>MBeanServerConnection</code>
  144. * calls. The value associated with this attribute is an instance
  145. * of {@link ClassLoader}.</p>
  146. */
  147. public static final String DEFAULT_CLASS_LOADER =
  148. "jmx.remote.default.class.loader";
  149. /**
  150. * <p>Name of the attribute that specifies the provider packages
  151. * that are consulted when looking for the handler for a protocol.
  152. * The value associated with this attribute is a string with
  153. * package names separated by vertical bars (<code>|</code>).</p>
  154. */
  155. public static final String PROTOCOL_PROVIDER_PACKAGES =
  156. "jmx.remote.protocol.provider.pkgs";
  157. /**
  158. * <p>Name of the attribute that specifies the class
  159. * loader for loading protocol providers.
  160. * The value associated with this attribute is an instance
  161. * of {@link ClassLoader}.</p>
  162. */
  163. public static final String PROTOCOL_PROVIDER_CLASS_LOADER =
  164. "jmx.remote.protocol.provider.class.loader";
  165. private static final String PROTOCOL_PROVIDER_DEFAULT_PACKAGE =
  166. "com.sun.jmx.remote.protocol";
  167. private static final ClassLogger logger =
  168. new ClassLogger("javax.management.remote.misc", "JMXConnectorFactory");
  169. /** There are no instances of this class. */
  170. private JMXConnectorFactory() {
  171. }
  172. /**
  173. * <p>Creates a connection to the connector server at the given
  174. * address.</p>
  175. *
  176. * <p>This method is equivalent to {@link
  177. * #connect(JMXServiceURL,Map) connect(serviceURL, null)}.</p>
  178. *
  179. * @param serviceURL the address of the connector server to
  180. * connect to.
  181. *
  182. * @return a <code>JMXConnector</code> whose {@link
  183. * JMXConnector#connect connect} method has been called.
  184. *
  185. * @exception NullPointerException if <code>serviceURL</code> is null.
  186. *
  187. * @exception IOException if the connector client or the
  188. * connection cannot be made because of a communication problem.
  189. *
  190. * @exception SecurityException if the connection cannot be made
  191. * for security reasons.
  192. */
  193. public static JMXConnector connect(JMXServiceURL serviceURL)
  194. throws IOException {
  195. return connect(serviceURL, null);
  196. }
  197. /**
  198. * <p>Creates a connection to the connector server at the given
  199. * address.</p>
  200. *
  201. * <p>This method is equivalent to:</p>
  202. *
  203. * <pre>
  204. * JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL,
  205. * environment);
  206. * conn.connect(environment);
  207. * </pre>
  208. *
  209. * @param serviceURL the address of the connector server to connect to.
  210. *
  211. * @param environment a set of attributes to determine how the
  212. * connection is made. This parameter can be null. Keys in this
  213. * map must be Strings. The appropriate type of each associated
  214. * value depends on the attribute. The contents of
  215. * <code>environment</code> are not changed by this call.
  216. *
  217. * @return a <code>JMXConnector</code> representing the newly-made
  218. * connection. Each successful call to this method produces a
  219. * different object.
  220. *
  221. * @exception NullPointerException if <code>serviceURL</code> is null.
  222. *
  223. * @exception IOException if the connector client or the
  224. * connection cannot be made because of a communication problem.
  225. *
  226. * @exception SecurityException if the connection cannot be made
  227. * for security reasons.
  228. */
  229. public static JMXConnector connect(JMXServiceURL serviceURL,
  230. Map<String,?> environment)
  231. throws IOException {
  232. if (serviceURL == null)
  233. throw new NullPointerException("Null JMXServiceURL");
  234. JMXConnector conn = newJMXConnector(serviceURL, environment);
  235. conn.connect(environment);
  236. return conn;
  237. }
  238. /**
  239. * <p>Creates a connector client for the connector server at the
  240. * given address. The resultant client is not connected until its
  241. * {@link JMXConnector#connect(Map) connect} method is called.</p>
  242. *
  243. * @param serviceURL the address of the connector server to connect to.
  244. *
  245. * @param environment a set of attributes to determine how the
  246. * connection is made. This parameter can be null. Keys in this
  247. * map must be Strings. The appropriate type of each associated
  248. * value depends on the attribute. The contents of
  249. * <code>environment</code> are not changed by this call.
  250. *
  251. * @return a <code>JMXConnector</code> representing the new
  252. * connector client. Each successful call to this method produces
  253. * a different object.
  254. *
  255. * @exception NullPointerException if <code>serviceURL</code> is null.
  256. *
  257. * @exception IOException if the connector client cannot be made
  258. * because of a communication problem.
  259. *
  260. * @exception MalformedURLException if there is no provider for the
  261. * protocol in <code>serviceURL</code>.
  262. *
  263. * @exception JMXProviderException if there is a provider for the
  264. * protocol in <code>serviceURL</code> but it cannot be used for
  265. * some reason.
  266. */
  267. public static JMXConnector newJMXConnector(JMXServiceURL serviceURL,
  268. Map<String,?> environment)
  269. throws IOException {
  270. if (environment == null)
  271. environment = new HashMap();
  272. else {
  273. EnvHelp.checkAttributes(environment);
  274. environment = new HashMap(environment);
  275. }
  276. final ClassLoader loader = resolveClassLoader(environment);
  277. final Class targetInterface = JMXConnectorProvider.class;
  278. final String protocol = serviceURL.getProtocol();
  279. final String providerClassName = "ClientProvider";
  280. JMXConnectorProvider provider =
  281. (JMXConnectorProvider) getProvider(serviceURL, environment,
  282. providerClassName,
  283. targetInterface,
  284. loader);
  285. if(provider == null) {
  286. // Loader is null when context class loader is set to null
  287. // and no loader has been provided in map.
  288. // com.sun.jmx.remote.util.Service class extracted from j2se
  289. // provider search algorithm doesn't handle well null classloader.
  290. if(loader != null) {
  291. JMXConnector connection = getConnectorAsService(loader,
  292. serviceURL,
  293. environment);
  294. if(connection != null)
  295. return connection;
  296. }
  297. provider = (JMXConnectorProvider)
  298. getProvider(protocol, PROTOCOL_PROVIDER_DEFAULT_PACKAGE,
  299. JMXConnectorFactory.class.getClassLoader(),
  300. providerClassName, targetInterface);
  301. }
  302. if(provider == null)
  303. throw new MalformedURLException("Unsupported protocol: " +
  304. protocol);
  305. environment = Collections.unmodifiableMap(environment);
  306. return provider.newJMXConnector(serviceURL, environment);
  307. }
  308. private static String resolvePkgs(Map env) throws JMXProviderException {
  309. Object pkgsObject = null;
  310. if (env != null)
  311. pkgsObject = env.get(PROTOCOL_PROVIDER_PACKAGES);
  312. if (pkgsObject == null)
  313. pkgsObject =
  314. AccessController.doPrivileged(new PrivilegedAction() {
  315. public Object run() {
  316. return System.getProperty(PROTOCOL_PROVIDER_PACKAGES);
  317. }
  318. });
  319. if (pkgsObject == null)
  320. return null;
  321. if (!(pkgsObject instanceof String)) {
  322. final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
  323. " parameter is not a String: " +
  324. pkgsObject.getClass().getName();
  325. throw new JMXProviderException(msg);
  326. }
  327. final String pkgs = (String) pkgsObject;
  328. if (pkgs.trim().equals(""))
  329. return null;
  330. // pkgs may not contain an empty element
  331. if (pkgs.startsWith("|") || pkgs.endsWith("|") ||
  332. pkgs.indexOf("||") >= 0) {
  333. final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
  334. " contains an empty element: " + pkgs;
  335. throw new JMXProviderException(msg);
  336. }
  337. return pkgs;
  338. }
  339. static Object getProvider(JMXServiceURL serviceURL,
  340. Map environment, String providerClassName,
  341. Class targetInterface,
  342. ClassLoader loader)
  343. throws IOException {
  344. final String protocol = serviceURL.getProtocol();
  345. final String pkgs = resolvePkgs(environment);
  346. Object instance = null;
  347. if (pkgs != null) {
  348. environment.put(PROTOCOL_PROVIDER_CLASS_LOADER, loader);
  349. instance =
  350. getProvider(protocol, pkgs, loader, providerClassName,
  351. targetInterface);
  352. }
  353. return instance;
  354. }
  355. static Iterator getProviderIterator(final Class providerClass,
  356. final ClassLoader loader) {
  357. PrivilegedAction action = new PrivilegedAction() {
  358. public Object run() {
  359. return Service.providers(providerClass, loader);
  360. }
  361. };
  362. return (Iterator) AccessController.doPrivileged(action);
  363. }
  364. private static JMXConnector getConnectorAsService(ClassLoader loader,
  365. JMXServiceURL url,
  366. Map map)
  367. throws IllegalArgumentException, JMXProviderException {
  368. Iterator providers = getProviderIterator(JMXConnectorProvider.class,
  369. loader);
  370. JMXConnectorProvider provider = null;
  371. JMXConnector connection = null;
  372. while(providers.hasNext()) {
  373. provider =
  374. (JMXConnectorProvider) providers.next();
  375. try {
  376. connection = provider.newJMXConnector(url, map);
  377. return connection;
  378. } catch (JMXProviderException e) {
  379. throw e;
  380. }
  381. catch (Exception e) {
  382. if (logger.traceOn())
  383. logger.trace("getConnectorAsService",
  384. "URL[" + url +
  385. "] Service provider exception: " + e);
  386. continue;
  387. }
  388. }
  389. return null;
  390. }
  391. static Object getProvider(String protocol,
  392. String pkgs,
  393. ClassLoader loader,
  394. String providerClassName,
  395. Class targetInterface)
  396. throws IOException {
  397. StringTokenizer tokenizer = new StringTokenizer(pkgs, "|");
  398. while (tokenizer.hasMoreTokens()) {
  399. String pkg = tokenizer.nextToken();
  400. String className = (pkg + "." + protocol2package(protocol) +
  401. "." + providerClassName);
  402. Class providerClass;
  403. try {
  404. providerClass = Class.forName(className, true, loader);
  405. } catch (ClassNotFoundException e) {
  406. //Add trace.
  407. continue;
  408. }
  409. if (!targetInterface.isAssignableFrom(providerClass)) {
  410. final String msg =
  411. "Provider class does not implement " +
  412. targetInterface.getName() + ": " +
  413. providerClass.getName();
  414. throw new JMXProviderException(msg);
  415. }
  416. try {
  417. return providerClass.newInstance();
  418. } catch (Exception e) {
  419. final String msg =
  420. "Exception when instantiating provider [" + className +
  421. "]";
  422. throw new JMXProviderException(msg, e);
  423. }
  424. }
  425. return null;
  426. }
  427. static ClassLoader resolveClassLoader(Map environment) {
  428. ClassLoader loader = null;
  429. if (environment != null) {
  430. try {
  431. loader = (ClassLoader)
  432. environment.get(PROTOCOL_PROVIDER_CLASS_LOADER);
  433. } catch (ClassCastException e) {
  434. final String msg =
  435. "The ClassLoader supplied in the environment map using " +
  436. "the " + PROTOCOL_PROVIDER_CLASS_LOADER +
  437. " attribute is not an instance of java.lang.ClassLoader";
  438. throw new IllegalArgumentException(msg);
  439. }
  440. }
  441. if (loader == null)
  442. loader = (ClassLoader)
  443. AccessController.doPrivileged(new PrivilegedAction() {
  444. public Object run() {
  445. return
  446. Thread.currentThread().getContextClassLoader();
  447. }
  448. });
  449. return loader;
  450. }
  451. private static String protocol2package(String protocol) {
  452. return protocol.replace('+', '.').replace('-', '_');
  453. }
  454. }