rev 14210 : 8154231: Simplify access to System properties from JDK code
Reviewed-by: rriggs

   1 /*
   2  * Copyright (c) 1995, 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 java.net;
  27 
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.net.spi.URLStreamHandlerProvider;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 import java.util.Hashtable;
  34 import java.io.InvalidObjectException;
  35 import java.io.ObjectStreamException;
  36 import java.io.ObjectStreamField;
  37 import java.io.ObjectInputStream.GetField;
  38 import java.util.Iterator;
  39 import java.util.Locale;
  40 import java.util.NoSuchElementException;
  41 import java.util.ServiceConfigurationError;
  42 import java.util.ServiceLoader;
  43 
  44 import sun.security.util.SecurityConstants;
  45 import sun.security.action.GetPropertyAction;
  46 
  47 /**
  48  * Class {@code URL} represents a Uniform Resource
  49  * Locator, a pointer to a "resource" on the World
  50  * Wide Web. A resource can be something as simple as a file or a
  51  * directory, or it can be a reference to a more complicated object,
  52  * such as a query to a database or to a search engine. More
  53  * information on the types of URLs and their formats can be found at:
  54  * <a href=
  55  * "http://web.archive.org/web/20051219043731/http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/url-primer.html">
  56  * <i>Types of URL</i></a>
  57  * <p>
  58  * In general, a URL can be broken into several parts. Consider the
  59  * following example:
  60  * <blockquote><pre>
  61  *     http://www.example.com/docs/resource1.html
  62  * </pre></blockquote>
  63  * <p>
  64  * The URL above indicates that the protocol to use is
  65  * {@code http} (HyperText Transfer Protocol) and that the
  66  * information resides on a host machine named
  67  * {@code www.example.com}. The information on that host
  68  * machine is named {@code /docs/resource1.html}. The exact
  69  * meaning of this name on the host machine is both protocol
  70  * dependent and host dependent. The information normally resides in
  71  * a file, but it could be generated on the fly. This component of
  72  * the URL is called the <i>path</i> component.
  73  * <p>
  74  * A URL can optionally specify a "port", which is the
  75  * port number to which the TCP connection is made on the remote host
  76  * machine. If the port is not specified, the default port for
  77  * the protocol is used instead. For example, the default port for
  78  * {@code http} is {@code 80}. An alternative port could be
  79  * specified as:
  80  * <blockquote><pre>
  81  *     http://www.example.com:1080/docs/resource1.html
  82  * </pre></blockquote>
  83  * <p>
  84  * The syntax of {@code URL} is defined by  <a
  85  * href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
  86  * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
  87  * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
  88  * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
  89  * also supports scope_ids. The syntax and usage of scope_ids is described
  90  * <a href="Inet6Address.html#scoped">here</a>.
  91  * <p>
  92  * A URL may have appended to it a "fragment", also known
  93  * as a "ref" or a "reference". The fragment is indicated by the sharp
  94  * sign character "#" followed by more characters. For example,
  95  * <blockquote><pre>
  96  *     http://java.sun.com/index.html#chapter1
  97  * </pre></blockquote>
  98  * <p>
  99  * This fragment is not technically part of the URL. Rather, it
 100  * indicates that after the specified resource is retrieved, the
 101  * application is specifically interested in that part of the
 102  * document that has the tag {@code chapter1} attached to it. The
 103  * meaning of a tag is resource specific.
 104  * <p>
 105  * An application can also specify a "relative URL",
 106  * which contains only enough information to reach the resource
 107  * relative to another URL. Relative URLs are frequently used within
 108  * HTML pages. For example, if the contents of the URL:
 109  * <blockquote><pre>
 110  *     http://java.sun.com/index.html
 111  * </pre></blockquote>
 112  * contained within it the relative URL:
 113  * <blockquote><pre>
 114  *     FAQ.html
 115  * </pre></blockquote>
 116  * it would be a shorthand for:
 117  * <blockquote><pre>
 118  *     http://java.sun.com/FAQ.html
 119  * </pre></blockquote>
 120  * <p>
 121  * The relative URL need not specify all the components of a URL. If
 122  * the protocol, host name, or port number is missing, the value is
 123  * inherited from the fully specified URL. The file component must be
 124  * specified. The optional fragment is not inherited.
 125  * <p>
 126  * The URL class does not itself encode or decode any URL components
 127  * according to the escaping mechanism defined in RFC2396. It is the
 128  * responsibility of the caller to encode any fields, which need to be
 129  * escaped prior to calling URL, and also to decode any escaped fields,
 130  * that are returned from URL. Furthermore, because URL has no knowledge
 131  * of URL escaping, it does not recognise equivalence between the encoded
 132  * or decoded form of the same URL. For example, the two URLs:<br>
 133  * <pre>    http://foo.com/hello world/ and http://foo.com/hello%20world</pre>
 134  * would be considered not equal to each other.
 135  * <p>
 136  * Note, the {@link java.net.URI} class does perform escaping of its
 137  * component fields in certain circumstances. The recommended way
 138  * to manage the encoding and decoding of URLs is to use {@link java.net.URI},
 139  * and to convert between these two classes using {@link #toURI()} and
 140  * {@link URI#toURL()}.
 141  * <p>
 142  * The {@link URLEncoder} and {@link URLDecoder} classes can also be
 143  * used, but only for HTML form encoding, which is not the same
 144  * as the encoding scheme defined in RFC2396.
 145  *
 146  * @author  James Gosling
 147  * @since 1.0
 148  */
 149 public final class URL implements java.io.Serializable {
 150 
 151     static final String BUILTIN_HANDLERS_PREFIX = "sun.net.www.protocol";
 152     static final long serialVersionUID = -7627629688361524110L;
 153 
 154     /**
 155      * The property which specifies the package prefix list to be scanned
 156      * for protocol handlers.  The value of this property (if any) should
 157      * be a vertical bar delimited list of package names to search through
 158      * for a protocol handler to load.  The policy of this class is that
 159      * all protocol handlers will be in a class called <protocolname>.Handler,
 160      * and each package in the list is examined in turn for a matching
 161      * handler.  If none are found (or the property is not specified), the
 162      * default package prefix, sun.net.www.protocol, is used.  The search
 163      * proceeds from the first package in the list to the last and stops
 164      * when a match is found.
 165      */
 166     private static final String protocolPathProp = "java.protocol.handler.pkgs";
 167 
 168     /**
 169      * The protocol to use (ftp, http, nntp, ... etc.) .
 170      * @serial
 171      */
 172     private String protocol;
 173 
 174     /**
 175      * The host name to connect to.
 176      * @serial
 177      */
 178     private String host;
 179 
 180     /**
 181      * The protocol port to connect to.
 182      * @serial
 183      */
 184     private int port = -1;
 185 
 186     /**
 187      * The specified file name on that host. {@code file} is
 188      * defined as {@code path[?query]}
 189      * @serial
 190      */
 191     private String file;
 192 
 193     /**
 194      * The query part of this URL.
 195      */
 196     private transient String query;
 197 
 198     /**
 199      * The authority part of this URL.
 200      * @serial
 201      */
 202     private String authority;
 203 
 204     /**
 205      * The path part of this URL.
 206      */
 207     private transient String path;
 208 
 209     /**
 210      * The userinfo part of this URL.
 211      */
 212     private transient String userInfo;
 213 
 214     /**
 215      * # reference.
 216      * @serial
 217      */
 218     private String ref;
 219 
 220     /**
 221      * The host's IP address, used in equals and hashCode.
 222      * Computed on demand. An uninitialized or unknown hostAddress is null.
 223      */
 224     transient InetAddress hostAddress;
 225 
 226     /**
 227      * The URLStreamHandler for this URL.
 228      */
 229     transient URLStreamHandler handler;
 230 
 231     /* Our hash code.
 232      * @serial
 233      */
 234     private int hashCode = -1;
 235 
 236     private transient UrlDeserializedState tempState;
 237 
 238     /**
 239      * Creates a {@code URL} object from the specified
 240      * {@code protocol}, {@code host}, {@code port}
 241      * number, and {@code file}.<p>
 242      *
 243      * {@code host} can be expressed as a host name or a literal
 244      * IP address. If IPv6 literal address is used, it should be
 245      * enclosed in square brackets ({@code '['} and {@code ']'}), as
 246      * specified by <a
 247      * href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>;
 248      * However, the literal IPv6 address format defined in <a
 249      * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
 250      * Version 6 Addressing Architecture</i></a> is also accepted.<p>
 251      *
 252      * Specifying a {@code port} number of {@code -1}
 253      * indicates that the URL should use the default port for the
 254      * protocol.<p>
 255      *
 256      * If this is the first URL object being created with the specified
 257      * protocol, a <i>stream protocol handler</i> object, an instance of
 258      * class {@code URLStreamHandler}, is created for that protocol:
 259      * <ol>
 260      * <li>If the application has previously set up an instance of
 261      *     {@code URLStreamHandlerFactory} as the stream handler factory,
 262      *     then the {@code createURLStreamHandler} method of that instance
 263      *     is called with the protocol string as an argument to create the
 264      *     stream protocol handler.
 265      * <li>If no {@code URLStreamHandlerFactory} has yet been set up,
 266      *     or if the factory's {@code createURLStreamHandler} method
 267      *     returns {@code null}, then the {@linkplain java.util.ServiceLoader
 268      *     ServiceLoader} mechanism is used to locate {@linkplain
 269      *     java.net.spi.URLStreamHandlerProvider URLStreamHandlerProvider}
 270      *     implementations using the system class
 271      *     loader. The order that providers are located is implementation
 272      *     specific, and an implementation is free to cache the located
 273      *     providers. A {@linkplain java.util.ServiceConfigurationError
 274      *     ServiceConfigurationError}, {@code Error} or {@code RuntimeException}
 275      *     thrown from the {@code createURLStreamHandler}, if encountered, will
 276      *     be propagated to the calling thread. The {@code
 277      *     createURLStreamHandler} method of each provider, if instantiated, is
 278      *     invoked, with the protocol string, until a provider returns non-null,
 279      *     or all providers have been exhausted.
 280      * <li>If the previous step fails to find a protocol handler, the
 281      *     constructor reads the value of the system property:
 282      *     <blockquote>{@code
 283      *         java.protocol.handler.pkgs
 284      *     }</blockquote>
 285      *     If the value of that system property is not {@code null},
 286      *     it is interpreted as a list of packages separated by a vertical
 287      *     slash character '{@code |}'. The constructor tries to load
 288      *     the class named:
 289      *     <blockquote>{@code
 290      *         <package>.<protocol>.Handler
 291      *     }</blockquote>
 292      *     where {@code <package>} is replaced by the name of the package
 293      *     and {@code <protocol>} is replaced by the name of the protocol.
 294      *     If this class does not exist, or if the class exists but it is not
 295      *     a subclass of {@code URLStreamHandler}, then the next package
 296      *     in the list is tried.
 297      * <li>If the previous step fails to find a protocol handler, then the
 298      *     constructor tries to load a built-in protocol handler.
 299      *     If this class does not exist, or if the class exists but it is not a
 300      *     subclass of {@code URLStreamHandler}, then a
 301      *     {@code MalformedURLException} is thrown.
 302      * </ol>
 303      *
 304      * <p>Protocol handlers for the following protocols are guaranteed
 305      * to exist on the search path :-
 306      * <blockquote><pre>
 307      *     http, https, file, and jar
 308      * </pre></blockquote>
 309      * Protocol handlers for additional protocols may also be  available.
 310      * Some protocol handlers, for example those used for loading platform
 311      * classes or classes on the class path, may not be overridden. The details
 312      * of such restrictions, and when those restrictions apply (during
 313      * initialization of the runtime for example), are implementation specific
 314      * and therefore not specified
 315      *
 316      * <p>No validation of the inputs is performed by this constructor.
 317      *
 318      * @param      protocol   the name of the protocol to use.
 319      * @param      host       the name of the host.
 320      * @param      port       the port number on the host.
 321      * @param      file       the file on the host
 322      * @exception  MalformedURLException  if an unknown protocol or the port
 323      *                  is a negative number other than -1
 324      * @see        java.lang.System#getProperty(java.lang.String)
 325      * @see        java.net.URL#setURLStreamHandlerFactory(
 326      *                  java.net.URLStreamHandlerFactory)
 327      * @see        java.net.URLStreamHandler
 328      * @see        java.net.URLStreamHandlerFactory#createURLStreamHandler(
 329      *                  java.lang.String)
 330      */
 331     public URL(String protocol, String host, int port, String file)
 332         throws MalformedURLException
 333     {
 334         this(protocol, host, port, file, null);
 335     }
 336 
 337     /**
 338      * Creates a URL from the specified {@code protocol}
 339      * name, {@code host} name, and {@code file} name. The
 340      * default port for the specified protocol is used.
 341      * <p>
 342      * This constructor is equivalent to the four-argument
 343      * constructor with the only difference of using the
 344      * default port for the specified protocol.
 345      *
 346      * No validation of the inputs is performed by this constructor.
 347      *
 348      * @param      protocol   the name of the protocol to use.
 349      * @param      host       the name of the host.
 350      * @param      file       the file on the host.
 351      * @exception  MalformedURLException  if an unknown protocol is specified.
 352      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
 353      *                  int, java.lang.String)
 354      */
 355     public URL(String protocol, String host, String file)
 356             throws MalformedURLException {
 357         this(protocol, host, -1, file);
 358     }
 359 
 360     /**
 361      * Creates a {@code URL} object from the specified
 362      * {@code protocol}, {@code host}, {@code port}
 363      * number, {@code file}, and {@code handler}. Specifying
 364      * a {@code port} number of {@code -1} indicates that
 365      * the URL should use the default port for the protocol. Specifying
 366      * a {@code handler} of {@code null} indicates that the URL
 367      * should use a default stream handler for the protocol, as outlined
 368      * for:
 369      *     java.net.URL#URL(java.lang.String, java.lang.String, int,
 370      *                      java.lang.String)
 371      *
 372      * <p>If the handler is not null and there is a security manager,
 373      * the security manager's {@code checkPermission}
 374      * method is called with a
 375      * {@code NetPermission("specifyStreamHandler")} permission.
 376      * This may result in a SecurityException.
 377      *
 378      * No validation of the inputs is performed by this constructor.
 379      *
 380      * @param      protocol   the name of the protocol to use.
 381      * @param      host       the name of the host.
 382      * @param      port       the port number on the host.
 383      * @param      file       the file on the host
 384      * @param      handler    the stream handler for the URL.
 385      * @exception  MalformedURLException  if an unknown protocol or the port
 386                         is a negative number other than -1
 387      * @exception  SecurityException
 388      *        if a security manager exists and its
 389      *        {@code checkPermission} method doesn't allow
 390      *        specifying a stream handler explicitly.
 391      * @see        java.lang.System#getProperty(java.lang.String)
 392      * @see        java.net.URL#setURLStreamHandlerFactory(
 393      *                  java.net.URLStreamHandlerFactory)
 394      * @see        java.net.URLStreamHandler
 395      * @see        java.net.URLStreamHandlerFactory#createURLStreamHandler(
 396      *                  java.lang.String)
 397      * @see        SecurityManager#checkPermission
 398      * @see        java.net.NetPermission
 399      */
 400     public URL(String protocol, String host, int port, String file,
 401                URLStreamHandler handler) throws MalformedURLException {
 402         if (handler != null) {
 403             SecurityManager sm = System.getSecurityManager();
 404             if (sm != null) {
 405                 // check for permission to specify a handler
 406                 checkSpecifyHandler(sm);
 407             }
 408         }
 409 
 410         protocol = protocol.toLowerCase(Locale.ROOT);
 411         this.protocol = protocol;
 412         if (host != null) {
 413 
 414             /**
 415              * if host is a literal IPv6 address,
 416              * we will make it conform to RFC 2732
 417              */
 418             if (host.indexOf(':') >= 0 && !host.startsWith("[")) {
 419                 host = "["+host+"]";
 420             }
 421             this.host = host;
 422 
 423             if (port < -1) {
 424                 throw new MalformedURLException("Invalid port number :" +
 425                                                     port);
 426             }
 427             this.port = port;
 428             authority = (port == -1) ? host : host + ":" + port;
 429         }
 430 
 431         Parts parts = new Parts(file);
 432         path = parts.getPath();
 433         query = parts.getQuery();
 434 
 435         if (query != null) {
 436             this.file = path + "?" + query;
 437         } else {
 438             this.file = path;
 439         }
 440         ref = parts.getRef();
 441 
 442         // Note: we don't do validation of the URL here. Too risky to change
 443         // right now, but worth considering for future reference. -br
 444         if (handler == null &&
 445             (handler = getURLStreamHandler(protocol)) == null) {
 446             throw new MalformedURLException("unknown protocol: " + protocol);
 447         }
 448         this.handler = handler;
 449     }
 450 
 451     /**
 452      * Creates a {@code URL} object from the {@code String}
 453      * representation.
 454      * <p>
 455      * This constructor is equivalent to a call to the two-argument
 456      * constructor with a {@code null} first argument.
 457      *
 458      * @param      spec   the {@code String} to parse as a URL.
 459      * @exception  MalformedURLException  if no protocol is specified, or an
 460      *               unknown protocol is found, or {@code spec} is {@code null},
 461      *               or the parsed URL fails to comply with the specific syntax
 462      *               of the associated protocol.
 463      * @see        java.net.URL#URL(java.net.URL, java.lang.String)
 464      */
 465     public URL(String spec) throws MalformedURLException {
 466         this(null, spec);
 467     }
 468 
 469     /**
 470      * Creates a URL by parsing the given spec within a specified context.
 471      *
 472      * The new URL is created from the given context URL and the spec
 473      * argument as described in
 474      * RFC2396 &quot;Uniform Resource Identifiers : Generic * Syntax&quot; :
 475      * <blockquote><pre>
 476      *          &lt;scheme&gt;://&lt;authority&gt;&lt;path&gt;?&lt;query&gt;#&lt;fragment&gt;
 477      * </pre></blockquote>
 478      * The reference is parsed into the scheme, authority, path, query and
 479      * fragment parts. If the path component is empty and the scheme,
 480      * authority, and query components are undefined, then the new URL is a
 481      * reference to the current document. Otherwise, the fragment and query
 482      * parts present in the spec are used in the new URL.
 483      * <p>
 484      * If the scheme component is defined in the given spec and does not match
 485      * the scheme of the context, then the new URL is created as an absolute
 486      * URL based on the spec alone. Otherwise the scheme component is inherited
 487      * from the context URL.
 488      * <p>
 489      * If the authority component is present in the spec then the spec is
 490      * treated as absolute and the spec authority and path will replace the
 491      * context authority and path. If the authority component is absent in the
 492      * spec then the authority of the new URL will be inherited from the
 493      * context.
 494      * <p>
 495      * If the spec's path component begins with a slash character
 496      * &quot;/&quot; then the
 497      * path is treated as absolute and the spec path replaces the context path.
 498      * <p>
 499      * Otherwise, the path is treated as a relative path and is appended to the
 500      * context path, as described in RFC2396. Also, in this case,
 501      * the path is canonicalized through the removal of directory
 502      * changes made by occurrences of &quot;..&quot; and &quot;.&quot;.
 503      * <p>
 504      * For a more detailed description of URL parsing, refer to RFC2396.
 505      *
 506      * @param      context   the context in which to parse the specification.
 507      * @param      spec      the {@code String} to parse as a URL.
 508      * @exception  MalformedURLException  if no protocol is specified, or an
 509      *               unknown protocol is found, or {@code spec} is {@code null},
 510      *               or the parsed URL fails to comply with the specific syntax
 511      *               of the associated protocol.
 512      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
 513      *                  int, java.lang.String)
 514      * @see        java.net.URLStreamHandler
 515      * @see        java.net.URLStreamHandler#parseURL(java.net.URL,
 516      *                  java.lang.String, int, int)
 517      */
 518     public URL(URL context, String spec) throws MalformedURLException {
 519         this(context, spec, null);
 520     }
 521 
 522     /**
 523      * Creates a URL by parsing the given spec with the specified handler
 524      * within a specified context. If the handler is null, the parsing
 525      * occurs as with the two argument constructor.
 526      *
 527      * @param      context   the context in which to parse the specification.
 528      * @param      spec      the {@code String} to parse as a URL.
 529      * @param      handler   the stream handler for the URL.
 530      * @exception  MalformedURLException  if no protocol is specified, or an
 531      *               unknown protocol is found, or {@code spec} is {@code null},
 532      *               or the parsed URL fails to comply with the specific syntax
 533      *               of the associated protocol.
 534      * @exception  SecurityException
 535      *        if a security manager exists and its
 536      *        {@code checkPermission} method doesn't allow
 537      *        specifying a stream handler.
 538      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
 539      *                  int, java.lang.String)
 540      * @see        java.net.URLStreamHandler
 541      * @see        java.net.URLStreamHandler#parseURL(java.net.URL,
 542      *                  java.lang.String, int, int)
 543      */
 544     public URL(URL context, String spec, URLStreamHandler handler)
 545         throws MalformedURLException
 546     {
 547         String original = spec;
 548         int i, limit, c;
 549         int start = 0;
 550         String newProtocol = null;
 551         boolean aRef=false;
 552         boolean isRelative = false;
 553 
 554         // Check for permission to specify a handler
 555         if (handler != null) {
 556             SecurityManager sm = System.getSecurityManager();
 557             if (sm != null) {
 558                 checkSpecifyHandler(sm);
 559             }
 560         }
 561 
 562         try {
 563             limit = spec.length();
 564             while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) {
 565                 limit--;        //eliminate trailing whitespace
 566             }
 567             while ((start < limit) && (spec.charAt(start) <= ' ')) {
 568                 start++;        // eliminate leading whitespace
 569             }
 570 
 571             if (spec.regionMatches(true, start, "url:", 0, 4)) {
 572                 start += 4;
 573             }
 574             if (start < spec.length() && spec.charAt(start) == '#') {
 575                 /* we're assuming this is a ref relative to the context URL.
 576                  * This means protocols cannot start w/ '#', but we must parse
 577                  * ref URL's like: "hello:there" w/ a ':' in them.
 578                  */
 579                 aRef=true;
 580             }
 581             for (i = start ; !aRef && (i < limit) &&
 582                      ((c = spec.charAt(i)) != '/') ; i++) {
 583                 if (c == ':') {
 584                     String s = spec.substring(start, i).toLowerCase(Locale.ROOT);
 585                     if (isValidProtocol(s)) {
 586                         newProtocol = s;
 587                         start = i + 1;
 588                     }
 589                     break;
 590                 }
 591             }
 592 
 593             // Only use our context if the protocols match.
 594             protocol = newProtocol;
 595             if ((context != null) && ((newProtocol == null) ||
 596                             newProtocol.equalsIgnoreCase(context.protocol))) {
 597                 // inherit the protocol handler from the context
 598                 // if not specified to the constructor
 599                 if (handler == null) {
 600                     handler = context.handler;
 601                 }
 602 
 603                 // If the context is a hierarchical URL scheme and the spec
 604                 // contains a matching scheme then maintain backwards
 605                 // compatibility and treat it as if the spec didn't contain
 606                 // the scheme; see 5.2.3 of RFC2396
 607                 if (context.path != null && context.path.startsWith("/"))
 608                     newProtocol = null;
 609 
 610                 if (newProtocol == null) {
 611                     protocol = context.protocol;
 612                     authority = context.authority;
 613                     userInfo = context.userInfo;
 614                     host = context.host;
 615                     port = context.port;
 616                     file = context.file;
 617                     path = context.path;
 618                     isRelative = true;
 619                 }
 620             }
 621 
 622             if (protocol == null) {
 623                 throw new MalformedURLException("no protocol: "+original);
 624             }
 625 
 626             // Get the protocol handler if not specified or the protocol
 627             // of the context could not be used
 628             if (handler == null &&
 629                 (handler = getURLStreamHandler(protocol)) == null) {
 630                 throw new MalformedURLException("unknown protocol: "+protocol);
 631             }
 632 
 633             this.handler = handler;
 634 
 635             i = spec.indexOf('#', start);
 636             if (i >= 0) {
 637                 ref = spec.substring(i + 1, limit);
 638                 limit = i;
 639             }
 640 
 641             /*
 642              * Handle special case inheritance of query and fragment
 643              * implied by RFC2396 section 5.2.2.
 644              */
 645             if (isRelative && start == limit) {
 646                 query = context.query;
 647                 if (ref == null) {
 648                     ref = context.ref;
 649                 }
 650             }
 651 
 652             handler.parseURL(this, spec, start, limit);
 653 
 654         } catch(MalformedURLException e) {
 655             throw e;
 656         } catch(Exception e) {
 657             MalformedURLException exception = new MalformedURLException(e.getMessage());
 658             exception.initCause(e);
 659             throw exception;
 660         }
 661     }
 662 
 663     /**
 664      * Creates a URL from a URI, as if by invoking {@code uri.toURL()}.
 665      *
 666      * @see java.net.URI#toURL()
 667      */
 668     static URL fromURI(URI uri) throws MalformedURLException {
 669         if (!uri.isAbsolute()) {
 670             throw new IllegalArgumentException("URI is not absolute");
 671         }
 672         String protocol = uri.getScheme();
 673 
 674         // In general we need to go via Handler.parseURL, but for the jrt
 675         // protocol we enforce that the Handler is not overrideable and can
 676         // optimize URI to URL conversion.
 677         //
 678         // Case-sensitive comparison for performance; malformed protocols will
 679         // be handled correctly by the slow path.
 680         if (protocol.equals("jrt") && !uri.isOpaque()
 681                 && uri.getRawFragment() == null) {
 682 
 683             String query = uri.getRawQuery();
 684             String path = uri.getRawPath();
 685             String file = (query == null) ? path : path + "?" + query;
 686 
 687             // URL represent undefined host as empty string while URI use null
 688             String host = uri.getHost();
 689             if (host == null) {
 690                 host = "";
 691             }
 692 
 693             int port = uri.getPort();
 694 
 695             return new URL("jrt", host, port, file, null);
 696         } else {
 697             return new URL((URL)null, uri.toString(), null);
 698         }
 699     }
 700 
 701     /*
 702      * Returns true if specified string is a valid protocol name.
 703      */
 704     private boolean isValidProtocol(String protocol) {
 705         int len = protocol.length();
 706         if (len < 1)
 707             return false;
 708         char c = protocol.charAt(0);
 709         if (!Character.isLetter(c))
 710             return false;
 711         for (int i = 1; i < len; i++) {
 712             c = protocol.charAt(i);
 713             if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' &&
 714                 c != '-') {
 715                 return false;
 716             }
 717         }
 718         return true;
 719     }
 720 
 721     /*
 722      * Checks for permission to specify a stream handler.
 723      */
 724     private void checkSpecifyHandler(SecurityManager sm) {
 725         sm.checkPermission(SecurityConstants.SPECIFY_HANDLER_PERMISSION);
 726     }
 727 
 728     /**
 729      * Sets the fields of the URL. This is not a public method so that
 730      * only URLStreamHandlers can modify URL fields. URLs are
 731      * otherwise constant.
 732      *
 733      * @param protocol the name of the protocol to use
 734      * @param host the name of the host
 735        @param port the port number on the host
 736      * @param file the file on the host
 737      * @param ref the internal reference in the URL
 738      */
 739     void set(String protocol, String host, int port,
 740              String file, String ref) {
 741         synchronized (this) {
 742             this.protocol = protocol;
 743             this.host = host;
 744             authority = port == -1 ? host : host + ":" + port;
 745             this.port = port;
 746             this.file = file;
 747             this.ref = ref;
 748             /* This is very important. We must recompute this after the
 749              * URL has been changed. */
 750             hashCode = -1;
 751             hostAddress = null;
 752             int q = file.lastIndexOf('?');
 753             if (q != -1) {
 754                 query = file.substring(q+1);
 755                 path = file.substring(0, q);
 756             } else
 757                 path = file;
 758         }
 759     }
 760 
 761     /**
 762      * Sets the specified 8 fields of the URL. This is not a public method so
 763      * that only URLStreamHandlers can modify URL fields. URLs are otherwise
 764      * constant.
 765      *
 766      * @param protocol the name of the protocol to use
 767      * @param host the name of the host
 768      * @param port the port number on the host
 769      * @param authority the authority part for the url
 770      * @param userInfo the username and password
 771      * @param path the file on the host
 772      * @param ref the internal reference in the URL
 773      * @param query the query part of this URL
 774      * @since 1.3
 775      */
 776     void set(String protocol, String host, int port,
 777              String authority, String userInfo, String path,
 778              String query, String ref) {
 779         synchronized (this) {
 780             this.protocol = protocol;
 781             this.host = host;
 782             this.port = port;
 783             this.file = query == null ? path : path + "?" + query;
 784             this.userInfo = userInfo;
 785             this.path = path;
 786             this.ref = ref;
 787             /* This is very important. We must recompute this after the
 788              * URL has been changed. */
 789             hashCode = -1;
 790             hostAddress = null;
 791             this.query = query;
 792             this.authority = authority;
 793         }
 794     }
 795 
 796     /**
 797      * Gets the query part of this {@code URL}.
 798      *
 799      * @return  the query part of this {@code URL},
 800      * or <CODE>null</CODE> if one does not exist
 801      * @since 1.3
 802      */
 803     public String getQuery() {
 804         return query;
 805     }
 806 
 807     /**
 808      * Gets the path part of this {@code URL}.
 809      *
 810      * @return  the path part of this {@code URL}, or an
 811      * empty string if one does not exist
 812      * @since 1.3
 813      */
 814     public String getPath() {
 815         return path;
 816     }
 817 
 818     /**
 819      * Gets the userInfo part of this {@code URL}.
 820      *
 821      * @return  the userInfo part of this {@code URL}, or
 822      * <CODE>null</CODE> if one does not exist
 823      * @since 1.3
 824      */
 825     public String getUserInfo() {
 826         return userInfo;
 827     }
 828 
 829     /**
 830      * Gets the authority part of this {@code URL}.
 831      *
 832      * @return  the authority part of this {@code URL}
 833      * @since 1.3
 834      */
 835     public String getAuthority() {
 836         return authority;
 837     }
 838 
 839     /**
 840      * Gets the port number of this {@code URL}.
 841      *
 842      * @return  the port number, or -1 if the port is not set
 843      */
 844     public int getPort() {
 845         return port;
 846     }
 847 
 848     /**
 849      * Gets the default port number of the protocol associated
 850      * with this {@code URL}. If the URL scheme or the URLStreamHandler
 851      * for the URL do not define a default port number,
 852      * then -1 is returned.
 853      *
 854      * @return  the port number
 855      * @since 1.4
 856      */
 857     public int getDefaultPort() {
 858         return handler.getDefaultPort();
 859     }
 860 
 861     /**
 862      * Gets the protocol name of this {@code URL}.
 863      *
 864      * @return  the protocol of this {@code URL}.
 865      */
 866     public String getProtocol() {
 867         return protocol;
 868     }
 869 
 870     /**
 871      * Gets the host name of this {@code URL}, if applicable.
 872      * The format of the host conforms to RFC 2732, i.e. for a
 873      * literal IPv6 address, this method will return the IPv6 address
 874      * enclosed in square brackets ({@code '['} and {@code ']'}).
 875      *
 876      * @return  the host name of this {@code URL}.
 877      */
 878     public String getHost() {
 879         return host;
 880     }
 881 
 882     /**
 883      * Gets the file name of this {@code URL}.
 884      * The returned file portion will be
 885      * the same as <CODE>getPath()</CODE>, plus the concatenation of
 886      * the value of <CODE>getQuery()</CODE>, if any. If there is
 887      * no query portion, this method and <CODE>getPath()</CODE> will
 888      * return identical results.
 889      *
 890      * @return  the file name of this {@code URL},
 891      * or an empty string if one does not exist
 892      */
 893     public String getFile() {
 894         return file;
 895     }
 896 
 897     /**
 898      * Gets the anchor (also known as the "reference") of this
 899      * {@code URL}.
 900      *
 901      * @return  the anchor (also known as the "reference") of this
 902      *          {@code URL}, or <CODE>null</CODE> if one does not exist
 903      */
 904     public String getRef() {
 905         return ref;
 906     }
 907 
 908     /**
 909      * Compares this URL for equality with another object.<p>
 910      *
 911      * If the given object is not a URL then this method immediately returns
 912      * {@code false}.<p>
 913      *
 914      * Two URL objects are equal if they have the same protocol, reference
 915      * equivalent hosts, have the same port number on the host, and the same
 916      * file and fragment of the file.<p>
 917      *
 918      * Two hosts are considered equivalent if both host names can be resolved
 919      * into the same IP addresses; else if either host name can't be
 920      * resolved, the host names must be equal without regard to case; or both
 921      * host names equal to null.<p>
 922      *
 923      * Since hosts comparison requires name resolution, this operation is a
 924      * blocking operation. <p>
 925      *
 926      * Note: The defined behavior for {@code equals} is known to
 927      * be inconsistent with virtual hosting in HTTP.
 928      *
 929      * @param   obj   the URL to compare against.
 930      * @return  {@code true} if the objects are the same;
 931      *          {@code false} otherwise.
 932      */
 933     public boolean equals(Object obj) {
 934         if (!(obj instanceof URL))
 935             return false;
 936         URL u2 = (URL)obj;
 937 
 938         return handler.equals(this, u2);
 939     }
 940 
 941     /**
 942      * Creates an integer suitable for hash table indexing.<p>
 943      *
 944      * The hash code is based upon all the URL components relevant for URL
 945      * comparison. As such, this operation is a blocking operation.
 946      *
 947      * @return  a hash code for this {@code URL}.
 948      */
 949     public synchronized int hashCode() {
 950         if (hashCode != -1)
 951             return hashCode;
 952 
 953         hashCode = handler.hashCode(this);
 954         return hashCode;
 955     }
 956 
 957     /**
 958      * Compares two URLs, excluding the fragment component.<p>
 959      *
 960      * Returns {@code true} if this {@code URL} and the
 961      * {@code other} argument are equal without taking the
 962      * fragment component into consideration.
 963      *
 964      * @param   other   the {@code URL} to compare against.
 965      * @return  {@code true} if they reference the same remote object;
 966      *          {@code false} otherwise.
 967      */
 968     public boolean sameFile(URL other) {
 969         return handler.sameFile(this, other);
 970     }
 971 
 972     /**
 973      * Constructs a string representation of this {@code URL}. The
 974      * string is created by calling the {@code toExternalForm}
 975      * method of the stream protocol handler for this object.
 976      *
 977      * @return  a string representation of this object.
 978      * @see     java.net.URL#URL(java.lang.String, java.lang.String, int,
 979      *                  java.lang.String)
 980      * @see     java.net.URLStreamHandler#toExternalForm(java.net.URL)
 981      */
 982     public String toString() {
 983         return toExternalForm();
 984     }
 985 
 986     /**
 987      * Constructs a string representation of this {@code URL}. The
 988      * string is created by calling the {@code toExternalForm}
 989      * method of the stream protocol handler for this object.
 990      *
 991      * @return  a string representation of this object.
 992      * @see     java.net.URL#URL(java.lang.String, java.lang.String,
 993      *                  int, java.lang.String)
 994      * @see     java.net.URLStreamHandler#toExternalForm(java.net.URL)
 995      */
 996     public String toExternalForm() {
 997         return handler.toExternalForm(this);
 998     }
 999 
1000     /**
1001      * Returns a {@link java.net.URI} equivalent to this URL.
1002      * This method functions in the same way as {@code new URI (this.toString())}.
1003      * <p>Note, any URL instance that complies with RFC 2396 can be converted
1004      * to a URI. However, some URLs that are not strictly in compliance
1005      * can not be converted to a URI.
1006      *
1007      * @exception URISyntaxException if this URL is not formatted strictly according to
1008      *            to RFC2396 and cannot be converted to a URI.
1009      *
1010      * @return    a URI instance equivalent to this URL.
1011      * @since 1.5
1012      */
1013     public URI toURI() throws URISyntaxException {
1014         return new URI (toString());
1015     }
1016 
1017     /**
1018      * Returns a {@link java.net.URLConnection URLConnection} instance that
1019      * represents a connection to the remote object referred to by the
1020      * {@code URL}.
1021      *
1022      * <P>A new instance of {@linkplain java.net.URLConnection URLConnection} is
1023      * created every time when invoking the
1024      * {@linkplain java.net.URLStreamHandler#openConnection(URL)
1025      * URLStreamHandler.openConnection(URL)} method of the protocol handler for
1026      * this URL.</P>
1027      *
1028      * <P>It should be noted that a URLConnection instance does not establish
1029      * the actual network connection on creation. This will happen only when
1030      * calling {@linkplain java.net.URLConnection#connect() URLConnection.connect()}.</P>
1031      *
1032      * <P>If for the URL's protocol (such as HTTP or JAR), there
1033      * exists a public, specialized URLConnection subclass belonging
1034      * to one of the following packages or one of their subpackages:
1035      * java.lang, java.io, java.util, java.net, the connection
1036      * returned will be of that subclass. For example, for HTTP an
1037      * HttpURLConnection will be returned, and for JAR a
1038      * JarURLConnection will be returned.</P>
1039      *
1040      * @return     a {@link java.net.URLConnection URLConnection} linking
1041      *             to the URL.
1042      * @exception  IOException  if an I/O exception occurs.
1043      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1044      *             int, java.lang.String)
1045      */
1046     public URLConnection openConnection() throws java.io.IOException {
1047         return handler.openConnection(this);
1048     }
1049 
1050     /**
1051      * Same as {@link #openConnection()}, except that the connection will be
1052      * made through the specified proxy; Protocol handlers that do not
1053      * support proxing will ignore the proxy parameter and make a
1054      * normal connection.
1055      *
1056      * Invoking this method preempts the system's default
1057      * {@link java.net.ProxySelector ProxySelector} settings.
1058      *
1059      * @param      proxy the Proxy through which this connection
1060      *             will be made. If direct connection is desired,
1061      *             Proxy.NO_PROXY should be specified.
1062      * @return     a {@code URLConnection} to the URL.
1063      * @exception  IOException  if an I/O exception occurs.
1064      * @exception  SecurityException if a security manager is present
1065      *             and the caller doesn't have permission to connect
1066      *             to the proxy.
1067      * @exception  IllegalArgumentException will be thrown if proxy is null,
1068      *             or proxy has the wrong type
1069      * @exception  UnsupportedOperationException if the subclass that
1070      *             implements the protocol handler doesn't support
1071      *             this method.
1072      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1073      *             int, java.lang.String)
1074      * @see        java.net.URLConnection
1075      * @see        java.net.URLStreamHandler#openConnection(java.net.URL,
1076      *             java.net.Proxy)
1077      * @since      1.5
1078      */
1079     public URLConnection openConnection(Proxy proxy)
1080         throws java.io.IOException {
1081         if (proxy == null) {
1082             throw new IllegalArgumentException("proxy can not be null");
1083         }
1084 
1085         // Create a copy of Proxy as a security measure
1086         Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy);
1087         SecurityManager sm = System.getSecurityManager();
1088         if (p.type() != Proxy.Type.DIRECT && sm != null) {
1089             InetSocketAddress epoint = (InetSocketAddress) p.address();
1090             if (epoint.isUnresolved())
1091                 sm.checkConnect(epoint.getHostName(), epoint.getPort());
1092             else
1093                 sm.checkConnect(epoint.getAddress().getHostAddress(),
1094                                 epoint.getPort());
1095         }
1096         return handler.openConnection(this, p);
1097     }
1098 
1099     /**
1100      * Opens a connection to this {@code URL} and returns an
1101      * {@code InputStream} for reading from that connection. This
1102      * method is a shorthand for:
1103      * <blockquote><pre>
1104      *     openConnection().getInputStream()
1105      * </pre></blockquote>
1106      *
1107      * @return     an input stream for reading from the URL connection.
1108      * @exception  IOException  if an I/O exception occurs.
1109      * @see        java.net.URL#openConnection()
1110      * @see        java.net.URLConnection#getInputStream()
1111      */
1112     public final InputStream openStream() throws java.io.IOException {
1113         return openConnection().getInputStream();
1114     }
1115 
1116     /**
1117      * Gets the contents of this URL. This method is a shorthand for:
1118      * <blockquote><pre>
1119      *     openConnection().getContent()
1120      * </pre></blockquote>
1121      *
1122      * @return     the contents of this URL.
1123      * @exception  IOException  if an I/O exception occurs.
1124      * @see        java.net.URLConnection#getContent()
1125      */
1126     public final Object getContent() throws java.io.IOException {
1127         return openConnection().getContent();
1128     }
1129 
1130     /**
1131      * Gets the contents of this URL. This method is a shorthand for:
1132      * <blockquote><pre>
1133      *     openConnection().getContent(classes)
1134      * </pre></blockquote>
1135      *
1136      * @param classes an array of Java types
1137      * @return     the content object of this URL that is the first match of
1138      *               the types specified in the classes array.
1139      *               null if none of the requested types are supported.
1140      * @exception  IOException  if an I/O exception occurs.
1141      * @see        java.net.URLConnection#getContent(Class[])
1142      * @since 1.3
1143      */
1144     public final Object getContent(Class<?>[] classes)
1145     throws java.io.IOException {
1146         return openConnection().getContent(classes);
1147     }
1148 
1149     /**
1150      * The URLStreamHandler factory.
1151      */
1152     private static volatile URLStreamHandlerFactory factory;
1153 
1154     /**
1155      * Sets an application's {@code URLStreamHandlerFactory}.
1156      * This method can be called at most once in a given Java Virtual
1157      * Machine.
1158      *
1159      *<p> The {@code URLStreamHandlerFactory} instance is used to
1160      *construct a stream protocol handler from a protocol name.
1161      *
1162      * <p> If there is a security manager, this method first calls
1163      * the security manager's {@code checkSetFactory} method
1164      * to ensure the operation is allowed.
1165      * This could result in a SecurityException.
1166      *
1167      * @param      fac   the desired factory.
1168      * @exception  Error  if the application has already set a factory.
1169      * @exception  SecurityException  if a security manager exists and its
1170      *             {@code checkSetFactory} method doesn't allow
1171      *             the operation.
1172      * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1173      *             int, java.lang.String)
1174      * @see        java.net.URLStreamHandlerFactory
1175      * @see        SecurityManager#checkSetFactory
1176      */
1177     public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) {
1178         synchronized (streamHandlerLock) {
1179             if (factory != null) {
1180                 throw new Error("factory already defined");
1181             }
1182             SecurityManager security = System.getSecurityManager();
1183             if (security != null) {
1184                 security.checkSetFactory();
1185             }
1186             handlers.clear();
1187 
1188             // safe publication of URLStreamHandlerFactory with volatile write
1189             factory = fac;
1190         }
1191     }
1192 
1193     private static final URLStreamHandlerFactory defaultFactory = new DefaultFactory();
1194 
1195     private static class DefaultFactory implements URLStreamHandlerFactory {
1196         private static String PREFIX = "sun.net.www.protocol";
1197 
1198         public URLStreamHandler createURLStreamHandler(String protocol) {
1199             String name = PREFIX + "." + protocol + ".Handler";
1200             try {
1201                 Class<?> c = Class.forName(name);
1202                 return (URLStreamHandler)c.newInstance();
1203             } catch (ClassNotFoundException x) {
1204                 // ignore
1205             } catch (Exception e) {
1206                 // For compatibility, all Exceptions are ignored.
1207                 // any number of exceptions can get thrown here
1208             }
1209             return null;
1210         }
1211     }
1212 
1213     private static URLStreamHandler lookupViaProperty(String protocol) {
1214         String packagePrefixList =
1215                 GetPropertyAction.getProperty(protocolPathProp);




1216         if (packagePrefixList == null) {
1217             // not set
1218             return null;
1219         }
1220 
1221         String[] packagePrefixes = packagePrefixList.split("\\|");
1222         URLStreamHandler handler = null;
1223         for (int i=0; handler == null && i<packagePrefixes.length; i++) {
1224             String packagePrefix = packagePrefixes[i].trim();
1225             try {
1226                 String clsName = packagePrefix + "." + protocol + ".Handler";
1227                 Class<?> cls = null;
1228                 try {
1229                     cls = Class.forName(clsName);
1230                 } catch (ClassNotFoundException e) {
1231                     ClassLoader cl = ClassLoader.getSystemClassLoader();
1232                     if (cl != null) {
1233                         cls = cl.loadClass(clsName);
1234                     }
1235                 }
1236                 if (cls != null) {
1237                     handler = (URLStreamHandler)cls.newInstance();
1238                 }
1239             } catch (Exception e) {
1240                 // any number of exceptions can get thrown here
1241             }
1242         }
1243         return handler;
1244     }
1245 
1246     private static Iterator<URLStreamHandlerProvider> providers() {
1247         return new Iterator<>() {
1248 
1249             ClassLoader cl = ClassLoader.getSystemClassLoader();
1250             ServiceLoader<URLStreamHandlerProvider> sl =
1251                     ServiceLoader.load(URLStreamHandlerProvider.class, cl);
1252             Iterator<URLStreamHandlerProvider> i = sl.iterator();
1253 
1254             URLStreamHandlerProvider next = null;
1255 
1256             private boolean getNext() {
1257                 while (next == null) {
1258                     try {
1259                         if (!i.hasNext())
1260                             return false;
1261                         next = i.next();
1262                     } catch (ServiceConfigurationError sce) {
1263                         if (sce.getCause() instanceof SecurityException) {
1264                             // Ignore security exceptions
1265                             continue;
1266                         }
1267                         throw sce;
1268                     }
1269                 }
1270                 return true;
1271             }
1272 
1273             public boolean hasNext() {
1274                 return getNext();
1275             }
1276 
1277             public URLStreamHandlerProvider next() {
1278                 if (!getNext())
1279                     throw new NoSuchElementException();
1280                 URLStreamHandlerProvider n = next;
1281                 next = null;
1282                 return n;
1283             }
1284         };
1285     }
1286 
1287     // Thread-local gate to prevent recursive provider lookups
1288     private static ThreadLocal<Object> gate = new ThreadLocal<>();
1289 
1290     private static URLStreamHandler lookupViaProviders(final String protocol) {
1291         if (gate.get() != null)
1292             throw new Error("Circular loading of URL stream handler providers detected");
1293 
1294         gate.set(gate);
1295         try {
1296             return AccessController.doPrivileged(
1297                 new PrivilegedAction<>() {
1298                     public URLStreamHandler run() {
1299                         Iterator<URLStreamHandlerProvider> itr = providers();
1300                         while (itr.hasNext()) {
1301                             URLStreamHandlerProvider f = itr.next();
1302                             URLStreamHandler h = f.createURLStreamHandler(protocol);
1303                             if (h != null)
1304                                 return h;
1305                         }
1306                         return null;
1307                     }
1308                 });
1309         } finally {
1310             gate.set(null);
1311         }
1312     }
1313 
1314 
1315     /**
1316      * Non-overrideable protocols: "jrt" and "file"
1317      *
1318      * Character-based comparison for performance reasons; also ensures
1319      * case-insensitive comparison in a locale-independent fashion.
1320      */
1321     static boolean isOverrideable(String protocol) {
1322         if (protocol.length() == 3) {
1323             if ((Character.toLowerCase(protocol.charAt(0)) == 'j') &&
1324                     (Character.toLowerCase(protocol.charAt(1)) == 'r') &&
1325                     (Character.toLowerCase(protocol.charAt(2)) == 't')) {
1326                 return false;
1327             }
1328         } else if (protocol.length() == 4) {
1329             if ((Character.toLowerCase(protocol.charAt(0)) == 'f') &&
1330                     (Character.toLowerCase(protocol.charAt(1)) == 'i') &&
1331                     (Character.toLowerCase(protocol.charAt(2)) == 'l') &&
1332                     (Character.toLowerCase(protocol.charAt(3)) == 'e')) {
1333                 return false;
1334             }
1335         }
1336         return true;
1337     }
1338 
1339     /**
1340      * A table of protocol handlers.
1341      */
1342     static Hashtable<String,URLStreamHandler> handlers = new Hashtable<>();
1343     private static final Object streamHandlerLock = new Object();
1344 
1345     /**
1346      * Returns the Stream Handler.
1347      * @param protocol the protocol to use
1348      */
1349     static URLStreamHandler getURLStreamHandler(String protocol) {
1350 
1351         URLStreamHandler handler = handlers.get(protocol);
1352 
1353         if (handler != null) {
1354             return handler;
1355         }
1356 
1357         URLStreamHandlerFactory fac;
1358         boolean checkedWithFactory = false;
1359 
1360         if (isOverrideable(protocol) && jdk.internal.misc.VM.isBooted()) {
1361             // Use the factory (if any). Volatile read makes
1362             // URLStreamHandlerFactory appear fully initialized to current thread.
1363             fac = factory;
1364             if (fac != null) {
1365                 handler = fac.createURLStreamHandler(protocol);
1366                 checkedWithFactory = true;
1367             }
1368 
1369             if (handler == null && !protocol.equalsIgnoreCase("jar")) {
1370                 handler = lookupViaProviders(protocol);
1371             }
1372 
1373             if (handler == null) {
1374                 handler = lookupViaProperty(protocol);
1375             }
1376         }
1377 
1378         synchronized (streamHandlerLock) {
1379             if (handler == null) {
1380                 // Try the built-in protocol handler
1381                 handler = defaultFactory.createURLStreamHandler(protocol);
1382             } else {
1383                 URLStreamHandler handler2 = null;
1384 
1385                 // Check again with hashtable just in case another
1386                 // thread created a handler since we last checked
1387                 handler2 = handlers.get(protocol);
1388 
1389                 if (handler2 != null) {
1390                     return handler2;
1391                 }
1392 
1393                 // Check with factory if another thread set a
1394                 // factory since our last check
1395                 if (!checkedWithFactory && (fac = factory) != null) {
1396                     handler2 =  fac.createURLStreamHandler(protocol);
1397                 }
1398 
1399                 if (handler2 != null) {
1400                     // The handler from the factory must be given more
1401                     // importance. Discard the default handler that
1402                     // this thread created.
1403                     handler = handler2;
1404                 }
1405             }
1406 
1407             // Insert this handler into the hashtable
1408             if (handler != null) {
1409                 handlers.put(protocol, handler);
1410             }
1411         }
1412 
1413         return handler;
1414     }
1415 
1416     /**
1417      * @serialField    protocol String
1418      *
1419      * @serialField    host String
1420      *
1421      * @serialField    port int
1422      *
1423      * @serialField    authority String
1424      *
1425      * @serialField    file String
1426      *
1427      * @serialField    ref String
1428      *
1429      * @serialField    hashCode int
1430      *
1431      */
1432     private static final ObjectStreamField[] serialPersistentFields = {
1433         new ObjectStreamField("protocol", String.class),
1434         new ObjectStreamField("host", String.class),
1435         new ObjectStreamField("port", int.class),
1436         new ObjectStreamField("authority", String.class),
1437         new ObjectStreamField("file", String.class),
1438         new ObjectStreamField("ref", String.class),
1439         new ObjectStreamField("hashCode", int.class), };
1440 
1441     /**
1442      * WriteObject is called to save the state of the URL to an
1443      * ObjectOutputStream. The handler is not saved since it is
1444      * specific to this system.
1445      *
1446      * @serialData the default write object value. When read back in,
1447      * the reader must ensure that calling getURLStreamHandler with
1448      * the protocol variable returns a valid URLStreamHandler and
1449      * throw an IOException if it does not.
1450      */
1451     private synchronized void writeObject(java.io.ObjectOutputStream s)
1452         throws IOException
1453     {
1454         s.defaultWriteObject(); // write the fields
1455     }
1456 
1457     /**
1458      * readObject is called to restore the state of the URL from the
1459      * stream.  It reads the components of the URL and finds the local
1460      * stream handler.
1461      */
1462     private synchronized void readObject(java.io.ObjectInputStream s)
1463             throws IOException, ClassNotFoundException {
1464         GetField gf = s.readFields();
1465         String protocol = (String)gf.get("protocol", null);
1466         if (getURLStreamHandler(protocol) == null) {
1467             throw new IOException("unknown protocol: " + protocol);
1468         }
1469         String host = (String)gf.get("host", null);
1470         int port = gf.get("port", -1);
1471         String authority = (String)gf.get("authority", null);
1472         String file = (String)gf.get("file", null);
1473         String ref = (String)gf.get("ref", null);
1474         int hashCode = gf.get("hashCode", -1);
1475         if (authority == null
1476                 && ((host != null && host.length() > 0) || port != -1)) {
1477             if (host == null)
1478                 host = "";
1479             authority = (port == -1) ? host : host + ":" + port;
1480         }
1481         tempState = new UrlDeserializedState(protocol, host, port, authority,
1482                file, ref, hashCode);
1483     }
1484 
1485     /**
1486      * Replaces the de-serialized object with an URL object.
1487      *
1488      * @return a newly created object from deserialized data
1489      *
1490      * @throws ObjectStreamException if a new object replacing this
1491      * object could not be created
1492      */
1493 
1494    private Object readResolve() throws ObjectStreamException {
1495 
1496         URLStreamHandler handler = null;
1497         // already been checked in readObject
1498         handler = getURLStreamHandler(tempState.getProtocol());
1499 
1500         URL replacementURL = null;
1501         if (isBuiltinStreamHandler(handler.getClass().getName())) {
1502             replacementURL = fabricateNewURL();
1503         } else {
1504             replacementURL = setDeserializedFields(handler);
1505         }
1506         return replacementURL;
1507     }
1508 
1509     private URL setDeserializedFields(URLStreamHandler handler) {
1510         URL replacementURL;
1511         String userInfo = null;
1512         String protocol = tempState.getProtocol();
1513         String host = tempState.getHost();
1514         int port = tempState.getPort();
1515         String authority = tempState.getAuthority();
1516         String file = tempState.getFile();
1517         String ref = tempState.getRef();
1518         int hashCode = tempState.getHashCode();
1519 
1520 
1521         // Construct authority part
1522         if (authority == null
1523             && ((host != null && host.length() > 0) || port != -1)) {
1524             if (host == null)
1525                 host = "";
1526             authority = (port == -1) ? host : host + ":" + port;
1527 
1528             // Handle hosts with userInfo in them
1529             int at = host.lastIndexOf('@');
1530             if (at != -1) {
1531                 userInfo = host.substring(0, at);
1532                 host = host.substring(at+1);
1533             }
1534         } else if (authority != null) {
1535             // Construct user info part
1536             int ind = authority.indexOf('@');
1537             if (ind != -1)
1538                 userInfo = authority.substring(0, ind);
1539         }
1540 
1541         // Construct path and query part
1542         String path = null;
1543         String query = null;
1544         if (file != null) {
1545             // Fix: only do this if hierarchical?
1546             int q = file.lastIndexOf('?');
1547             if (q != -1) {
1548                 query = file.substring(q+1);
1549                 path = file.substring(0, q);
1550             } else
1551                 path = file;
1552         }
1553 
1554         if (port == -1) {
1555             port = 0;
1556         }
1557         // Set the object fields.
1558         this.protocol = protocol;
1559         this.host = host;
1560         this.port = port;
1561         this.file = file;
1562         this.authority = authority;
1563         this.ref = ref;
1564         this.hashCode = hashCode;
1565         this.handler = handler;
1566         this.query = query;
1567         this.path = path;
1568         this.userInfo = userInfo;
1569         replacementURL = this;
1570         return replacementURL;
1571     }
1572 
1573     private URL fabricateNewURL()
1574                 throws InvalidObjectException {
1575         // create URL string from deserialized object
1576         URL replacementURL = null;
1577         String urlString = tempState.reconstituteUrlString();
1578 
1579         try {
1580             replacementURL = new URL(urlString);
1581         } catch (MalformedURLException mEx) {
1582             resetState();
1583             InvalidObjectException invoEx = new InvalidObjectException(
1584                     "Malformed URL:  " + urlString);
1585             invoEx.initCause(mEx);
1586             throw invoEx;
1587         }
1588         replacementURL.setSerializedHashCode(tempState.getHashCode());
1589         resetState();
1590         return replacementURL;
1591     }
1592 
1593     private boolean isBuiltinStreamHandler(String handlerClassName) {
1594         return (handlerClassName.startsWith(BUILTIN_HANDLERS_PREFIX));
1595     }
1596 
1597     private void resetState() {
1598         this.protocol = null;
1599         this.host = null;
1600         this.port = -1;
1601         this.file = null;
1602         this.authority = null;
1603         this.ref = null;
1604         this.hashCode = -1;
1605         this.handler = null;
1606         this.query = null;
1607         this.path = null;
1608         this.userInfo = null;
1609         this.tempState = null;
1610     }
1611 
1612     private void setSerializedHashCode(int hc) {
1613         this.hashCode = hc;
1614     }
1615 }
1616 
1617 class Parts {
1618     String path, query, ref;
1619 
1620     Parts(String file) {
1621         int ind = file.indexOf('#');
1622         ref = ind < 0 ? null: file.substring(ind + 1);
1623         file = ind < 0 ? file: file.substring(0, ind);
1624         int q = file.lastIndexOf('?');
1625         if (q != -1) {
1626             query = file.substring(q+1);
1627             path = file.substring(0, q);
1628         } else {
1629             path = file;
1630         }
1631     }
1632 
1633     String getPath() {
1634         return path;
1635     }
1636 
1637     String getQuery() {
1638         return query;
1639     }
1640 
1641     String getRef() {
1642         return ref;
1643     }
1644 }
1645 
1646 final class UrlDeserializedState {
1647     private final String protocol;
1648     private final String host;
1649     private final int port;
1650     private final String authority;
1651     private final String file;
1652     private final String ref;
1653     private final int hashCode;
1654 
1655     public UrlDeserializedState(String protocol,
1656                                 String host, int port,
1657                                 String authority, String file,
1658                                 String ref, int hashCode) {
1659         this.protocol = protocol;
1660         this.host = host;
1661         this.port = port;
1662         this.authority = authority;
1663         this.file = file;
1664         this.ref = ref;
1665         this.hashCode = hashCode;
1666     }
1667 
1668     String getProtocol() {
1669         return protocol;
1670     }
1671 
1672     String getHost() {
1673         return host;
1674     }
1675 
1676     String getAuthority () {
1677         return authority;
1678     }
1679 
1680     int getPort() {
1681         return port;
1682     }
1683 
1684     String getFile () {
1685         return file;
1686     }
1687 
1688     String getRef () {
1689         return ref;
1690     }
1691 
1692     int getHashCode () {
1693         return hashCode;
1694     }
1695 
1696     String reconstituteUrlString() {
1697 
1698         // pre-compute length of StringBuffer
1699         int len = protocol.length() + 1;
1700         if (authority != null && authority.length() > 0)
1701             len += 2 + authority.length();
1702         if (file != null) {
1703             len += file.length();
1704         }
1705         if (ref != null)
1706             len += 1 + ref.length();
1707         StringBuilder result = new StringBuilder(len);
1708         result.append(protocol);
1709         result.append(":");
1710         if (authority != null && authority.length() > 0) {
1711             result.append("//");
1712             result.append(authority);
1713         }
1714         if (file != null) {
1715             result.append(file);
1716         }
1717         if (ref != null) {
1718             result.append("#");
1719             result.append(ref);
1720         }
1721         return result.toString();
1722     }
1723 }
--- EOF ---