JMXConnectorFactory.java revision 16603:db6e995edd0a
1/*
2 * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package javax.management.remote;
27
28import com.sun.jmx.mbeanserver.Util;
29import java.io.IOException;
30import java.io.UncheckedIOException;
31import java.lang.reflect.Module;
32import java.net.MalformedURLException;
33import java.util.Collections;
34import java.util.HashMap;
35import java.util.Map;
36import java.util.ServiceLoader;
37import java.util.ServiceLoader.Provider;
38import java.util.StringTokenizer;
39import java.util.function.Predicate;
40import java.util.stream.Stream;
41import java.security.AccessController;
42import java.security.PrivilegedAction;
43
44import com.sun.jmx.remote.util.ClassLogger;
45import com.sun.jmx.remote.util.EnvHelp;
46import sun.reflect.misc.ReflectUtil;
47
48
49/**
50 * <p>Factory to create JMX API connector clients.  There
51 * are no instances of this class.</p>
52 *
53 * <p>Connections are usually made using the {@link
54 * #connect(JMXServiceURL) connect} method of this class.  More
55 * advanced applications can separate the creation of the connector
56 * client, using {@link #newJMXConnector(JMXServiceURL, Map)
57 * newJMXConnector} and the establishment of the connection itself, using
58 * {@link JMXConnector#connect(Map)}.</p>
59 *
60 * <p>Each client is created by an instance of {@link
61 * JMXConnectorProvider}.  This instance is found as follows.  Suppose
62 * the given {@link JMXServiceURL} looks like
63 * <code>"service:jmx:<em>protocol</em>:<em>remainder</em>"</code>.
64 * Then the factory will attempt to find the appropriate {@link
65 * JMXConnectorProvider} for <code><em>protocol</em></code>.  Each
66 * occurrence of the character <code>+</code> or <code>-</code> in
67 * <code><em>protocol</em></code> is replaced by <code>.</code> or
68 * <code>_</code>, respectively.</p>
69 *
70 * <p>A <em>provider package list</em> is searched for as follows:</p>
71 *
72 * <ol>
73 *
74 * <li>If the <code>environment</code> parameter to {@link
75 * #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
76 * key <code>jmx.remote.protocol.provider.pkgs</code> then the
77 * associated value is the provider package list.
78 *
79 * <li>Otherwise, if the system property
80 * <code>jmx.remote.protocol.provider.pkgs</code> exists, then its value
81 * is the provider package list.
82 *
83 * <li>Otherwise, there is no provider package list.
84 *
85 * </ol>
86 *
87 * <p>The provider package list is a string that is interpreted as a
88 * list of non-empty Java package names separated by vertical bars
89 * (<code>|</code>).  If the string is empty, then so is the provider
90 * package list.  If the provider package list is not a String, or if
91 * it contains an element that is an empty string, a {@link
92 * JMXProviderException} is thrown.</p>
93 *
94 * <p>If the provider package list exists and is not empty, then for
95 * each element <code><em>pkg</em></code> of the list, the factory
96 * will attempt to load the class
97 *
98 * <blockquote>
99 * <code><em>pkg</em>.<em>protocol</em>.ClientProvider</code>
100 * </blockquote>
101
102 * <p>If the <code>environment</code> parameter to {@link
103 * #newJMXConnector(JMXServiceURL, Map) newJMXConnector} contains the
104 * key <code>jmx.remote.protocol.provider.class.loader</code> then the
105 * associated value is the class loader to use to load the provider.
106 * If the associated value is not an instance of {@link
107 * java.lang.ClassLoader}, an {@link
108 * java.lang.IllegalArgumentException} is thrown.</p>
109 *
110 * <p>If the <code>jmx.remote.protocol.provider.class.loader</code>
111 * key is not present in the <code>environment</code> parameter, the
112 * calling thread's context class loader is used.</p>
113 *
114 * <p>If the attempt to load this class produces a {@link
115 * ClassNotFoundException}, the search for a handler continues with
116 * the next element of the list.</p>
117 *
118 * <p>Otherwise, a problem with the provider found is signalled by a
119 * {@link JMXProviderException} whose {@link
120 * JMXProviderException#getCause() <em>cause</em>} indicates the underlying
121 * exception, as follows:</p>
122 *
123 * <ul>
124 *
125 * <li>if the attempt to load the class produces an exception other
126 * than <code>ClassNotFoundException</code>, that is the
127 * <em>cause</em>;
128 *
129 * <li>if {@link Class#newInstance()} for the class produces an
130 * exception, that is the <em>cause</em>.
131 *
132 * </ul>
133 *
134 * <p>If no provider is found by the above steps, including the
135 * default case where there is no provider package list, then the
136 * implementation will use its own provider for
137 * <code><em>protocol</em></code>, or it will throw a
138 * <code>MalformedURLException</code> if there is none.  An
139 * implementation may choose to find providers by other means.  For
140 * example, it may support the <a
141 * href="{@docRoot}/../technotes/guides/jar/jar.html#Service%20Provider">
142 * JAR conventions for service providers</a>, where the service
143 * interface is <code>JMXConnectorProvider</code>.</p>
144 *
145 * <p>Every implementation must support the RMI connector protocol with
146 * the default RMI transport, specified with string <code>rmi</code>.
147 * </p>
148 *
149 * <p>Once a provider is found, the result of the
150 * <code>newJMXConnector</code> method is the result of calling {@link
151 * JMXConnectorProvider#newJMXConnector(JMXServiceURL,Map) newJMXConnector}
152 * on the provider.</p>
153 *
154 * <p>The <code>Map</code> parameter passed to the
155 * <code>JMXConnectorProvider</code> is a new read-only
156 * <code>Map</code> that contains all the entries that were in the
157 * <code>environment</code> parameter to {@link
158 * #newJMXConnector(JMXServiceURL,Map)
159 * JMXConnectorFactory.newJMXConnector}, if there was one.
160 * Additionally, if the
161 * <code>jmx.remote.protocol.provider.class.loader</code> key is not
162 * present in the <code>environment</code> parameter, it is added to
163 * the new read-only <code>Map</code>.  The associated value is the
164 * calling thread's context class loader.</p>
165 *
166 * @since 1.5
167 */
168public class JMXConnectorFactory {
169
170    /**
171     * <p>Name of the attribute that specifies the default class
172     * loader. This class loader is used to deserialize return values and
173     * exceptions from remote <code>MBeanServerConnection</code>
174     * calls.  The value associated with this attribute is an instance
175     * of {@link ClassLoader}.</p>
176     */
177    public static final String DEFAULT_CLASS_LOADER =
178        "jmx.remote.default.class.loader";
179
180    /**
181     * <p>Name of the attribute that specifies the provider packages
182     * that are consulted when looking for the handler for a protocol.
183     * The value associated with this attribute is a string with
184     * package names separated by vertical bars (<code>|</code>).</p>
185     */
186    public static final String PROTOCOL_PROVIDER_PACKAGES =
187        "jmx.remote.protocol.provider.pkgs";
188
189    /**
190     * <p>Name of the attribute that specifies the class
191     * loader for loading protocol providers.
192     * The value associated with this attribute is an instance
193     * of {@link ClassLoader}.</p>
194     */
195    public static final String PROTOCOL_PROVIDER_CLASS_LOADER =
196        "jmx.remote.protocol.provider.class.loader";
197
198    private static final String PROTOCOL_PROVIDER_DEFAULT_PACKAGE =
199        "com.sun.jmx.remote.protocol";
200
201    private static final ClassLogger logger =
202        new ClassLogger("javax.management.remote.misc", "JMXConnectorFactory");
203
204    /** There are no instances of this class.  */
205    private JMXConnectorFactory() {
206    }
207
208    /**
209     * <p>Creates a connection to the connector server at the given
210     * address.</p>
211     *
212     * <p>This method is equivalent to {@link
213     * #connect(JMXServiceURL,Map) connect(serviceURL, null)}.</p>
214     *
215     * @param serviceURL the address of the connector server to
216     * connect to.
217     *
218     * @return a <code>JMXConnector</code> whose {@link
219     * JMXConnector#connect connect} method has been called.
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            throws IOException {
231        return connect(serviceURL, null);
232    }
233
234    /**
235     * <p>Creates a connection to the connector server at the given
236     * address.</p>
237     *
238     * <p>This method is equivalent to:</p>
239     *
240     * <pre>
241     * JMXConnector conn = JMXConnectorFactory.newJMXConnector(serviceURL,
242     *                                                         environment);
243     * conn.connect(environment);
244     * </pre>
245     *
246     * @param serviceURL the address of the connector server to connect to.
247     *
248     * @param environment a set of attributes to determine how the
249     * connection is made.  This parameter can be null.  Keys in this
250     * map must be Strings.  The appropriate type of each associated
251     * value depends on the attribute.  The contents of
252     * <code>environment</code> are not changed by this call.
253     *
254     * @return a <code>JMXConnector</code> representing the newly-made
255     * connection.  Each successful call to this method produces a
256     * different object.
257     *
258     * @exception NullPointerException if <code>serviceURL</code> is null.
259     *
260     * @exception IOException if the connector client or the
261     * connection cannot be made because of a communication problem.
262     *
263     * @exception SecurityException if the connection cannot be made
264     * for security reasons.
265     */
266    public static JMXConnector connect(JMXServiceURL serviceURL,
267                                       Map<String,?> environment)
268            throws IOException {
269        if (serviceURL == null)
270            throw new NullPointerException("Null JMXServiceURL");
271        JMXConnector conn = newJMXConnector(serviceURL, environment);
272        conn.connect(environment);
273        return conn;
274    }
275
276    private static <K,V> Map<K,V> newHashMap() {
277        return new HashMap<K,V>();
278    }
279
280    private static <K> Map<K,Object> newHashMap(Map<K,?> map) {
281        return new HashMap<K,Object>(map);
282    }
283
284    /**
285     * <p>Creates a connector client for the connector server at the
286     * given address.  The resultant client is not connected until its
287     * {@link JMXConnector#connect(Map) connect} method is called.</p>
288     *
289     * @param serviceURL the address of the connector server to connect to.
290     *
291     * @param environment a set of attributes to determine how the
292     * connection is made.  This parameter can be null.  Keys in this
293     * map must be Strings.  The appropriate type of each associated
294     * value depends on the attribute.  The contents of
295     * <code>environment</code> are not changed by this call.
296     *
297     * @return a <code>JMXConnector</code> representing the new
298     * connector client.  Each successful call to this method produces
299     * a different object.
300     *
301     * @exception NullPointerException if <code>serviceURL</code> is null.
302     *
303     * @exception IOException if the connector client cannot be made
304     * because of a communication problem.
305     *
306     * @exception MalformedURLException if there is no provider for the
307     * protocol in <code>serviceURL</code>.
308     *
309     * @exception JMXProviderException if there is a provider for the
310     * protocol in <code>serviceURL</code> but it cannot be used for
311     * some reason.
312     */
313    public static JMXConnector newJMXConnector(JMXServiceURL serviceURL,
314                                               Map<String,?> environment)
315            throws IOException {
316
317        final Map<String,Object> envcopy;
318        if (environment == null)
319            envcopy = newHashMap();
320        else {
321            EnvHelp.checkAttributes(environment);
322            envcopy = newHashMap(environment);
323        }
324
325        final ClassLoader loader = resolveClassLoader(envcopy);
326        final Class<JMXConnectorProvider> targetInterface =
327                JMXConnectorProvider.class;
328        final String protocol = serviceURL.getProtocol();
329        final String providerClassName = "ClientProvider";
330        final JMXServiceURL providerURL = serviceURL;
331
332        JMXConnectorProvider provider = getProvider(providerURL, envcopy,
333                                               providerClassName,
334                                               targetInterface,
335                                               loader);
336
337        IOException exception = null;
338        if (provider == null) {
339            Predicate<Provider<?>> systemProvider =
340                    JMXConnectorFactory::isSystemProvider;
341            // Loader is null when context class loader is set to null
342            // and no loader has been provided in map.
343            // com.sun.jmx.remote.util.Service class extracted from j2se
344            // provider search algorithm doesn't handle well null classloader.
345            JMXConnector connection = null;
346            if (loader != null) {
347                try {
348                    connection = getConnectorAsService(loader,
349                                                       providerURL,
350                                                       envcopy,
351                                                       systemProvider.negate());
352                    if (connection != null) return connection;
353                } catch (JMXProviderException e) {
354                    throw e;
355                } catch (IOException e) {
356                    exception = e;
357                }
358            }
359            connection = getConnectorAsService(
360                             JMXConnectorFactory.class.getClassLoader(),
361                             providerURL,
362                             Collections.unmodifiableMap(envcopy),
363                             systemProvider);
364            if (connection != null) return connection;
365        }
366
367        if (provider == null) {
368            MalformedURLException e =
369                new MalformedURLException("Unsupported protocol: " + protocol);
370            if (exception == null) {
371                throw e;
372            } else {
373                throw EnvHelp.initCause(e, exception);
374            }
375        }
376
377        final Map<String,Object> fixedenv =
378                Collections.unmodifiableMap(envcopy);
379
380        return provider.newJMXConnector(serviceURL, fixedenv);
381    }
382
383    private static String resolvePkgs(Map<String, ?> env)
384            throws JMXProviderException {
385
386        Object pkgsObject = null;
387
388        if (env != null)
389            pkgsObject = env.get(PROTOCOL_PROVIDER_PACKAGES);
390
391        if (pkgsObject == null)
392            pkgsObject =
393                AccessController.doPrivileged(new PrivilegedAction<String>() {
394                    public String run() {
395                        return System.getProperty(PROTOCOL_PROVIDER_PACKAGES);
396                    }
397                });
398
399        if (pkgsObject == null)
400            return null;
401
402        if (!(pkgsObject instanceof String)) {
403            final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
404                " parameter is not a String: " +
405                pkgsObject.getClass().getName();
406            throw new JMXProviderException(msg);
407        }
408
409        final String pkgs = (String) pkgsObject;
410        if (pkgs.trim().equals(""))
411            return null;
412
413        // pkgs may not contain an empty element
414        if (pkgs.startsWith("|") || pkgs.endsWith("|") ||
415            pkgs.indexOf("||") >= 0) {
416            final String msg = "Value of " + PROTOCOL_PROVIDER_PACKAGES +
417                " contains an empty element: " + pkgs;
418            throw new JMXProviderException(msg);
419        }
420
421        return pkgs;
422    }
423
424    static <T> T getProvider(JMXServiceURL serviceURL,
425                             final Map<String, Object> environment,
426                             String providerClassName,
427                             Class<T> targetInterface,
428                             final ClassLoader loader)
429            throws IOException {
430
431        final String protocol = serviceURL.getProtocol();
432
433        final String pkgs = resolvePkgs(environment);
434
435        T instance = null;
436
437        if (pkgs != null) {
438            instance =
439                getProvider(protocol, pkgs, loader, providerClassName,
440                            targetInterface);
441
442            if (instance != null) {
443                boolean needsWrap = (loader != instance.getClass().getClassLoader());
444                environment.put(PROTOCOL_PROVIDER_CLASS_LOADER, needsWrap ? wrap(loader) : loader);
445            }
446        }
447
448        return instance;
449    }
450
451    private static ClassLoader wrap(final ClassLoader parent) {
452        return parent != null ? AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
453            @Override
454            public ClassLoader run() {
455                return new ClassLoader(parent) {
456                    @Override
457                    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
458                        ReflectUtil.checkPackageAccess(name);
459                        return super.loadClass(name, resolve);
460                    }
461                };
462            }
463        }) : null;
464    }
465
466    /**
467     * Checks whether the given provider is our system provider for
468     * the RMI connector.
469     * If providers for additional protocols are added in the future
470     * then the name of their modules may need to be added here.
471     * System providers will be loaded only if no other provider is found.
472     * @param provider the provider to test.
473     * @return true if this provider is a default system provider.
474     */
475    static boolean isSystemProvider(Provider<?> provider) {
476        Module providerModule = provider.type().getModule();
477        return providerModule.isNamed()
478           && providerModule.getName().equals("java.management.rmi");
479    }
480
481    /**
482     * Creates a JMXConnector from the first JMXConnectorProvider service
483     * supporting the given url that can be loaded from the given loader.
484     * <p>
485     * Parses the list of JMXConnectorProvider services that can be loaded
486     * from the given loader, only retaining those that satisfy the given filter.
487     * Then for each provider, attempts to create a new JMXConnector.
488     * The first JMXConnector successfully created is returned.
489     * <p>
490     * The filter predicate is usually used to either exclude system providers
491     * or only retain system providers (see isSystemProvider(...) above).
492     *
493     * @param loader The ClassLoader to use when looking up an implementation
494     *        of the service. If null, then only installed services will be
495     *        considered.
496     *
497     * @param url The JMXServiceURL of the connector for which a provider is
498     *        requested.
499     *
500     * @param filter A filter used to exclude or return provider
501     *        implementations. Typically the filter will either exclude
502     *        system services (system default implementations) or only
503     *        retain those.
504     *        This can allow to first look for custom implementations (e.g.
505     *        deployed on the CLASSPATH with META-INF/services) and
506     *        then only default to system implementations.
507     *
508     * @throws IOException if no connector could not be instantiated, and
509     *         at least one provider threw an exception that wasn't a
510     *         {@code MalformedURLException} or a {@code JMProviderException}.
511     *
512     * @throws JMXProviderException if a provider for the protocol in
513     *         <code>url</code> was found, but couldn't create the connector
514     *         some reason.
515     *
516     * @return an instance of JMXConnector if a provider was found from
517     *         which one could be instantiated, {@code null} otherwise.
518     */
519    private static JMXConnector getConnectorAsService(ClassLoader loader,
520                                                      JMXServiceURL url,
521                                                      Map<String, ?> map,
522                                                      Predicate<Provider<?>> filter)
523        throws IOException {
524
525        final ConnectorFactory<JMXConnectorProvider, JMXConnector> factory =
526                (p) -> p.newJMXConnector(url, map);
527        return getConnectorAsService(JMXConnectorProvider.class, loader, url,
528                                     filter, factory);
529    }
530
531
532    /**
533     * A factory function that can create a connector from a provider.
534     * The pair (P,C) will be either one of:
535     * a. (JMXConnectorProvider, JMXConnector) or
536     * b. (JMXConnectorServerProvider, JMXConnectorServer)
537     */
538    @FunctionalInterface
539    static interface ConnectorFactory<P,C> {
540        public C apply(P provider) throws Exception;
541    }
542
543    /**
544     * An instance of ProviderFinder is used to traverse a
545     * {@code Stream<Provider<P>>} and find the first implementation of P
546     * that supports creating a connector C from the given JMXServiceURL.
547     * <p>
548     * The pair (P,C) will be either one of: <br>
549     * a. (JMXConnectorProvider, JMXConnector) or <br>
550     * b. (JMXConnectorServerProvider, JMXConnectorServer)
551     * <p>
552     * The first connector successfully created while traversing the stream
553     * is stored in the ProviderFinder instance. After that, the
554     * ProviderFinder::test method, if called, will always return false, skipping
555     * the remaining providers.
556     * <p>
557     * An instance of ProviderFinder is always expected to be used in conjunction
558     * with Stream::findFirst, so that the stream traversal is stopped as soon
559     * as a matching provider is found.
560     * <p>
561     * At the end of the stream traversal, the ProviderFinder::get method can be
562     * used to obtain the connector instance (an instance of C) that was created.
563     * If no connector could be created, and an exception was encountered while
564     * traversing the stream and attempting to create the connector, then that
565     * exception will be thrown by ProviderFinder::get, wrapped, if needed,
566     * inside an IOException.
567     * <p>
568     * If any JMXProviderException is encountered while traversing the stream and
569     * attempting to create the connector, that exception will be wrapped in an
570     * UncheckedIOException and thrown immediately within the stream, thus
571     * interrupting the traversal.
572     * <p>
573     * If no matching provider was found (no provider found or attempting
574     * factory.apply always returned null or threw a MalformedURLException,
575     * indicating the provider didn't support the protocol asked for by
576     * the JMXServiceURL), then ProviderFinder::get will simply return null.
577     */
578    private static final class ProviderFinder<P,C> implements Predicate<Provider<P>> {
579
580        final ConnectorFactory<P,C> factory;
581        final JMXServiceURL  url;
582        private IOException  exception = null;
583        private C connection = null;
584
585        ProviderFinder(ConnectorFactory<P,C> factory, JMXServiceURL url) {
586            this.factory = factory;
587            this.url = url;
588        }
589
590        /**
591         * Returns {@code true} for the first provider {@code sp} that can
592         * be used to obtain an instance of {@code C} from the given
593         * {@code factory}.
594         *
595         * @param sp a candidate provider for instantiating {@code C}.
596         *
597         * @throws UncheckedIOException if {@code sp} throws a
598         *         JMXProviderException. The JMXProviderException is set as the
599         *         root cause.
600         *
601         * @return {@code true} for the first provider {@code sp} for which
602         *         {@code C} could be instantiated, {@code false} otherwise.
603         */
604        public boolean test(Provider<P> sp) {
605            if (connection == null) {
606                P provider = sp.get();
607                try {
608                    connection = factory.apply(provider);
609                    return connection != null;
610                } catch (JMXProviderException e) {
611                    throw new UncheckedIOException(e);
612                } catch (Exception e) {
613                    if (logger.traceOn())
614                        logger.trace("getConnectorAsService",
615                             "URL[" + url +
616                             "] Service provider exception: " + e);
617                    if (!(e instanceof MalformedURLException)) {
618                        if (exception == null) {
619                            if (e instanceof IOException) {
620                                exception = (IOException) e;
621                            } else {
622                                exception = EnvHelp.initCause(
623                                    new IOException(e.getMessage()), e);
624                            }
625                        }
626                    }
627                }
628            }
629            return false;
630        }
631
632        /**
633         * Returns an instance of {@code C} if a provider was found from
634         * which {@code C} could be instantiated.
635         *
636         * @throws IOException if {@code C} could not be instantiated, and
637         *         at least one provider threw an exception that wasn't a
638         *         {@code MalformedURLException} or a {@code JMProviderException}.
639         *
640         * @return an instance of {@code C} if a provider was found from
641         *         which {@code C} could be instantiated, {@code null} otherwise.
642         */
643        C get() throws IOException {
644            if (connection != null) return connection;
645            else if (exception != null) throw exception;
646            else return null;
647        }
648    }
649
650    /**
651     * Creates a connector from a provider loaded from the ServiceLoader.
652     * <p>
653     * The pair (P,C) will be either one of: <br>
654     * a. (JMXConnectorProvider, JMXConnector) or <br>
655     * b. (JMXConnectorServerProvider, JMXConnectorServer)
656     *
657     * @param providerClass The service type for which an implementation
658     *        should be looked up from the {@code ServiceLoader}. This will
659     *        be either {@code JMXConnectorProvider.class} or
660     *        {@code JMXConnectorServerProvider.class}
661     *
662     * @param loader The ClassLoader to use when looking up an implementation
663     *        of the service. If null, then only installed services will be
664     *        considered.
665     *
666     * @param url The JMXServiceURL of the connector for which a provider is
667     *        requested.
668     *
669     * @param filter A filter used to exclude or return provider
670     *        implementations. Typically the filter will either exclude
671     *        system services (system default implementations) or only
672     *        retain those.
673     *        This can allow to first look for custom implementations (e.g.
674     *        deployed on the CLASSPATH with META-INF/services) and
675     *        then only default to system implementations.
676     *
677     * @param factory A functional factory that can attempt to create an
678     *        instance of connector {@code C} from a provider {@code P}.
679     *        Typically, this is a simple wrapper over {@code
680     *        JMXConnectorProvider::newJMXConnector} or {@code
681     *        JMXConnectorProviderServer::newJMXConnectorServer}.
682     *
683     * @throws IOException if {@code C} could not be instantiated, and
684     *         at least one provider {@code P} threw an exception that wasn't a
685     *         {@code MalformedURLException} or a {@code JMProviderException}.
686     *
687     * @throws JMXProviderException if a provider {@code P} for the protocol in
688     *         <code>url</code> was found, but couldn't create the connector
689     *         {@code C} for some reason.
690     *
691     * @return an instance of {@code C} if a provider {@code P} was found from
692     *         which one could be instantiated, {@code null} otherwise.
693     */
694    static <P,C> C getConnectorAsService(Class<P> providerClass,
695                                         ClassLoader loader,
696                                         JMXServiceURL url,
697                                         Predicate<Provider<?>> filter,
698                                         ConnectorFactory<P,C> factory)
699        throws IOException {
700
701        // sanity check
702        if (JMXConnectorProvider.class != providerClass
703            && JMXConnectorServerProvider.class != providerClass) {
704            // should never happen
705            throw new InternalError("Unsupported service interface: "
706                                    + providerClass.getName());
707        }
708
709        ServiceLoader<P> serviceLoader = loader == null
710                ? ServiceLoader.loadInstalled(providerClass)
711                : ServiceLoader.load(providerClass, loader);
712        Stream<Provider<P>> stream = serviceLoader.stream().filter(filter);
713        ProviderFinder<P,C> finder = new ProviderFinder<>(factory, url);
714
715        try {
716            stream.filter(finder).findFirst();
717            return finder.get();
718        } catch (UncheckedIOException e) {
719            if (e.getCause() instanceof JMXProviderException) {
720                throw (JMXProviderException) e.getCause();
721            } else {
722                throw e;
723            }
724        }
725    }
726
727    static <T> T getProvider(String protocol,
728                              String pkgs,
729                              ClassLoader loader,
730                              String providerClassName,
731                              Class<T> targetInterface)
732            throws IOException {
733
734        StringTokenizer tokenizer = new StringTokenizer(pkgs, "|");
735
736        while (tokenizer.hasMoreTokens()) {
737            String pkg = tokenizer.nextToken();
738            String className = (pkg + "." + protocol2package(protocol) +
739                                "." + providerClassName);
740            Class<?> providerClass;
741            try {
742                providerClass = Class.forName(className, true, loader);
743            } catch (ClassNotFoundException e) {
744                //Add trace.
745                continue;
746            }
747
748            if (!targetInterface.isAssignableFrom(providerClass)) {
749                final String msg =
750                    "Provider class does not implement " +
751                    targetInterface.getName() + ": " +
752                    providerClass.getName();
753                throw new JMXProviderException(msg);
754            }
755
756            // We have just proved that this cast is correct
757            Class<? extends T> providerClassT = Util.cast(providerClass);
758            try {
759                @SuppressWarnings("deprecation")
760                T result = providerClassT.newInstance();
761                return result;
762            } catch (Exception e) {
763                final String msg =
764                    "Exception when instantiating provider [" + className +
765                    "]";
766                throw new JMXProviderException(msg, e);
767            }
768        }
769
770        return null;
771    }
772
773    static ClassLoader resolveClassLoader(Map<String, ?> environment) {
774        ClassLoader loader = null;
775
776        if (environment != null) {
777            try {
778                loader = (ClassLoader)
779                    environment.get(PROTOCOL_PROVIDER_CLASS_LOADER);
780            } catch (ClassCastException e) {
781                final String msg =
782                    "The ClassLoader supplied in the environment map using " +
783                    "the " + PROTOCOL_PROVIDER_CLASS_LOADER +
784                    " attribute is not an instance of java.lang.ClassLoader";
785                throw new IllegalArgumentException(msg);
786            }
787        }
788
789        if (loader == null) {
790            loader = Thread.currentThread().getContextClassLoader();
791        }
792
793        return loader;
794    }
795
796    private static String protocol2package(String protocol) {
797        return protocol.replace('+', '.').replace('-', '_');
798    }
799}
800