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