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