1 /*
   2  * Copyright (c) 2003, 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 
  26 package javax.management.remote;
  27 
  28 
  29 import com.sun.jmx.remote.util.ClassLogger;
  30 import com.sun.jmx.remote.util.EnvHelp;
  31 
  32 import java.io.IOException;
  33 import java.io.UncheckedIOException;
  34 import java.net.MalformedURLException;
  35 import java.util.Collections;
  36 import java.util.HashMap;
  37 import java.util.Map;
  38 import java.util.ServiceLoader.Provider;
  39 import java.util.function.Predicate;
  40 
  41 import javax.management.MBeanServer;
  42 import javax.management.remote.JMXConnectorFactory.ConnectorFactory;
  43 
  44 /**
  45  * <p>Factory to create JMX API connector servers.  There
  46  * are no instances of this class.</p>
  47  *
  48  * <p>Each connector server is created by an instance of {@link
  49  * JMXConnectorServerProvider}.  This instance is found as follows.  Suppose
  50  * the given {@link JMXServiceURL} looks like
  51  * <code>"service:jmx:<em>protocol</em>:<em>remainder</em>"</code>.
  52  * Then the factory will attempt to find the appropriate {@link
  53  * JMXConnectorServerProvider} for <code><em>protocol</em></code>.  Each
  54  * occurrence of the character <code>+</code> or <code>-</code> in
  55  * <code><em>protocol</em></code> is replaced by <code>.</code> or
  56  * <code>_</code>, respectively.</p>
  57  *
  58  * <p>A <em>provider package list</em> is searched for as follows:</p>
  59  *
  60  * <ol>
  61  *
  62  * <li>If the <code>environment</code> parameter to {@link
  63  * #newJMXConnectorServer(JMXServiceURL,Map,MBeanServer)
  64  * newJMXConnectorServer} contains the key
  65  * <code>jmx.remote.protocol.provider.pkgs</code> then the associated
  66  * value is the provider package list.
  67  *
  68  * <li>Otherwise, if the system property
  69  * <code>jmx.remote.protocol.provider.pkgs</code> exists, then its value
  70  * is the provider package list.
  71  *
  72  * <li>Otherwise, there is no provider package list.
  73  *
  74  * </ol>
  75  *
  76  * <p>The provider package list is a string that is interpreted as a
  77  * list of non-empty Java package names separated by vertical bars
  78  * (<code>|</code>).  If the string is empty, then so is the provider
  79  * package list.  If the provider package list is not a String, or if
  80  * it contains an element that is an empty string, a {@link
  81  * JMXProviderException} is thrown.</p>
  82  *
  83  * <p>If the provider package list exists and is not empty, then for
  84  * each element <code><em>pkg</em></code> of the list, the factory
  85  * will attempt to load the class
  86  *
  87  * <blockquote>
  88  * <code><em>pkg</em>.<em>protocol</em>.ServerProvider</code>
  89  * </blockquote>
  90 
  91  * <p>If the <code>environment</code> parameter to {@link
  92  * #newJMXConnectorServer(JMXServiceURL, Map, MBeanServer)
  93  * newJMXConnectorServer} contains the key
  94  * <code>jmx.remote.protocol.provider.class.loader</code> then the
  95  * associated value is the class loader to use to load the provider.
  96  * If the associated value is not an instance of {@link
  97  * java.lang.ClassLoader}, an {@link
  98  * java.lang.IllegalArgumentException} is thrown.</p>
  99  *
 100  * <p>If the <code>jmx.remote.protocol.provider.class.loader</code>
 101  * key is not present in the <code>environment</code> parameter, the
 102  * calling thread's context class loader is used.</p>
 103  *
 104  * <p>If the attempt to load this class produces a {@link
 105  * ClassNotFoundException}, the search for a handler continues with
 106  * the next element of the list.</p>
 107  *
 108  * <p>Otherwise, a problem with the provider found is signalled by a
 109  * {@link JMXProviderException} whose {@link
 110  * JMXProviderException#getCause() <em>cause</em>} indicates the
 111  * underlying exception, as follows:</p>
 112  *
 113  * <ul>
 114  *
 115  * <li>if the attempt to load the class produces an exception other
 116  * than <code>ClassNotFoundException</code>, that is the
 117  * <em>cause</em>;
 118  *
 119  * <li>if {@link Class#newInstance()} for the class produces an
 120  * exception, that is the <em>cause</em>.
 121  *
 122  * </ul>
 123  *
 124  * <p>If no provider is found by the above steps, including the
 125  * default case where there is no provider package list, then the
 126  * implementation will use its own provider for
 127  * <code><em>protocol</em></code>, or it will throw a
 128  * <code>MalformedURLException</code> if there is none.  An
 129  * implementation may choose to find providers by other means.  For
 130  * example, it may support the <a
 131  * href="{@docRoot}/../technotes/guides/jar/jar.html#Service%20Provider">
 132  * JAR conventions for service providers</a>, where the service
 133  * interface is <code>JMXConnectorServerProvider</code>.</p>
 134  *
 135  * <p>Every implementation must support the RMI connector protocol with
 136  * the default RMI transport, specified with string <code>rmi</code>.
 137  * </p>
 138  *
 139  * <p>Once a provider is found, the result of the
 140  * <code>newJMXConnectorServer</code> method is the result of calling
 141  * {@link
 142  * JMXConnectorServerProvider#newJMXConnectorServer(JMXServiceURL,
 143  * Map, MBeanServer) newJMXConnectorServer} on the provider.</p>
 144  *
 145  * <p>The <code>Map</code> parameter passed to the
 146  * <code>JMXConnectorServerProvider</code> is a new read-only
 147  * <code>Map</code> that contains all the entries that were in the
 148  * <code>environment</code> parameter to {@link
 149  * #newJMXConnectorServer(JMXServiceURL,Map,MBeanServer)
 150  * JMXConnectorServerFactory.newJMXConnectorServer}, if there was one.
 151  * Additionally, if the
 152  * <code>jmx.remote.protocol.provider.class.loader</code> key is not
 153  * present in the <code>environment</code> parameter, it is added to
 154  * the new read-only <code>Map</code>. The associated value is the
 155  * calling thread's context class loader.</p>
 156  *
 157  * @since 1.5
 158  */
 159 public class JMXConnectorServerFactory {
 160 
 161     /**
 162      * <p>Name of the attribute that specifies the default class
 163      * loader.  This class loader is used to deserialize objects in
 164      * requests received from the client, possibly after consulting an
 165      * MBean-specific class loader.  The value associated with this
 166      * attribute is an instance of {@link ClassLoader}.</p>
 167      */
 168     public static final String DEFAULT_CLASS_LOADER =
 169         JMXConnectorFactory.DEFAULT_CLASS_LOADER;
 170 
 171     /**
 172      * <p>Name of the attribute that specifies the default class
 173      * loader MBean name.  This class loader is used to deserialize objects in
 174      * requests received from the client, possibly after consulting an
 175      * MBean-specific class loader.  The value associated with this
 176      * attribute is an instance of {@link javax.management.ObjectName
 177      * ObjectName}.</p>
 178      */
 179     public static final String DEFAULT_CLASS_LOADER_NAME =
 180         "jmx.remote.default.class.loader.name";
 181 
 182     /**
 183      * <p>Name of the attribute that specifies the provider packages
 184      * that are consulted when looking for the handler for a protocol.
 185      * The value associated with this attribute is a string with
 186      * package names separated by vertical bars (<code>|</code>).</p>
 187      */
 188     public static final String PROTOCOL_PROVIDER_PACKAGES =
 189         "jmx.remote.protocol.provider.pkgs";
 190 
 191     /**
 192      * <p>Name of the attribute that specifies the class
 193      * loader for loading protocol providers.
 194      * The value associated with this attribute is an instance
 195      * of {@link ClassLoader}.</p>
 196      */
 197     public static final String PROTOCOL_PROVIDER_CLASS_LOADER =
 198         "jmx.remote.protocol.provider.class.loader";
 199 
 200     private static final String PROTOCOL_PROVIDER_DEFAULT_PACKAGE =
 201         "com.sun.jmx.remote.protocol";
 202 
 203     private static final ClassLogger logger =
 204         new ClassLogger("javax.management.remote.misc","JMXConnectorServerFactory");
 205 
 206     /** There are no instances of this class.  */
 207     private JMXConnectorServerFactory() {
 208     }
 209 
 210     private static JMXConnectorServer
 211         getConnectorServerAsService(ClassLoader loader, JMXServiceURL url,
 212                                     Map<String, ?> map, MBeanServer mbs,
 213                                     Predicate<Provider<?>> filter)
 214         throws IOException {
 215         final ConnectorFactory<JMXConnectorServerProvider,JMXConnectorServer>
 216               factory = (p) -> p.newJMXConnectorServer(url, map, mbs);
 217         return JMXConnectorFactory.getConnectorAsService(
 218                                      JMXConnectorServerProvider.class,
 219                                      loader, url, filter, factory);
 220     }
 221 
 222     /**
 223      * <p>Creates a connector server at the given address.  The
 224      * resultant server is not started until its {@link
 225      * JMXConnectorServer#start() start} method is called.</p>
 226      *
 227      * @param serviceURL the address of the new connector server.  The
 228      * actual address of the new connector server, as returned by its
 229      * {@link JMXConnectorServer#getAddress() getAddress} method, will
 230      * not necessarily be exactly the same.  For example, it might
 231      * include a port number if the original address did not.
 232      *
 233      * @param environment a set of attributes to control the new
 234      * connector server's behavior.  This parameter can be null.
 235      * Keys in this map must be Strings.  The appropriate type of each
 236      * associated value depends on the attribute.  The contents of
 237      * <code>environment</code> are not changed by this call.
 238      *
 239      * @param mbeanServer the MBean server that this connector server
 240      * is attached to.  Null if this connector server will be attached
 241      * to an MBean server by being registered in it.
 242      *
 243      * @return a <code>JMXConnectorServer</code> representing the new
 244      * connector server.  Each successful call to this method produces
 245      * a different object.
 246      *
 247      * @exception NullPointerException if <code>serviceURL</code> is null.
 248      *
 249      * @exception IOException if the connector server cannot be made
 250      * because of a communication problem.
 251      *
 252      * @exception MalformedURLException if there is no provider for the
 253      * protocol in <code>serviceURL</code>.
 254      *
 255      * @exception JMXProviderException if there is a provider for the
 256      * protocol in <code>serviceURL</code> but it cannot be used for
 257      * some reason.
 258      */
 259     public static JMXConnectorServer
 260         newJMXConnectorServer(JMXServiceURL serviceURL,
 261                               Map<String,?> environment,
 262                               MBeanServer mbeanServer)
 263             throws IOException {
 264         Map<String, Object> envcopy;
 265         if (environment == null)
 266             envcopy = new HashMap<String, Object>();
 267         else {
 268             EnvHelp.checkAttributes(environment);
 269             envcopy = new HashMap<String, Object>(environment);
 270         }
 271 
 272         final Class<JMXConnectorServerProvider> targetInterface =
 273                 JMXConnectorServerProvider.class;
 274         final ClassLoader loader =
 275             JMXConnectorFactory.resolveClassLoader(envcopy);
 276         final String protocol = serviceURL.getProtocol();
 277         final String providerClassName = "ServerProvider";
 278 
 279         JMXConnectorServerProvider provider =
 280             JMXConnectorFactory.getProvider(serviceURL,
 281                                             envcopy,
 282                                             providerClassName,
 283                                             targetInterface,
 284                                             loader);
 285 
 286         IOException exception = null;
 287         JMXConnectorServer connection = null;
 288         if (provider == null) {
 289             Predicate<Provider<?>> systemProvider =
 290                     JMXConnectorFactory::isSystemProvider;
 291             // Loader is null when context class loader is set to null
 292             // and no loader has been provided in map.
 293             // com.sun.jmx.remote.util.Service class extracted from j2se
 294             // provider search algorithm doesn't handle well null classloader.
 295             if (loader != null) {
 296                 try {
 297                     connection =
 298                         getConnectorServerAsService(loader,
 299                                                     serviceURL,
 300                                                     envcopy,
 301                                                     mbeanServer,
 302                                                     systemProvider.negate());
 303                     if (connection != null)
 304                         return connection;
 305                 } catch (JMXProviderException e) {
 306                     throw e;
 307                 } catch (IOException e) {
 308                     exception = e;
 309                 }
 310             }
 311             connection = getConnectorServerAsService(
 312                             JMXConnectorFactory.class.getClassLoader(),
 313                             serviceURL,
 314                             Collections.unmodifiableMap(envcopy),
 315                             mbeanServer,
 316                             systemProvider);
 317             if (connection != null) return connection;
 318         }
 319 
 320         if (provider == null) {
 321             MalformedURLException e =
 322                 new MalformedURLException("Unsupported protocol: " + protocol);
 323             if (exception == null) {
 324                 throw e;
 325             } else {
 326                 throw EnvHelp.initCause(e, exception);
 327             }
 328         }
 329 
 330         envcopy = Collections.unmodifiableMap(envcopy);
 331 
 332         return provider.newJMXConnectorServer(serviceURL,
 333                                               envcopy,
 334                                               mbeanServer);
 335     }
 336 }