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