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