1/*
2 * Copyright (c) 1995, 2017, 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 java.net;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.net.spi.URLStreamHandlerProvider;
31import java.security.AccessController;
32import java.security.PrivilegedAction;
33import java.util.Hashtable;
34import java.io.InvalidObjectException;
35import java.io.ObjectStreamException;
36import java.io.ObjectStreamField;
37import java.io.ObjectInputStream.GetField;
38import java.util.Iterator;
39import java.util.Locale;
40import java.util.NoSuchElementException;
41import java.util.ServiceConfigurationError;
42import java.util.ServiceLoader;
43
44import jdk.internal.misc.JavaNetURLAccess;
45import jdk.internal.misc.SharedSecrets;
46import sun.security.util.SecurityConstants;
47import sun.security.action.GetPropertyAction;
48
49/**
50 * Class {@code URL} represents a Uniform Resource
51 * Locator, a pointer to a "resource" on the World
52 * Wide Web. A resource can be something as simple as a file or a
53 * directory, or it can be a reference to a more complicated object,
54 * such as a query to a database or to a search engine. More
55 * information on the types of URLs and their formats can be found at:
56 * <a href=
57 * "http://web.archive.org/web/20051219043731/http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/url-primer.html">
58 * <i>Types of URL</i></a>
59 * <p>
60 * In general, a URL can be broken into several parts. Consider the
61 * following example:
62 * <blockquote><pre>
63 *     http://www.example.com/docs/resource1.html
64 * </pre></blockquote>
65 * <p>
66 * The URL above indicates that the protocol to use is
67 * {@code http} (HyperText Transfer Protocol) and that the
68 * information resides on a host machine named
69 * {@code www.example.com}. The information on that host
70 * machine is named {@code /docs/resource1.html}. The exact
71 * meaning of this name on the host machine is both protocol
72 * dependent and host dependent. The information normally resides in
73 * a file, but it could be generated on the fly. This component of
74 * the URL is called the <i>path</i> component.
75 * <p>
76 * A URL can optionally specify a "port", which is the
77 * port number to which the TCP connection is made on the remote host
78 * machine. If the port is not specified, the default port for
79 * the protocol is used instead. For example, the default port for
80 * {@code http} is {@code 80}. An alternative port could be
81 * specified as:
82 * <blockquote><pre>
83 *     http://www.example.com:1080/docs/resource1.html
84 * </pre></blockquote>
85 * <p>
86 * The syntax of {@code URL} is defined by  <a
87 * href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
88 * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
89 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
90 * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
91 * also supports scope_ids. The syntax and usage of scope_ids is described
92 * <a href="Inet6Address.html#scoped">here</a>.
93 * <p>
94 * A URL may have appended to it a "fragment", also known
95 * as a "ref" or a "reference". The fragment is indicated by the sharp
96 * sign character "#" followed by more characters. For example,
97 * <blockquote><pre>
98 *     http://java.sun.com/index.html#chapter1
99 * </pre></blockquote>
100 * <p>
101 * This fragment is not technically part of the URL. Rather, it
102 * indicates that after the specified resource is retrieved, the
103 * application is specifically interested in that part of the
104 * document that has the tag {@code chapter1} attached to it. The
105 * meaning of a tag is resource specific.
106 * <p>
107 * An application can also specify a "relative URL",
108 * which contains only enough information to reach the resource
109 * relative to another URL. Relative URLs are frequently used within
110 * HTML pages. For example, if the contents of the URL:
111 * <blockquote><pre>
112 *     http://java.sun.com/index.html
113 * </pre></blockquote>
114 * contained within it the relative URL:
115 * <blockquote><pre>
116 *     FAQ.html
117 * </pre></blockquote>
118 * it would be a shorthand for:
119 * <blockquote><pre>
120 *     http://java.sun.com/FAQ.html
121 * </pre></blockquote>
122 * <p>
123 * The relative URL need not specify all the components of a URL. If
124 * the protocol, host name, or port number is missing, the value is
125 * inherited from the fully specified URL. The file component must be
126 * specified. The optional fragment is not inherited.
127 * <p>
128 * The URL class does not itself encode or decode any URL components
129 * according to the escaping mechanism defined in RFC2396. It is the
130 * responsibility of the caller to encode any fields, which need to be
131 * escaped prior to calling URL, and also to decode any escaped fields,
132 * that are returned from URL. Furthermore, because URL has no knowledge
133 * of URL escaping, it does not recognise equivalence between the encoded
134 * or decoded form of the same URL. For example, the two URLs:<br>
135 * <pre>    http://foo.com/hello world/ and http://foo.com/hello%20world</pre>
136 * would be considered not equal to each other.
137 * <p>
138 * Note, the {@link java.net.URI} class does perform escaping of its
139 * component fields in certain circumstances. The recommended way
140 * to manage the encoding and decoding of URLs is to use {@link java.net.URI},
141 * and to convert between these two classes using {@link #toURI()} and
142 * {@link URI#toURL()}.
143 * <p>
144 * The {@link URLEncoder} and {@link URLDecoder} classes can also be
145 * used, but only for HTML form encoding, which is not the same
146 * as the encoding scheme defined in RFC2396.
147 *
148 * @author  James Gosling
149 * @since 1.0
150 */
151public final class URL implements java.io.Serializable {
152
153    static final String BUILTIN_HANDLERS_PREFIX = "sun.net.www.protocol";
154    static final long serialVersionUID = -7627629688361524110L;
155
156    /**
157     * The property which specifies the package prefix list to be scanned
158     * for protocol handlers.  The value of this property (if any) should
159     * be a vertical bar delimited list of package names to search through
160     * for a protocol handler to load.  The policy of this class is that
161     * all protocol handlers will be in a class called <protocolname>.Handler,
162     * and each package in the list is examined in turn for a matching
163     * handler.  If none are found (or the property is not specified), the
164     * default package prefix, sun.net.www.protocol, is used.  The search
165     * proceeds from the first package in the list to the last and stops
166     * when a match is found.
167     */
168    private static final String protocolPathProp = "java.protocol.handler.pkgs";
169
170    /**
171     * The protocol to use (ftp, http, nntp, ... etc.) .
172     * @serial
173     */
174    private String protocol;
175
176    /**
177     * The host name to connect to.
178     * @serial
179     */
180    private String host;
181
182    /**
183     * The protocol port to connect to.
184     * @serial
185     */
186    private int port = -1;
187
188    /**
189     * The specified file name on that host. {@code file} is
190     * defined as {@code path[?query]}
191     * @serial
192     */
193    private String file;
194
195    /**
196     * The query part of this URL.
197     */
198    private transient String query;
199
200    /**
201     * The authority part of this URL.
202     * @serial
203     */
204    private String authority;
205
206    /**
207     * The path part of this URL.
208     */
209    private transient String path;
210
211    /**
212     * The userinfo part of this URL.
213     */
214    private transient String userInfo;
215
216    /**
217     * # reference.
218     * @serial
219     */
220    private String ref;
221
222    /**
223     * The host's IP address, used in equals and hashCode.
224     * Computed on demand. An uninitialized or unknown hostAddress is null.
225     */
226    transient InetAddress hostAddress;
227
228    /**
229     * The URLStreamHandler for this URL.
230     */
231    transient URLStreamHandler handler;
232
233    /* Our hash code.
234     * @serial
235     */
236    private int hashCode = -1;
237
238    private transient UrlDeserializedState tempState;
239
240    /**
241     * Creates a {@code URL} object from the specified
242     * {@code protocol}, {@code host}, {@code port}
243     * number, and {@code file}.<p>
244     *
245     * {@code host} can be expressed as a host name or a literal
246     * IP address. If IPv6 literal address is used, it should be
247     * enclosed in square brackets ({@code '['} and {@code ']'}), as
248     * specified by <a
249     * href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>;
250     * However, the literal IPv6 address format defined in <a
251     * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IP
252     * Version 6 Addressing Architecture</i></a> is also accepted.<p>
253     *
254     * Specifying a {@code port} number of {@code -1}
255     * indicates that the URL should use the default port for the
256     * protocol.<p>
257     *
258     * If this is the first URL object being created with the specified
259     * protocol, a <i>stream protocol handler</i> object, an instance of
260     * class {@code URLStreamHandler}, is created for that protocol:
261     * <ol>
262     * <li>If the application has previously set up an instance of
263     *     {@code URLStreamHandlerFactory} as the stream handler factory,
264     *     then the {@code createURLStreamHandler} method of that instance
265     *     is called with the protocol string as an argument to create the
266     *     stream protocol handler.
267     * <li>If no {@code URLStreamHandlerFactory} has yet been set up,
268     *     or if the factory's {@code createURLStreamHandler} method
269     *     returns {@code null}, then the {@linkplain java.util.ServiceLoader
270     *     ServiceLoader} mechanism is used to locate {@linkplain
271     *     java.net.spi.URLStreamHandlerProvider URLStreamHandlerProvider}
272     *     implementations using the system class
273     *     loader. The order that providers are located is implementation
274     *     specific, and an implementation is free to cache the located
275     *     providers. A {@linkplain java.util.ServiceConfigurationError
276     *     ServiceConfigurationError}, {@code Error} or {@code RuntimeException}
277     *     thrown from the {@code createURLStreamHandler}, if encountered, will
278     *     be propagated to the calling thread. The {@code
279     *     createURLStreamHandler} method of each provider, if instantiated, is
280     *     invoked, with the protocol string, until a provider returns non-null,
281     *     or all providers have been exhausted.
282     * <li>If the previous step fails to find a protocol handler, the
283     *     constructor reads the value of the system property:
284     *     <blockquote>{@code
285     *         java.protocol.handler.pkgs
286     *     }</blockquote>
287     *     If the value of that system property is not {@code null},
288     *     it is interpreted as a list of packages separated by a vertical
289     *     slash character '{@code |}'. The constructor tries to load
290     *     the class named:
291     *     <blockquote>{@code
292     *         <package>.<protocol>.Handler
293     *     }</blockquote>
294     *     where {@code <package>} is replaced by the name of the package
295     *     and {@code <protocol>} is replaced by the name of the protocol.
296     *     If this class does not exist, or if the class exists but it is not
297     *     a subclass of {@code URLStreamHandler}, then the next package
298     *     in the list is tried.
299     * <li>If the previous step fails to find a protocol handler, then the
300     *     constructor tries to load a built-in protocol handler.
301     *     If this class does not exist, or if the class exists but it is not a
302     *     subclass of {@code URLStreamHandler}, then a
303     *     {@code MalformedURLException} is thrown.
304     * </ol>
305     *
306     * <p>Protocol handlers for the following protocols are guaranteed
307     * to exist on the search path :-
308     * <blockquote><pre>
309     *     http, https, file, and jar
310     * </pre></blockquote>
311     * Protocol handlers for additional protocols may also be  available.
312     * Some protocol handlers, for example those used for loading platform
313     * classes or classes on the class path, may not be overridden. The details
314     * of such restrictions, and when those restrictions apply (during
315     * initialization of the runtime for example), are implementation specific
316     * and therefore not specified
317     *
318     * <p>No validation of the inputs is performed by this constructor.
319     *
320     * @param      protocol   the name of the protocol to use.
321     * @param      host       the name of the host.
322     * @param      port       the port number on the host.
323     * @param      file       the file on the host
324     * @exception  MalformedURLException  if an unknown protocol or the port
325     *                  is a negative number other than -1
326     * @see        java.lang.System#getProperty(java.lang.String)
327     * @see        java.net.URL#setURLStreamHandlerFactory(
328     *                  java.net.URLStreamHandlerFactory)
329     * @see        java.net.URLStreamHandler
330     * @see        java.net.URLStreamHandlerFactory#createURLStreamHandler(
331     *                  java.lang.String)
332     */
333    public URL(String protocol, String host, int port, String file)
334        throws MalformedURLException
335    {
336        this(protocol, host, port, file, null);
337    }
338
339    /**
340     * Creates a URL from the specified {@code protocol}
341     * name, {@code host} name, and {@code file} name. The
342     * default port for the specified protocol is used.
343     * <p>
344     * This constructor is equivalent to the four-argument
345     * constructor with the only difference of using the
346     * default port for the specified protocol.
347     *
348     * No validation of the inputs is performed by this constructor.
349     *
350     * @param      protocol   the name of the protocol to use.
351     * @param      host       the name of the host.
352     * @param      file       the file on the host.
353     * @exception  MalformedURLException  if an unknown protocol is specified.
354     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
355     *                  int, java.lang.String)
356     */
357    public URL(String protocol, String host, String file)
358            throws MalformedURLException {
359        this(protocol, host, -1, file);
360    }
361
362    /**
363     * Creates a {@code URL} object from the specified
364     * {@code protocol}, {@code host}, {@code port}
365     * number, {@code file}, and {@code handler}. Specifying
366     * a {@code port} number of {@code -1} indicates that
367     * the URL should use the default port for the protocol. Specifying
368     * a {@code handler} of {@code null} indicates that the URL
369     * should use a default stream handler for the protocol, as outlined
370     * for:
371     *     java.net.URL#URL(java.lang.String, java.lang.String, int,
372     *                      java.lang.String)
373     *
374     * <p>If the handler is not null and there is a security manager,
375     * the security manager's {@code checkPermission}
376     * method is called with a
377     * {@code NetPermission("specifyStreamHandler")} permission.
378     * This may result in a SecurityException.
379     *
380     * No validation of the inputs is performed by this constructor.
381     *
382     * @param      protocol   the name of the protocol to use.
383     * @param      host       the name of the host.
384     * @param      port       the port number on the host.
385     * @param      file       the file on the host
386     * @param      handler    the stream handler for the URL.
387     * @exception  MalformedURLException  if an unknown protocol or the port
388                        is a negative number other than -1
389     * @exception  SecurityException
390     *        if a security manager exists and its
391     *        {@code checkPermission} method doesn't allow
392     *        specifying a stream handler explicitly.
393     * @see        java.lang.System#getProperty(java.lang.String)
394     * @see        java.net.URL#setURLStreamHandlerFactory(
395     *                  java.net.URLStreamHandlerFactory)
396     * @see        java.net.URLStreamHandler
397     * @see        java.net.URLStreamHandlerFactory#createURLStreamHandler(
398     *                  java.lang.String)
399     * @see        SecurityManager#checkPermission
400     * @see        java.net.NetPermission
401     */
402    public URL(String protocol, String host, int port, String file,
403               URLStreamHandler handler) throws MalformedURLException {
404        if (handler != null) {
405            SecurityManager sm = System.getSecurityManager();
406            if (sm != null) {
407                // check for permission to specify a handler
408                checkSpecifyHandler(sm);
409            }
410        }
411
412        protocol = toLowerCase(protocol);
413        this.protocol = protocol;
414        if (host != null) {
415
416            /**
417             * if host is a literal IPv6 address,
418             * we will make it conform to RFC 2732
419             */
420            if (host.indexOf(':') >= 0 && !host.startsWith("[")) {
421                host = "["+host+"]";
422            }
423            this.host = host;
424
425            if (port < -1) {
426                throw new MalformedURLException("Invalid port number :" +
427                                                    port);
428            }
429            this.port = port;
430            authority = (port == -1) ? host : host + ":" + port;
431        }
432
433        int index = file.indexOf('#');
434        this.ref = index < 0 ? null : file.substring(index + 1);
435        file = index < 0 ? file : file.substring(0, index);
436        int q = file.lastIndexOf('?');
437        if (q != -1) {
438            this.query = file.substring(q + 1);
439            this.path = file.substring(0, q);
440            this.file = path + "?" + query;
441        } else {
442            this.path = file;
443            this.file = path;
444        }
445
446        // Note: we don't do validation of the URL here. Too risky to change
447        // right now, but worth considering for future reference. -br
448        if (handler == null &&
449            (handler = getURLStreamHandler(protocol)) == null) {
450            throw new MalformedURLException("unknown protocol: " + protocol);
451        }
452        this.handler = handler;
453    }
454
455    /**
456     * Creates a {@code URL} object from the {@code String}
457     * representation.
458     * <p>
459     * This constructor is equivalent to a call to the two-argument
460     * constructor with a {@code null} first argument.
461     *
462     * @param      spec   the {@code String} to parse as a URL.
463     * @exception  MalformedURLException  if no protocol is specified, or an
464     *               unknown protocol is found, or {@code spec} is {@code null},
465     *               or the parsed URL fails to comply with the specific syntax
466     *               of the associated protocol.
467     * @see        java.net.URL#URL(java.net.URL, java.lang.String)
468     */
469    public URL(String spec) throws MalformedURLException {
470        this(null, spec);
471    }
472
473    /**
474     * Creates a URL by parsing the given spec within a specified context.
475     *
476     * The new URL is created from the given context URL and the spec
477     * argument as described in
478     * RFC2396 &quot;Uniform Resource Identifiers : Generic * Syntax&quot; :
479     * <blockquote><pre>
480     *          &lt;scheme&gt;://&lt;authority&gt;&lt;path&gt;?&lt;query&gt;#&lt;fragment&gt;
481     * </pre></blockquote>
482     * The reference is parsed into the scheme, authority, path, query and
483     * fragment parts. If the path component is empty and the scheme,
484     * authority, and query components are undefined, then the new URL is a
485     * reference to the current document. Otherwise, the fragment and query
486     * parts present in the spec are used in the new URL.
487     * <p>
488     * If the scheme component is defined in the given spec and does not match
489     * the scheme of the context, then the new URL is created as an absolute
490     * URL based on the spec alone. Otherwise the scheme component is inherited
491     * from the context URL.
492     * <p>
493     * If the authority component is present in the spec then the spec is
494     * treated as absolute and the spec authority and path will replace the
495     * context authority and path. If the authority component is absent in the
496     * spec then the authority of the new URL will be inherited from the
497     * context.
498     * <p>
499     * If the spec's path component begins with a slash character
500     * &quot;/&quot; then the
501     * path is treated as absolute and the spec path replaces the context path.
502     * <p>
503     * Otherwise, the path is treated as a relative path and is appended to the
504     * context path, as described in RFC2396. Also, in this case,
505     * the path is canonicalized through the removal of directory
506     * changes made by occurrences of &quot;..&quot; and &quot;.&quot;.
507     * <p>
508     * For a more detailed description of URL parsing, refer to RFC2396.
509     *
510     * @param      context   the context in which to parse the specification.
511     * @param      spec      the {@code String} to parse as a URL.
512     * @exception  MalformedURLException  if no protocol is specified, or an
513     *               unknown protocol is found, or {@code spec} is {@code null},
514     *               or the parsed URL fails to comply with the specific syntax
515     *               of the associated protocol.
516     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
517     *                  int, java.lang.String)
518     * @see        java.net.URLStreamHandler
519     * @see        java.net.URLStreamHandler#parseURL(java.net.URL,
520     *                  java.lang.String, int, int)
521     */
522    public URL(URL context, String spec) throws MalformedURLException {
523        this(context, spec, null);
524    }
525
526    /**
527     * Creates a URL by parsing the given spec with the specified handler
528     * within a specified context. If the handler is null, the parsing
529     * occurs as with the two argument constructor.
530     *
531     * @param      context   the context in which to parse the specification.
532     * @param      spec      the {@code String} to parse as a URL.
533     * @param      handler   the stream handler for the URL.
534     * @exception  MalformedURLException  if no protocol is specified, or an
535     *               unknown protocol is found, or {@code spec} is {@code null},
536     *               or the parsed URL fails to comply with the specific syntax
537     *               of the associated protocol.
538     * @exception  SecurityException
539     *        if a security manager exists and its
540     *        {@code checkPermission} method doesn't allow
541     *        specifying a stream handler.
542     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
543     *                  int, java.lang.String)
544     * @see        java.net.URLStreamHandler
545     * @see        java.net.URLStreamHandler#parseURL(java.net.URL,
546     *                  java.lang.String, int, int)
547     */
548    public URL(URL context, String spec, URLStreamHandler handler)
549        throws MalformedURLException
550    {
551        String original = spec;
552        int i, limit, c;
553        int start = 0;
554        String newProtocol = null;
555        boolean aRef=false;
556        boolean isRelative = false;
557
558        // Check for permission to specify a handler
559        if (handler != null) {
560            SecurityManager sm = System.getSecurityManager();
561            if (sm != null) {
562                checkSpecifyHandler(sm);
563            }
564        }
565
566        try {
567            limit = spec.length();
568            while ((limit > 0) && (spec.charAt(limit - 1) <= ' ')) {
569                limit--;        //eliminate trailing whitespace
570            }
571            while ((start < limit) && (spec.charAt(start) <= ' ')) {
572                start++;        // eliminate leading whitespace
573            }
574
575            if (spec.regionMatches(true, start, "url:", 0, 4)) {
576                start += 4;
577            }
578            if (start < spec.length() && spec.charAt(start) == '#') {
579                /* we're assuming this is a ref relative to the context URL.
580                 * This means protocols cannot start w/ '#', but we must parse
581                 * ref URL's like: "hello:there" w/ a ':' in them.
582                 */
583                aRef=true;
584            }
585            for (i = start ; !aRef && (i < limit) &&
586                     ((c = spec.charAt(i)) != '/') ; i++) {
587                if (c == ':') {
588                    String s = toLowerCase(spec.substring(start, i));
589                    if (isValidProtocol(s)) {
590                        newProtocol = s;
591                        start = i + 1;
592                    }
593                    break;
594                }
595            }
596
597            // Only use our context if the protocols match.
598            protocol = newProtocol;
599            if ((context != null) && ((newProtocol == null) ||
600                            newProtocol.equalsIgnoreCase(context.protocol))) {
601                // inherit the protocol handler from the context
602                // if not specified to the constructor
603                if (handler == null) {
604                    handler = context.handler;
605                }
606
607                // If the context is a hierarchical URL scheme and the spec
608                // contains a matching scheme then maintain backwards
609                // compatibility and treat it as if the spec didn't contain
610                // the scheme; see 5.2.3 of RFC2396
611                if (context.path != null && context.path.startsWith("/"))
612                    newProtocol = null;
613
614                if (newProtocol == null) {
615                    protocol = context.protocol;
616                    authority = context.authority;
617                    userInfo = context.userInfo;
618                    host = context.host;
619                    port = context.port;
620                    file = context.file;
621                    path = context.path;
622                    isRelative = true;
623                }
624            }
625
626            if (protocol == null) {
627                throw new MalformedURLException("no protocol: "+original);
628            }
629
630            // Get the protocol handler if not specified or the protocol
631            // of the context could not be used
632            if (handler == null &&
633                (handler = getURLStreamHandler(protocol)) == null) {
634                throw new MalformedURLException("unknown protocol: "+protocol);
635            }
636
637            this.handler = handler;
638
639            i = spec.indexOf('#', start);
640            if (i >= 0) {
641                ref = spec.substring(i + 1, limit);
642                limit = i;
643            }
644
645            /*
646             * Handle special case inheritance of query and fragment
647             * implied by RFC2396 section 5.2.2.
648             */
649            if (isRelative && start == limit) {
650                query = context.query;
651                if (ref == null) {
652                    ref = context.ref;
653                }
654            }
655
656            handler.parseURL(this, spec, start, limit);
657
658        } catch(MalformedURLException e) {
659            throw e;
660        } catch(Exception e) {
661            MalformedURLException exception = new MalformedURLException(e.getMessage());
662            exception.initCause(e);
663            throw exception;
664        }
665    }
666
667    /**
668     * Creates a URL from a URI, as if by invoking {@code uri.toURL()}.
669     *
670     * @see java.net.URI#toURL()
671     */
672    static URL fromURI(URI uri) throws MalformedURLException {
673        if (!uri.isAbsolute()) {
674            throw new IllegalArgumentException("URI is not absolute");
675        }
676        String protocol = uri.getScheme();
677
678        // In general we need to go via Handler.parseURL, but for the jrt
679        // protocol we enforce that the Handler is not overrideable and can
680        // optimize URI to URL conversion.
681        //
682        // Case-sensitive comparison for performance; malformed protocols will
683        // be handled correctly by the slow path.
684        if (protocol.equals("jrt") && !uri.isOpaque()
685                && uri.getRawFragment() == null) {
686
687            String query = uri.getRawQuery();
688            String path = uri.getRawPath();
689            String file = (query == null) ? path : path + "?" + query;
690
691            // URL represent undefined host as empty string while URI use null
692            String host = uri.getHost();
693            if (host == null) {
694                host = "";
695            }
696
697            int port = uri.getPort();
698
699            return new URL("jrt", host, port, file, null);
700        } else {
701            return new URL((URL)null, uri.toString(), null);
702        }
703    }
704
705    /*
706     * Returns true if specified string is a valid protocol name.
707     */
708    private boolean isValidProtocol(String protocol) {
709        int len = protocol.length();
710        if (len < 1)
711            return false;
712        char c = protocol.charAt(0);
713        if (!Character.isLetter(c))
714            return false;
715        for (int i = 1; i < len; i++) {
716            c = protocol.charAt(i);
717            if (!Character.isLetterOrDigit(c) && c != '.' && c != '+' &&
718                c != '-') {
719                return false;
720            }
721        }
722        return true;
723    }
724
725    /*
726     * Checks for permission to specify a stream handler.
727     */
728    private void checkSpecifyHandler(SecurityManager sm) {
729        sm.checkPermission(SecurityConstants.SPECIFY_HANDLER_PERMISSION);
730    }
731
732    /**
733     * Sets the fields of the URL. This is not a public method so that
734     * only URLStreamHandlers can modify URL fields. URLs are
735     * otherwise constant.
736     *
737     * @param protocol the name of the protocol to use
738     * @param host the name of the host
739       @param port the port number on the host
740     * @param file the file on the host
741     * @param ref the internal reference in the URL
742     */
743    void set(String protocol, String host, int port,
744             String file, String ref) {
745        synchronized (this) {
746            this.protocol = protocol;
747            this.host = host;
748            authority = port == -1 ? host : host + ":" + port;
749            this.port = port;
750            this.file = file;
751            this.ref = ref;
752            /* This is very important. We must recompute this after the
753             * URL has been changed. */
754            hashCode = -1;
755            hostAddress = null;
756            int q = file.lastIndexOf('?');
757            if (q != -1) {
758                query = file.substring(q+1);
759                path = file.substring(0, q);
760            } else
761                path = file;
762        }
763    }
764
765    /**
766     * Sets the specified 8 fields of the URL. This is not a public method so
767     * that only URLStreamHandlers can modify URL fields. URLs are otherwise
768     * constant.
769     *
770     * @param protocol the name of the protocol to use
771     * @param host the name of the host
772     * @param port the port number on the host
773     * @param authority the authority part for the url
774     * @param userInfo the username and password
775     * @param path the file on the host
776     * @param ref the internal reference in the URL
777     * @param query the query part of this URL
778     * @since 1.3
779     */
780    void set(String protocol, String host, int port,
781             String authority, String userInfo, String path,
782             String query, String ref) {
783        synchronized (this) {
784            this.protocol = protocol;
785            this.host = host;
786            this.port = port;
787            this.file = query == null ? path : path + "?" + query;
788            this.userInfo = userInfo;
789            this.path = path;
790            this.ref = ref;
791            /* This is very important. We must recompute this after the
792             * URL has been changed. */
793            hashCode = -1;
794            hostAddress = null;
795            this.query = query;
796            this.authority = authority;
797        }
798    }
799
800    /**
801     * Gets the query part of this {@code URL}.
802     *
803     * @return  the query part of this {@code URL},
804     * or <CODE>null</CODE> if one does not exist
805     * @since 1.3
806     */
807    public String getQuery() {
808        return query;
809    }
810
811    /**
812     * Gets the path part of this {@code URL}.
813     *
814     * @return  the path part of this {@code URL}, or an
815     * empty string if one does not exist
816     * @since 1.3
817     */
818    public String getPath() {
819        return path;
820    }
821
822    /**
823     * Gets the userInfo part of this {@code URL}.
824     *
825     * @return  the userInfo part of this {@code URL}, or
826     * <CODE>null</CODE> if one does not exist
827     * @since 1.3
828     */
829    public String getUserInfo() {
830        return userInfo;
831    }
832
833    /**
834     * Gets the authority part of this {@code URL}.
835     *
836     * @return  the authority part of this {@code URL}
837     * @since 1.3
838     */
839    public String getAuthority() {
840        return authority;
841    }
842
843    /**
844     * Gets the port number of this {@code URL}.
845     *
846     * @return  the port number, or -1 if the port is not set
847     */
848    public int getPort() {
849        return port;
850    }
851
852    /**
853     * Gets the default port number of the protocol associated
854     * with this {@code URL}. If the URL scheme or the URLStreamHandler
855     * for the URL do not define a default port number,
856     * then -1 is returned.
857     *
858     * @return  the port number
859     * @since 1.4
860     */
861    public int getDefaultPort() {
862        return handler.getDefaultPort();
863    }
864
865    /**
866     * Gets the protocol name of this {@code URL}.
867     *
868     * @return  the protocol of this {@code URL}.
869     */
870    public String getProtocol() {
871        return protocol;
872    }
873
874    /**
875     * Gets the host name of this {@code URL}, if applicable.
876     * The format of the host conforms to RFC 2732, i.e. for a
877     * literal IPv6 address, this method will return the IPv6 address
878     * enclosed in square brackets ({@code '['} and {@code ']'}).
879     *
880     * @return  the host name of this {@code URL}.
881     */
882    public String getHost() {
883        return host;
884    }
885
886    /**
887     * Gets the file name of this {@code URL}.
888     * The returned file portion will be
889     * the same as <CODE>getPath()</CODE>, plus the concatenation of
890     * the value of <CODE>getQuery()</CODE>, if any. If there is
891     * no query portion, this method and <CODE>getPath()</CODE> will
892     * return identical results.
893     *
894     * @return  the file name of this {@code URL},
895     * or an empty string if one does not exist
896     */
897    public String getFile() {
898        return file;
899    }
900
901    /**
902     * Gets the anchor (also known as the "reference") of this
903     * {@code URL}.
904     *
905     * @return  the anchor (also known as the "reference") of this
906     *          {@code URL}, or <CODE>null</CODE> if one does not exist
907     */
908    public String getRef() {
909        return ref;
910    }
911
912    /**
913     * Compares this URL for equality with another object.<p>
914     *
915     * If the given object is not a URL then this method immediately returns
916     * {@code false}.<p>
917     *
918     * Two URL objects are equal if they have the same protocol, reference
919     * equivalent hosts, have the same port number on the host, and the same
920     * file and fragment of the file.<p>
921     *
922     * Two hosts are considered equivalent if both host names can be resolved
923     * into the same IP addresses; else if either host name can't be
924     * resolved, the host names must be equal without regard to case; or both
925     * host names equal to null.<p>
926     *
927     * Since hosts comparison requires name resolution, this operation is a
928     * blocking operation. <p>
929     *
930     * Note: The defined behavior for {@code equals} is known to
931     * be inconsistent with virtual hosting in HTTP.
932     *
933     * @param   obj   the URL to compare against.
934     * @return  {@code true} if the objects are the same;
935     *          {@code false} otherwise.
936     */
937    public boolean equals(Object obj) {
938        if (!(obj instanceof URL))
939            return false;
940        URL u2 = (URL)obj;
941
942        return handler.equals(this, u2);
943    }
944
945    /**
946     * Creates an integer suitable for hash table indexing.<p>
947     *
948     * The hash code is based upon all the URL components relevant for URL
949     * comparison. As such, this operation is a blocking operation.
950     *
951     * @return  a hash code for this {@code URL}.
952     */
953    public synchronized int hashCode() {
954        if (hashCode != -1)
955            return hashCode;
956
957        hashCode = handler.hashCode(this);
958        return hashCode;
959    }
960
961    /**
962     * Compares two URLs, excluding the fragment component.<p>
963     *
964     * Returns {@code true} if this {@code URL} and the
965     * {@code other} argument are equal without taking the
966     * fragment component into consideration.
967     *
968     * @param   other   the {@code URL} to compare against.
969     * @return  {@code true} if they reference the same remote object;
970     *          {@code false} otherwise.
971     */
972    public boolean sameFile(URL other) {
973        return handler.sameFile(this, other);
974    }
975
976    /**
977     * Constructs a string representation of this {@code URL}. The
978     * string is created by calling the {@code toExternalForm}
979     * method of the stream protocol handler for this object.
980     *
981     * @return  a string representation of this object.
982     * @see     java.net.URL#URL(java.lang.String, java.lang.String, int,
983     *                  java.lang.String)
984     * @see     java.net.URLStreamHandler#toExternalForm(java.net.URL)
985     */
986    public String toString() {
987        return toExternalForm();
988    }
989
990    /**
991     * Constructs a string representation of this {@code URL}. The
992     * string is created by calling the {@code toExternalForm}
993     * method of the stream protocol handler for this object.
994     *
995     * @return  a string representation of this object.
996     * @see     java.net.URL#URL(java.lang.String, java.lang.String,
997     *                  int, java.lang.String)
998     * @see     java.net.URLStreamHandler#toExternalForm(java.net.URL)
999     */
1000    public String toExternalForm() {
1001        return handler.toExternalForm(this);
1002    }
1003
1004    /**
1005     * Returns a {@link java.net.URI} equivalent to this URL.
1006     * This method functions in the same way as {@code new URI (this.toString())}.
1007     * <p>Note, any URL instance that complies with RFC 2396 can be converted
1008     * to a URI. However, some URLs that are not strictly in compliance
1009     * can not be converted to a URI.
1010     *
1011     * @exception URISyntaxException if this URL is not formatted strictly according to
1012     *            to RFC2396 and cannot be converted to a URI.
1013     *
1014     * @return    a URI instance equivalent to this URL.
1015     * @since 1.5
1016     */
1017    public URI toURI() throws URISyntaxException {
1018        return new URI (toString());
1019    }
1020
1021    /**
1022     * Returns a {@link java.net.URLConnection URLConnection} instance that
1023     * represents a connection to the remote object referred to by the
1024     * {@code URL}.
1025     *
1026     * <P>A new instance of {@linkplain java.net.URLConnection URLConnection} is
1027     * created every time when invoking the
1028     * {@linkplain java.net.URLStreamHandler#openConnection(URL)
1029     * URLStreamHandler.openConnection(URL)} method of the protocol handler for
1030     * this URL.</P>
1031     *
1032     * <P>It should be noted that a URLConnection instance does not establish
1033     * the actual network connection on creation. This will happen only when
1034     * calling {@linkplain java.net.URLConnection#connect() URLConnection.connect()}.</P>
1035     *
1036     * <P>If for the URL's protocol (such as HTTP or JAR), there
1037     * exists a public, specialized URLConnection subclass belonging
1038     * to one of the following packages or one of their subpackages:
1039     * java.lang, java.io, java.util, java.net, the connection
1040     * returned will be of that subclass. For example, for HTTP an
1041     * HttpURLConnection will be returned, and for JAR a
1042     * JarURLConnection will be returned.</P>
1043     *
1044     * @return     a {@link java.net.URLConnection URLConnection} linking
1045     *             to the URL.
1046     * @exception  IOException  if an I/O exception occurs.
1047     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1048     *             int, java.lang.String)
1049     */
1050    public URLConnection openConnection() throws java.io.IOException {
1051        return handler.openConnection(this);
1052    }
1053
1054    /**
1055     * Same as {@link #openConnection()}, except that the connection will be
1056     * made through the specified proxy; Protocol handlers that do not
1057     * support proxing will ignore the proxy parameter and make a
1058     * normal connection.
1059     *
1060     * Invoking this method preempts the system's default
1061     * {@link java.net.ProxySelector ProxySelector} settings.
1062     *
1063     * @param      proxy the Proxy through which this connection
1064     *             will be made. If direct connection is desired,
1065     *             Proxy.NO_PROXY should be specified.
1066     * @return     a {@code URLConnection} to the URL.
1067     * @exception  IOException  if an I/O exception occurs.
1068     * @exception  SecurityException if a security manager is present
1069     *             and the caller doesn't have permission to connect
1070     *             to the proxy.
1071     * @exception  IllegalArgumentException will be thrown if proxy is null,
1072     *             or proxy has the wrong type
1073     * @exception  UnsupportedOperationException if the subclass that
1074     *             implements the protocol handler doesn't support
1075     *             this method.
1076     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1077     *             int, java.lang.String)
1078     * @see        java.net.URLConnection
1079     * @see        java.net.URLStreamHandler#openConnection(java.net.URL,
1080     *             java.net.Proxy)
1081     * @since      1.5
1082     */
1083    public URLConnection openConnection(Proxy proxy)
1084        throws java.io.IOException {
1085        if (proxy == null) {
1086            throw new IllegalArgumentException("proxy can not be null");
1087        }
1088
1089        // Create a copy of Proxy as a security measure
1090        Proxy p = proxy == Proxy.NO_PROXY ? Proxy.NO_PROXY : sun.net.ApplicationProxy.create(proxy);
1091        SecurityManager sm = System.getSecurityManager();
1092        if (p.type() != Proxy.Type.DIRECT && sm != null) {
1093            InetSocketAddress epoint = (InetSocketAddress) p.address();
1094            if (epoint.isUnresolved())
1095                sm.checkConnect(epoint.getHostName(), epoint.getPort());
1096            else
1097                sm.checkConnect(epoint.getAddress().getHostAddress(),
1098                                epoint.getPort());
1099        }
1100        return handler.openConnection(this, p);
1101    }
1102
1103    /**
1104     * Opens a connection to this {@code URL} and returns an
1105     * {@code InputStream} for reading from that connection. This
1106     * method is a shorthand for:
1107     * <blockquote><pre>
1108     *     openConnection().getInputStream()
1109     * </pre></blockquote>
1110     *
1111     * @return     an input stream for reading from the URL connection.
1112     * @exception  IOException  if an I/O exception occurs.
1113     * @see        java.net.URL#openConnection()
1114     * @see        java.net.URLConnection#getInputStream()
1115     */
1116    public final InputStream openStream() throws java.io.IOException {
1117        return openConnection().getInputStream();
1118    }
1119
1120    /**
1121     * Gets the contents of this URL. This method is a shorthand for:
1122     * <blockquote><pre>
1123     *     openConnection().getContent()
1124     * </pre></blockquote>
1125     *
1126     * @return     the contents of this URL.
1127     * @exception  IOException  if an I/O exception occurs.
1128     * @see        java.net.URLConnection#getContent()
1129     */
1130    public final Object getContent() throws java.io.IOException {
1131        return openConnection().getContent();
1132    }
1133
1134    /**
1135     * Gets the contents of this URL. This method is a shorthand for:
1136     * <blockquote><pre>
1137     *     openConnection().getContent(classes)
1138     * </pre></blockquote>
1139     *
1140     * @param classes an array of Java types
1141     * @return     the content object of this URL that is the first match of
1142     *               the types specified in the classes array.
1143     *               null if none of the requested types are supported.
1144     * @exception  IOException  if an I/O exception occurs.
1145     * @see        java.net.URLConnection#getContent(Class[])
1146     * @since 1.3
1147     */
1148    public final Object getContent(Class<?>[] classes)
1149    throws java.io.IOException {
1150        return openConnection().getContent(classes);
1151    }
1152
1153    /**
1154     * The URLStreamHandler factory.
1155     */
1156    private static volatile URLStreamHandlerFactory factory;
1157
1158    /**
1159     * Sets an application's {@code URLStreamHandlerFactory}.
1160     * This method can be called at most once in a given Java Virtual
1161     * Machine.
1162     *
1163     *<p> The {@code URLStreamHandlerFactory} instance is used to
1164     *construct a stream protocol handler from a protocol name.
1165     *
1166     * <p> If there is a security manager, this method first calls
1167     * the security manager's {@code checkSetFactory} method
1168     * to ensure the operation is allowed.
1169     * This could result in a SecurityException.
1170     *
1171     * @param      fac   the desired factory.
1172     * @exception  Error  if the application has already set a factory.
1173     * @exception  SecurityException  if a security manager exists and its
1174     *             {@code checkSetFactory} method doesn't allow
1175     *             the operation.
1176     * @see        java.net.URL#URL(java.lang.String, java.lang.String,
1177     *             int, java.lang.String)
1178     * @see        java.net.URLStreamHandlerFactory
1179     * @see        SecurityManager#checkSetFactory
1180     */
1181    public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) {
1182        synchronized (streamHandlerLock) {
1183            if (factory != null) {
1184                throw new Error("factory already defined");
1185            }
1186            SecurityManager security = System.getSecurityManager();
1187            if (security != null) {
1188                security.checkSetFactory();
1189            }
1190            handlers.clear();
1191
1192            // safe publication of URLStreamHandlerFactory with volatile write
1193            factory = fac;
1194        }
1195    }
1196
1197    private static final URLStreamHandlerFactory defaultFactory = new DefaultFactory();
1198
1199    private static class DefaultFactory implements URLStreamHandlerFactory {
1200        private static String PREFIX = "sun.net.www.protocol";
1201
1202        public URLStreamHandler createURLStreamHandler(String protocol) {
1203            String name = PREFIX + "." + protocol + ".Handler";
1204            try {
1205                @SuppressWarnings("deprecation")
1206                Object o = Class.forName(name).newInstance();
1207                return (URLStreamHandler)o;
1208            } catch (ClassNotFoundException x) {
1209                // ignore
1210            } catch (Exception e) {
1211                // For compatibility, all Exceptions are ignored.
1212                // any number of exceptions can get thrown here
1213            }
1214            return null;
1215        }
1216    }
1217
1218    private static URLStreamHandler lookupViaProperty(String protocol) {
1219        String packagePrefixList =
1220                GetPropertyAction.privilegedGetProperty(protocolPathProp);
1221        if (packagePrefixList == null) {
1222            // not set
1223            return null;
1224        }
1225
1226        String[] packagePrefixes = packagePrefixList.split("\\|");
1227        URLStreamHandler handler = null;
1228        for (int i=0; handler == null && i<packagePrefixes.length; i++) {
1229            String packagePrefix = packagePrefixes[i].trim();
1230            try {
1231                String clsName = packagePrefix + "." + protocol + ".Handler";
1232                Class<?> cls = null;
1233                try {
1234                    cls = Class.forName(clsName);
1235                } catch (ClassNotFoundException e) {
1236                    ClassLoader cl = ClassLoader.getSystemClassLoader();
1237                    if (cl != null) {
1238                        cls = cl.loadClass(clsName);
1239                    }
1240                }
1241                if (cls != null) {
1242                    @SuppressWarnings("deprecation")
1243                    Object tmp = cls.newInstance();
1244                    handler = (URLStreamHandler)tmp;
1245                }
1246            } catch (Exception e) {
1247                // any number of exceptions can get thrown here
1248            }
1249        }
1250        return handler;
1251    }
1252
1253    private static Iterator<URLStreamHandlerProvider> providers() {
1254        return new Iterator<>() {
1255
1256            ClassLoader cl = ClassLoader.getSystemClassLoader();
1257            ServiceLoader<URLStreamHandlerProvider> sl =
1258                    ServiceLoader.load(URLStreamHandlerProvider.class, cl);
1259            Iterator<URLStreamHandlerProvider> i = sl.iterator();
1260
1261            URLStreamHandlerProvider next = null;
1262
1263            private boolean getNext() {
1264                while (next == null) {
1265                    try {
1266                        if (!i.hasNext())
1267                            return false;
1268                        next = i.next();
1269                    } catch (ServiceConfigurationError sce) {
1270                        if (sce.getCause() instanceof SecurityException) {
1271                            // Ignore security exceptions
1272                            continue;
1273                        }
1274                        throw sce;
1275                    }
1276                }
1277                return true;
1278            }
1279
1280            public boolean hasNext() {
1281                return getNext();
1282            }
1283
1284            public URLStreamHandlerProvider next() {
1285                if (!getNext())
1286                    throw new NoSuchElementException();
1287                URLStreamHandlerProvider n = next;
1288                next = null;
1289                return n;
1290            }
1291        };
1292    }
1293
1294    // Thread-local gate to prevent recursive provider lookups
1295    private static ThreadLocal<Object> gate = new ThreadLocal<>();
1296
1297    private static URLStreamHandler lookupViaProviders(final String protocol) {
1298        if (gate.get() != null)
1299            throw new Error("Circular loading of URL stream handler providers detected");
1300
1301        gate.set(gate);
1302        try {
1303            return AccessController.doPrivileged(
1304                new PrivilegedAction<>() {
1305                    public URLStreamHandler run() {
1306                        Iterator<URLStreamHandlerProvider> itr = providers();
1307                        while (itr.hasNext()) {
1308                            URLStreamHandlerProvider f = itr.next();
1309                            URLStreamHandler h = f.createURLStreamHandler(protocol);
1310                            if (h != null)
1311                                return h;
1312                        }
1313                        return null;
1314                    }
1315                });
1316        } finally {
1317            gate.set(null);
1318        }
1319    }
1320
1321    /**
1322     * Returns the protocol in lower case. Special cases known protocols
1323     * to avoid loading locale classes during startup.
1324     */
1325    static String toLowerCase(String protocol) {
1326        if (protocol.equals("jrt") || protocol.equals("file") || protocol.equals("jar")) {
1327            return protocol;
1328        } else {
1329            return protocol.toLowerCase(Locale.ROOT);
1330        }
1331    }
1332
1333    /**
1334     * Non-overrideable protocols: "jrt" and "file"
1335     *
1336     * Character-based comparison for performance reasons; also ensures
1337     * case-insensitive comparison in a locale-independent fashion.
1338     */
1339    static boolean isOverrideable(String protocol) {
1340        if (protocol.length() == 3) {
1341            if ((Character.toLowerCase(protocol.charAt(0)) == 'j') &&
1342                    (Character.toLowerCase(protocol.charAt(1)) == 'r') &&
1343                    (Character.toLowerCase(protocol.charAt(2)) == 't')) {
1344                return false;
1345            }
1346        } else if (protocol.length() == 4) {
1347            if ((Character.toLowerCase(protocol.charAt(0)) == 'f') &&
1348                    (Character.toLowerCase(protocol.charAt(1)) == 'i') &&
1349                    (Character.toLowerCase(protocol.charAt(2)) == 'l') &&
1350                    (Character.toLowerCase(protocol.charAt(3)) == 'e')) {
1351                return false;
1352            }
1353        }
1354        return true;
1355    }
1356
1357    /**
1358     * A table of protocol handlers.
1359     */
1360    static Hashtable<String,URLStreamHandler> handlers = new Hashtable<>();
1361    private static final Object streamHandlerLock = new Object();
1362
1363    /**
1364     * Returns the Stream Handler.
1365     * @param protocol the protocol to use
1366     */
1367    static URLStreamHandler getURLStreamHandler(String protocol) {
1368
1369        URLStreamHandler handler = handlers.get(protocol);
1370
1371        if (handler != null) {
1372            return handler;
1373        }
1374
1375        URLStreamHandlerFactory fac;
1376        boolean checkedWithFactory = false;
1377
1378        if (isOverrideable(protocol) && jdk.internal.misc.VM.isBooted()) {
1379            // Use the factory (if any). Volatile read makes
1380            // URLStreamHandlerFactory appear fully initialized to current thread.
1381            fac = factory;
1382            if (fac != null) {
1383                handler = fac.createURLStreamHandler(protocol);
1384                checkedWithFactory = true;
1385            }
1386
1387            if (handler == null && !protocol.equalsIgnoreCase("jar")) {
1388                handler = lookupViaProviders(protocol);
1389            }
1390
1391            if (handler == null) {
1392                handler = lookupViaProperty(protocol);
1393            }
1394        }
1395
1396        synchronized (streamHandlerLock) {
1397            if (handler == null) {
1398                // Try the built-in protocol handler
1399                handler = defaultFactory.createURLStreamHandler(protocol);
1400            } else {
1401                URLStreamHandler handler2 = null;
1402
1403                // Check again with hashtable just in case another
1404                // thread created a handler since we last checked
1405                handler2 = handlers.get(protocol);
1406
1407                if (handler2 != null) {
1408                    return handler2;
1409                }
1410
1411                // Check with factory if another thread set a
1412                // factory since our last check
1413                if (!checkedWithFactory && (fac = factory) != null) {
1414                    handler2 =  fac.createURLStreamHandler(protocol);
1415                }
1416
1417                if (handler2 != null) {
1418                    // The handler from the factory must be given more
1419                    // importance. Discard the default handler that
1420                    // this thread created.
1421                    handler = handler2;
1422                }
1423            }
1424
1425            // Insert this handler into the hashtable
1426            if (handler != null) {
1427                handlers.put(protocol, handler);
1428            }
1429        }
1430
1431        return handler;
1432    }
1433
1434    /**
1435     * @serialField    protocol String
1436     *
1437     * @serialField    host String
1438     *
1439     * @serialField    port int
1440     *
1441     * @serialField    authority String
1442     *
1443     * @serialField    file String
1444     *
1445     * @serialField    ref String
1446     *
1447     * @serialField    hashCode int
1448     *
1449     */
1450    private static final ObjectStreamField[] serialPersistentFields = {
1451        new ObjectStreamField("protocol", String.class),
1452        new ObjectStreamField("host", String.class),
1453        new ObjectStreamField("port", int.class),
1454        new ObjectStreamField("authority", String.class),
1455        new ObjectStreamField("file", String.class),
1456        new ObjectStreamField("ref", String.class),
1457        new ObjectStreamField("hashCode", int.class), };
1458
1459    /**
1460     * WriteObject is called to save the state of the URL to an
1461     * ObjectOutputStream. The handler is not saved since it is
1462     * specific to this system.
1463     *
1464     * @serialData the default write object value. When read back in,
1465     * the reader must ensure that calling getURLStreamHandler with
1466     * the protocol variable returns a valid URLStreamHandler and
1467     * throw an IOException if it does not.
1468     */
1469    private synchronized void writeObject(java.io.ObjectOutputStream s)
1470        throws IOException
1471    {
1472        s.defaultWriteObject(); // write the fields
1473    }
1474
1475    /**
1476     * readObject is called to restore the state of the URL from the
1477     * stream.  It reads the components of the URL and finds the local
1478     * stream handler.
1479     */
1480    private synchronized void readObject(java.io.ObjectInputStream s)
1481            throws IOException, ClassNotFoundException {
1482        GetField gf = s.readFields();
1483        String protocol = (String)gf.get("protocol", null);
1484        if (getURLStreamHandler(protocol) == null) {
1485            throw new IOException("unknown protocol: " + protocol);
1486        }
1487        String host = (String)gf.get("host", null);
1488        int port = gf.get("port", -1);
1489        String authority = (String)gf.get("authority", null);
1490        String file = (String)gf.get("file", null);
1491        String ref = (String)gf.get("ref", null);
1492        int hashCode = gf.get("hashCode", -1);
1493        if (authority == null
1494                && ((host != null && host.length() > 0) || port != -1)) {
1495            if (host == null)
1496                host = "";
1497            authority = (port == -1) ? host : host + ":" + port;
1498        }
1499        tempState = new UrlDeserializedState(protocol, host, port, authority,
1500               file, ref, hashCode);
1501    }
1502
1503    /**
1504     * Replaces the de-serialized object with an URL object.
1505     *
1506     * @return a newly created object from deserialized data
1507     *
1508     * @throws ObjectStreamException if a new object replacing this
1509     * object could not be created
1510     */
1511
1512   private Object readResolve() throws ObjectStreamException {
1513
1514        URLStreamHandler handler = null;
1515        // already been checked in readObject
1516        handler = getURLStreamHandler(tempState.getProtocol());
1517
1518        URL replacementURL = null;
1519        if (isBuiltinStreamHandler(handler.getClass().getName())) {
1520            replacementURL = fabricateNewURL();
1521        } else {
1522            replacementURL = setDeserializedFields(handler);
1523        }
1524        return replacementURL;
1525    }
1526
1527    private URL setDeserializedFields(URLStreamHandler handler) {
1528        URL replacementURL;
1529        String userInfo = null;
1530        String protocol = tempState.getProtocol();
1531        String host = tempState.getHost();
1532        int port = tempState.getPort();
1533        String authority = tempState.getAuthority();
1534        String file = tempState.getFile();
1535        String ref = tempState.getRef();
1536        int hashCode = tempState.getHashCode();
1537
1538
1539        // Construct authority part
1540        if (authority == null
1541            && ((host != null && host.length() > 0) || port != -1)) {
1542            if (host == null)
1543                host = "";
1544            authority = (port == -1) ? host : host + ":" + port;
1545
1546            // Handle hosts with userInfo in them
1547            int at = host.lastIndexOf('@');
1548            if (at != -1) {
1549                userInfo = host.substring(0, at);
1550                host = host.substring(at+1);
1551            }
1552        } else if (authority != null) {
1553            // Construct user info part
1554            int ind = authority.indexOf('@');
1555            if (ind != -1)
1556                userInfo = authority.substring(0, ind);
1557        }
1558
1559        // Construct path and query part
1560        String path = null;
1561        String query = null;
1562        if (file != null) {
1563            // Fix: only do this if hierarchical?
1564            int q = file.lastIndexOf('?');
1565            if (q != -1) {
1566                query = file.substring(q+1);
1567                path = file.substring(0, q);
1568            } else
1569                path = file;
1570        }
1571
1572        // Set the object fields.
1573        this.protocol = protocol;
1574        this.host = host;
1575        this.port = port;
1576        this.file = file;
1577        this.authority = authority;
1578        this.ref = ref;
1579        this.hashCode = hashCode;
1580        this.handler = handler;
1581        this.query = query;
1582        this.path = path;
1583        this.userInfo = userInfo;
1584        replacementURL = this;
1585        return replacementURL;
1586    }
1587
1588    private URL fabricateNewURL()
1589                throws InvalidObjectException {
1590        // create URL string from deserialized object
1591        URL replacementURL = null;
1592        String urlString = tempState.reconstituteUrlString();
1593
1594        try {
1595            replacementURL = new URL(urlString);
1596        } catch (MalformedURLException mEx) {
1597            resetState();
1598            InvalidObjectException invoEx = new InvalidObjectException(
1599                    "Malformed URL:  " + urlString);
1600            invoEx.initCause(mEx);
1601            throw invoEx;
1602        }
1603        replacementURL.setSerializedHashCode(tempState.getHashCode());
1604        resetState();
1605        return replacementURL;
1606    }
1607
1608    private boolean isBuiltinStreamHandler(String handlerClassName) {
1609        return (handlerClassName.startsWith(BUILTIN_HANDLERS_PREFIX));
1610    }
1611
1612    private void resetState() {
1613        this.protocol = null;
1614        this.host = null;
1615        this.port = -1;
1616        this.file = null;
1617        this.authority = null;
1618        this.ref = null;
1619        this.hashCode = -1;
1620        this.handler = null;
1621        this.query = null;
1622        this.path = null;
1623        this.userInfo = null;
1624        this.tempState = null;
1625    }
1626
1627    private void setSerializedHashCode(int hc) {
1628        this.hashCode = hc;
1629    }
1630
1631    static {
1632        SharedSecrets.setJavaNetURLAccess(
1633                new JavaNetURLAccess() {
1634                    @Override
1635                    public URLStreamHandler getHandler(URL u) {
1636                        return u.handler;
1637                    }
1638                }
1639        );
1640    }
1641}
1642
1643final class UrlDeserializedState {
1644    private final String protocol;
1645    private final String host;
1646    private final int port;
1647    private final String authority;
1648    private final String file;
1649    private final String ref;
1650    private final int hashCode;
1651
1652    public UrlDeserializedState(String protocol,
1653                                String host, int port,
1654                                String authority, String file,
1655                                String ref, int hashCode) {
1656        this.protocol = protocol;
1657        this.host = host;
1658        this.port = port;
1659        this.authority = authority;
1660        this.file = file;
1661        this.ref = ref;
1662        this.hashCode = hashCode;
1663    }
1664
1665    String getProtocol() {
1666        return protocol;
1667    }
1668
1669    String getHost() {
1670        return host;
1671    }
1672
1673    String getAuthority () {
1674        return authority;
1675    }
1676
1677    int getPort() {
1678        return port;
1679    }
1680
1681    String getFile () {
1682        return file;
1683    }
1684
1685    String getRef () {
1686        return ref;
1687    }
1688
1689    int getHashCode () {
1690        return hashCode;
1691    }
1692
1693    String reconstituteUrlString() {
1694
1695        // pre-compute length of StringBuffer
1696        int len = protocol.length() + 1;
1697        if (authority != null && authority.length() > 0)
1698            len += 2 + authority.length();
1699        if (file != null) {
1700            len += file.length();
1701        }
1702        if (ref != null)
1703            len += 1 + ref.length();
1704        StringBuilder result = new StringBuilder(len);
1705        result.append(protocol);
1706        result.append(":");
1707        if (authority != null && authority.length() > 0) {
1708            result.append("//");
1709            result.append(authority);
1710        }
1711        if (file != null) {
1712            result.append(file);
1713        }
1714        if (ref != null) {
1715            result.append("#");
1716            result.append(ref);
1717        }
1718        return result.toString();
1719    }
1720}
1721