Source for java.net.URL

   1: /* URL.java -- Uniform Resource Locator Class
   2:    Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006
   3:    Free Software Foundation, Inc.
   4: 
   5: This file is part of GNU Classpath.
   6: 
   7: GNU Classpath is free software; you can redistribute it and/or modify
   8: it under the terms of the GNU General Public License as published by
   9: the Free Software Foundation; either version 2, or (at your option)
  10: any later version.
  11: 
  12: GNU Classpath is distributed in the hope that it will be useful, but
  13: WITHOUT ANY WARRANTY; without even the implied warranty of
  14: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15: General Public License for more details.
  16: 
  17: You should have received a copy of the GNU General Public License
  18: along with GNU Classpath; see the file COPYING.  If not, write to the
  19: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  20: 02110-1301 USA.
  21: 
  22: Linking this library statically or dynamically with other modules is
  23: making a combined work based on this library.  Thus, the terms and
  24: conditions of the GNU General Public License cover the whole
  25: combination.
  26: 
  27: As a special exception, the copyright holders of this library give you
  28: permission to link this library with independent modules to produce an
  29: executable, regardless of the license terms of these independent
  30: modules, and to copy and distribute the resulting executable under
  31: terms of your choice, provided that you also meet, for each linked
  32: independent module, the terms and conditions of the license of that
  33: module.  An independent module is a module which is not derived from
  34: or based on this library.  If you modify this library, you may extend
  35: this exception to your version of the library, but you are not
  36: obligated to do so.  If you do not wish to do so, delete this
  37: exception statement from your version. */
  38: 
  39: package java.net;
  40: 
  41: import gnu.classpath.SystemProperties;
  42: import gnu.java.net.URLParseError;
  43: 
  44: import java.io.IOException;
  45: import java.io.InputStream;
  46: import java.io.ObjectInputStream;
  47: import java.io.ObjectOutputStream;
  48: import java.io.Serializable;
  49: import java.security.AccessController;
  50: import java.security.PrivilegedAction;
  51: import java.util.HashMap;
  52: import java.util.StringTokenizer;
  53: 
  54: 
  55: /*
  56:  * Written using on-line Java Platform 1.2 API Specification, as well
  57:  * as "The Java Class Libraries", 2nd edition (Addison-Wesley, 1998).
  58:  * Status:  Believed complete and correct.
  59:  */
  60: 
  61: /**
  62:   * This final class represents an Internet Uniform Resource Locator (URL).
  63:   * For details on the syntax of URL's and what they can be used for,
  64:   * refer to RFC 1738, available from <a
  65:   * href="http://ds.internic.net/rfcs/rfc1738.txt">
  66:   * http://ds.internic.net/rfcs/rfc1738.txt</a>
  67:   * <p>
  68:   * There are a great many protocols supported by URL's such as "http",
  69:   * "ftp", and "file".  This object can handle any arbitrary URL for which
  70:   * a URLStreamHandler object can be written.  Default protocol handlers
  71:   * are provided for the "http" and "ftp" protocols.  Additional protocols
  72:   * handler implementations may be provided in the future.  In any case,
  73:   * an application or applet can install its own protocol handlers that
  74:   * can be "chained" with other protocol hanlders in the system to extend
  75:   * the base functionality provided with this class. (Note, however, that
  76:   * unsigned applets cannot access properties by default or install their
  77:   * own protocol handlers).
  78:   * <p>
  79:   * This chaining is done via the system property java.protocol.handler.pkgs
  80:   * If this property is set, it is assumed to be a "|" separated list of
  81:   * package names in which to attempt locating protocol handlers.  The
  82:   * protocol handler is searched for by appending the string
  83:   * ".&lt;protocol&gt;.Handler" to each packed in the list until a hander is
  84:   * found. If a protocol handler is not found in this list of packages, or if
  85:   * the property does not exist, then the default protocol handler of
  86:   * "gnu.java.net.&lt;protocol&gt;.Handler" is tried.  If this is
  87:   * unsuccessful, a MalformedURLException is thrown.
  88:   * <p>
  89:   * All of the constructor methods of URL attempt to load a protocol
  90:   * handler and so any needed protocol handlers must be installed when
  91:   * the URL is constructed.
  92:   * <p>
  93:   * Here is an example of how URL searches for protocol handlers.  Assume
  94:   * the value of java.protocol.handler.pkgs is "com.foo|com.bar" and the
  95:   * URL is "news://comp.lang.java.programmer".  URL would looking the
  96:   * following places for protocol handlers:
  97:   * <p><pre>
  98:   * com.foo.news.Handler
  99:   * com.bar.news.Handler
 100:   * gnu.java.net.news.Handler
 101:   * </pre><p>
 102:   * If the protocol handler is not found in any of those locations, a
 103:   * MalformedURLException would be thrown.
 104:   * <p>
 105:   * Please note that a protocol handler must be a subclass of
 106:   * URLStreamHandler.
 107:   * <p>
 108:   * Normally, this class caches protocol handlers.  Once it finds a handler
 109:   * for a particular protocol, it never tries to look up a new handler
 110:   * again.  However, if the system property
 111:   * gnu.java.net.nocache_protocol_handlers is set, then this
 112:   * caching behavior is disabled.  This property is specific to this
 113:   * implementation.  Sun's JDK may or may not do protocol caching, but it
 114:   * almost certainly does not examine this property.
 115:   * <p>
 116:   * Please also note that an application can install its own factory for
 117:   * loading protocol handlers (see setURLStreamHandlerFactory).  If this is
 118:   * done, then the above information is superseded and the behavior of this
 119:   * class in loading protocol handlers is dependent on that factory.
 120:   *
 121:   * @author Aaron M. Renn (arenn@urbanophile.com)
 122:   * @author Warren Levy (warrenl@cygnus.com)
 123:   *
 124:   * @see URLStreamHandler
 125:   */
 126: public final class URL implements Serializable
 127: {
 128:   private static final String DEFAULT_SEARCH_PATH =
 129:     "gnu.java.net.protocol|gnu.inet";
 130: 
 131:   // Cached System ClassLoader
 132:   private static ClassLoader systemClassLoader;
 133: 
 134:   /**
 135:    * The name of the protocol for this URL.
 136:    * The protocol is always stored in lower case.
 137:    */
 138:   private String protocol;
 139: 
 140:   /**
 141:    * The "authority" portion of the URL.
 142:    */
 143:   private String authority;
 144: 
 145:   /**
 146:    * The hostname or IP address of this protocol.
 147:    * This includes a possible user. For example <code>joe@some.host.net</code>.
 148:    */
 149:   private String host;
 150: 
 151:   /**
 152:    * The user information necessary to establish the connection.
 153:    */
 154:   private String userInfo;
 155: 
 156:   /**
 157:    * The port number of this protocol or -1 if the port number used is
 158:    * the default for this protocol.
 159:    */
 160:   private int port = -1; // Initialize for constructor using context.
 161: 
 162:   /**
 163:    * The "file" portion of the URL. It is defined as <code>path[?query]</code>.
 164:    */
 165:   private String file;
 166: 
 167:   /**
 168:    * The anchor portion of the URL.
 169:    */
 170:   private String ref;
 171: 
 172:   /**
 173:    * This is the hashCode for this URL
 174:    */
 175:   private int hashCode;
 176: 
 177:   /**
 178:    * The protocol handler in use for this URL
 179:    */
 180:   transient URLStreamHandler ph;
 181: 
 182:   /**
 183:    * If an application installs its own protocol handler factory, this is
 184:    * where we keep track of it.
 185:    */
 186:   private static URLStreamHandlerFactory factory;
 187:   private static final long serialVersionUID = -7627629688361524110L;
 188: 
 189:   /**
 190:    * This a table where we cache protocol handlers to avoid the overhead
 191:    * of looking them up each time.
 192:    */
 193:   private static HashMap ph_cache = new HashMap();
 194: 
 195:   /**
 196:    * Whether or not to cache protocol handlers.
 197:    */
 198:   private static boolean cache_handlers;
 199: 
 200:   static
 201:     {
 202:       String s = SystemProperties.getProperty("gnu.java.net.nocache_protocol_handlers");
 203: 
 204:       if (s == null)
 205:     cache_handlers = true;
 206:       else
 207:     cache_handlers = false;
 208:     }
 209: 
 210:   /**
 211:    * Constructs a URL and loads a protocol handler for the values passed as
 212:    * arguments.
 213:    *
 214:    * @param protocol The protocol for this URL ("http", "ftp", etc)
 215:    * @param host The hostname or IP address to connect to
 216:    * @param port The port number to use, or -1 to use the protocol's
 217:    * default port
 218:    * @param file The "file" portion of the URL.
 219:    *
 220:    * @exception MalformedURLException If a protocol handler cannot be loaded or
 221:    * a parse error occurs.
 222:    */
 223:   public URL(String protocol, String host, int port, String file)
 224:     throws MalformedURLException
 225:   {
 226:     this(protocol, host, port, file, null);
 227:   }
 228: 
 229:   /**
 230:    * Constructs a URL and loads a protocol handler for the values passed in
 231:    * as arugments.  Uses the default port for the protocol.
 232:    *
 233:    * @param protocol The protocol for this URL ("http", "ftp", etc)
 234:    * @param host The hostname or IP address for this URL
 235:    * @param file The "file" portion of this URL.
 236:    *
 237:    * @exception MalformedURLException If a protocol handler cannot be loaded or
 238:    * a parse error occurs.
 239:    */
 240:   public URL(String protocol, String host, String file)
 241:     throws MalformedURLException
 242:   {
 243:     this(protocol, host, -1, file, null);
 244:   }
 245: 
 246:   /**
 247:    * This method initializes a new instance of <code>URL</code> with the
 248:    * specified protocol, host, port, and file.  Additionally, this method
 249:    * allows the caller to specify a protocol handler to use instead of
 250:    * the default.  If this handler is specified, the caller must have
 251:    * the "specifyStreamHandler" permission (see <code>NetPermission</code>)
 252:    * or a <code>SecurityException</code> will be thrown.
 253:    *
 254:    * @param protocol The protocol for this URL ("http", "ftp", etc)
 255:    * @param host The hostname or IP address to connect to
 256:    * @param port The port number to use, or -1 to use the protocol's default
 257:    * port
 258:    * @param file The "file" portion of the URL.
 259:    * @param ph The protocol handler to use with this URL.
 260:    *
 261:    * @exception MalformedURLException If no protocol handler can be loaded
 262:    * for the specified protocol.
 263:    * @exception SecurityException If the <code>SecurityManager</code> exists
 264:    * and does not allow the caller to specify its own protocol handler.
 265:    *
 266:    * @since 1.2
 267:    */
 268:   public URL(String protocol, String host, int port, String file,
 269:              URLStreamHandler ph) throws MalformedURLException
 270:   {
 271:     if (protocol == null)
 272:       throw new MalformedURLException("null protocol");
 273:     protocol = protocol.toLowerCase();
 274:     this.protocol = protocol;
 275: 
 276:     if (ph != null)
 277:       {
 278:     SecurityManager s = System.getSecurityManager();
 279:     if (s != null)
 280:       s.checkPermission(new NetPermission("specifyStreamHandler"));
 281: 
 282:     this.ph = ph;
 283:       }
 284:     else
 285:       this.ph = getURLStreamHandler(protocol);
 286: 
 287:     if (this.ph == null)
 288:       throw new MalformedURLException("Protocol handler not found: "
 289:                                       + protocol);
 290: 
 291:     this.host = host;
 292:     this.port = port;
 293:     this.authority = (host != null) ? host : "";
 294:     if (port >= 0 && host != null)
 295:     this.authority += ":" + port;
 296: 
 297:     int hashAt = file.indexOf('#');
 298:     if (hashAt < 0)
 299:       {
 300:     this.file = file;
 301:     this.ref = null;
 302:       }
 303:     else
 304:       {
 305:     this.file = file.substring(0, hashAt);
 306:     this.ref = file.substring(hashAt + 1);
 307:       }
 308:     hashCode = hashCode(); // Used for serialization.
 309:   }
 310: 
 311:   /**
 312:    * Initializes a URL from a complete string specification such as
 313:    * "http://www.urbanophile.com/arenn/".  First the protocol name is parsed
 314:    * out of the string.  Then a handler is located for that protocol and
 315:    * the parseURL() method of that protocol handler is used to parse the
 316:    * remaining fields.
 317:    *
 318:    * @param spec The complete String representation of a URL
 319:    *
 320:    * @exception MalformedURLException If a protocol handler cannot be found
 321:    * or the URL cannot be parsed
 322:    */
 323:   public URL(String spec) throws MalformedURLException
 324:   {
 325:     this((URL) null, spec != null ? spec : "", (URLStreamHandler) null);
 326:   }
 327: 
 328:   /**
 329:    * This method parses a String representation of a URL within the
 330:    * context of an existing URL.  Principally this means that any
 331:    * fields not present the URL are inheritied from the context URL.
 332:    * This allows relative URL's to be easily constructed.  If the
 333:    * context argument is null, then a complete URL must be specified
 334:    * in the URL string.  If the protocol parsed out of the URL is
 335:    * different from the context URL's protocol, then then URL String
 336:    * is also expected to be a complete URL.
 337:    *
 338:    * @param context The context on which to parse the specification
 339:    * @param spec The string to parse an URL
 340:    *
 341:    * @exception MalformedURLException If a protocol handler cannot be found
 342:    * for the URL cannot be parsed
 343:    */
 344:   public URL(URL context, String spec) throws MalformedURLException
 345:   {
 346:     this(context, spec, (context == null) ? (URLStreamHandler)null : context.ph);
 347:   }
 348: 
 349:   /**
 350:    * Creates an URL from given arguments
 351:    * This method parses a String representation of a URL within the
 352:    * context of an existing URL.  Principally this means that any fields
 353:    * not present the URL are inheritied from the context URL.  This allows
 354:    * relative URL's to be easily constructed.  If the context argument is
 355:    * null, then a complete URL must be specified in the URL string.
 356:    * If the protocol parsed out of the URL is different
 357:    * from the context URL's protocol, then then URL String is also
 358:    * expected to be a complete URL.
 359:    * <p>
 360:    * Additionally, this method allows the caller to specify a protocol handler
 361:    * to use instead of  the default.  If this handler is specified, the caller
 362:    * must have the "specifyStreamHandler" permission
 363:    * (see <code>NetPermission</code>) or a <code>SecurityException</code>
 364:    * will be thrown.
 365:    *
 366:    * @param context The context in which to parse the specification
 367:    * @param spec The string to parse as an URL
 368:    * @param ph The stream handler for the URL
 369:    *
 370:    * @exception MalformedURLException If a protocol handler cannot be found
 371:    * or the URL cannot be parsed
 372:    * @exception SecurityException If the <code>SecurityManager</code> exists
 373:    * and does not allow the caller to specify its own protocol handler.
 374:    *
 375:    * @since 1.2
 376:    */
 377:   public URL(URL context, String spec, URLStreamHandler ph)
 378:     throws MalformedURLException
 379:   {
 380:     /* A protocol is defined by the doc as the substring before a ':'
 381:      * as long as the ':' occurs before any '/'.
 382:      *
 383:      * If context is null, then spec must be an absolute URL.
 384:      *
 385:      * The relative URL need not specify all the components of a URL.
 386:      * If the protocol, host name, or port number is missing, the value
 387:      * is inherited from the context.  A bare file component is appended
 388:      * to the context's file.  The optional anchor is not inherited.
 389:      */
 390: 
 391:     // If this is an absolute URL, then ignore context completely.
 392:     // An absolute URL must have chars prior to "://" but cannot have a colon
 393:     // right after the "://".  The second colon is for an optional port value
 394:     // and implies that the host from the context is used if available.
 395:     int colon;
 396:     int slash = spec.indexOf('/');
 397:     if ((colon = spec.indexOf("://", 1)) > 0
 398:     && ((colon < slash || slash < 0))
 399:         && ! spec.regionMatches(colon, "://:", 0, 4))
 400:       context = null;
 401: 
 402:     boolean protocolSpecified = false;
 403: 
 404:     if ((colon = spec.indexOf(':')) > 0
 405:         && (colon < slash || slash < 0))
 406:       {
 407:     // Protocol may have been specified in spec string.
 408:         protocolSpecified = true;
 409:     protocol = spec.substring(0, colon).toLowerCase();
 410:     if (context != null)
 411:           {
 412:             if (context.protocol.equals(protocol))
 413:               {
 414:                 // The 1.2 doc specifically says these are copied to the new URL.
 415:                 host = context.host;
 416:                 port = context.port;
 417:                 userInfo = context.userInfo;
 418:                 authority = context.authority;
 419:               }
 420:             else
 421:               {
 422:                 // There was a colon in the spec.  Check to see if
 423:                 // what precedes it is a valid protocol.  If it was
 424:                 // not, assume that it is relative to the context.
 425:                 URLStreamHandler specPh = getURLStreamHandler(protocol.trim());
 426:                 if (null == specPh)
 427:                     protocolSpecified = false;
 428:               }
 429:           }
 430:       }
 431: 
 432:     if (!protocolSpecified)
 433:       {
 434:         if (context != null)
 435:           {
 436:             // Protocol NOT specified in spec string.
 437:             // Use context fields (except ref) as a foundation for relative URLs.
 438:             colon = -1;
 439:             protocol = context.protocol;
 440:             host = context.host;
 441:             port = context.port;
 442:             userInfo = context.userInfo;
 443:             if (spec.indexOf(":/", 1) < 0)
 444:               {
 445:                 file = context.file;
 446:                 if (file == null || file.length() == 0)
 447:                   file = "/";
 448:               }
 449:             authority = context.authority;
 450:           }
 451:         else // Protocol NOT specified in spec. and no context available.
 452:           throw new MalformedURLException("Absolute URL required with null"
 453:                                           + " context: " + spec);
 454:       }
 455: 
 456:     protocol = protocol.trim();
 457: 
 458:     if (ph != null)
 459:       {
 460:     SecurityManager s = System.getSecurityManager();
 461:     if (s != null)
 462:       s.checkPermission(new NetPermission("specifyStreamHandler"));
 463: 
 464:     this.ph = ph;
 465:       }
 466:     else
 467:       this.ph = getURLStreamHandler(protocol);
 468: 
 469:     if (this.ph == null)
 470:       throw new MalformedURLException("Protocol handler not found: "
 471:                                       + protocol);
 472: 
 473:     // JDK 1.2 doc for parseURL specifically states that any '#' ref
 474:     // is to be excluded by passing the 'limit' as the indexOf the '#'
 475:     // if one exists, otherwise pass the end of the string.
 476:     int hashAt = spec.indexOf('#', colon + 1);
 477: 
 478:     try
 479:       {
 480:     this.ph.parseURL(this, spec, colon + 1,
 481:                      hashAt < 0 ? spec.length() : hashAt);
 482:       }
 483:     catch (URLParseError e)
 484:       {
 485:         MalformedURLException mue = new MalformedURLException(e.getMessage());
 486:         mue.initCause(e);
 487:     throw mue;
 488:       }
 489:     catch (RuntimeException e)
 490:       {
 491:         // This isn't documented, but the JDK also catches
 492:         // RuntimeExceptions here.
 493:         MalformedURLException mue = new MalformedURLException(e.getMessage());
 494:         mue.initCause(e);
 495:         throw mue;
 496:       }
 497: 
 498:     if (hashAt >= 0)
 499:       ref = spec.substring(hashAt + 1);
 500: 
 501:     hashCode = hashCode(); // Used for serialization.
 502:   }
 503: 
 504:   /**
 505:    * Test another URL for equality with this one.  This will be true only if
 506:    * the argument is non-null and all of the fields in the URL's match
 507:    * exactly (ie, protocol, host, port, file, and ref).  Overrides
 508:    * Object.equals(), implemented by calling the equals method of the handler.
 509:    *
 510:    * @param obj The URL to compare with
 511:    *
 512:    * @return true if the URL is equal, false otherwise
 513:    */
 514:   public boolean equals(Object obj)
 515:   {
 516:     if (! (obj instanceof URL))
 517:       return false;
 518: 
 519:     return ph.equals(this, (URL) obj);
 520:   }
 521: 
 522:   /**
 523:    * Returns the contents of this URL as an object by first opening a
 524:    * connection, then calling the getContent() method against the connection
 525:    *
 526:    * @return A content object for this URL
 527:    * @exception IOException If opening the connection or getting the
 528:    * content fails.
 529:    *
 530:    * @since 1.3
 531:    */
 532:   public Object getContent() throws IOException
 533:   {
 534:     return openConnection().getContent();
 535:   }
 536: 
 537:   /**
 538:    * Gets the contents of this URL
 539:    *
 540:    * @param classes The allow classes for the content object.
 541:    *
 542:    * @return a context object for this URL.
 543:    *
 544:    * @exception IOException If an error occurs
 545:    */
 546:   public Object getContent(Class[] classes) throws IOException
 547:   {
 548:     return openConnection().getContent(classes);
 549:   }
 550: 
 551:   /**
 552:    * Returns the file portion of the URL.
 553:    * Defined as <code>path[?query]</code>.
 554:    * Returns the empty string if there is no file portion.
 555:    *
 556:    * @return The filename specified in this URL, or an empty string if empty.
 557:    */
 558:   public String getFile()
 559:   {
 560:     return file == null ? "" : file;
 561:   }
 562: 
 563:   /**
 564:    * Returns the path of the URL. This is the part of the file before any '?'
 565:    * character.
 566:    *
 567:    * @return The path specified in this URL, or null if empty.
 568:    *
 569:    * @since 1.3
 570:    */
 571:   public String getPath()
 572:   {
 573:     // The spec says we need to return an empty string, but some
 574:     // applications depends on receiving null when the path is empty.
 575:     if (file == null)
 576:       return null;
 577:     int quest = file.indexOf('?');
 578:     return quest < 0 ? getFile() : file.substring(0, quest);
 579:   }
 580: 
 581:   /**
 582:    * Returns the authority of the URL
 583:    *
 584:    * @return The authority specified in this URL.
 585:    *
 586:    * @since 1.3
 587:    */
 588:   public String getAuthority()
 589:   {
 590:     return authority;
 591:   }
 592: 
 593:   /**
 594:    * Returns the host of the URL
 595:    *
 596:    * @return The host specified in this URL.
 597:    */
 598:   public String getHost()
 599:   {
 600:     int at = (host == null) ? -1 : host.indexOf('@');
 601:     return at < 0 ? host : host.substring(at + 1, host.length());
 602:   }
 603: 
 604:   /**
 605:    * Returns the port number of this URL or -1 if the default port number is
 606:    * being used.
 607:    *
 608:    * @return The port number
 609:    *
 610:    * @see #getDefaultPort()
 611:    */
 612:   public int getPort()
 613:   {
 614:     return port;
 615:   }
 616: 
 617:   /**
 618:    * Returns the default port of the URL. If the StreamHandler for the URL
 619:    * protocol does not define a default port it returns -1.
 620:    *
 621:    * @return The default port of the current protocol.
 622:    */
 623:   public int getDefaultPort()
 624:   {
 625:     return ph.getDefaultPort();
 626:   }
 627: 
 628:   /**
 629:    * Returns the protocol of the URL
 630:    *
 631:    * @return The specified protocol.
 632:    */
 633:   public String getProtocol()
 634:   {
 635:     return protocol;
 636:   }
 637: 
 638:   /**
 639:    * Returns the ref (sometimes called the "# reference" or "anchor") portion
 640:    * of the URL.
 641:    *
 642:    * @return The ref
 643:    */
 644:   public String getRef()
 645:   {
 646:     return ref;
 647:   }
 648: 
 649:   /**
 650:    * Returns the user information of the URL. This is the part of the host
 651:    * name before the '@'.
 652:    *
 653:    * @return the user at a particular host or null when no user defined.
 654:    */
 655:   public String getUserInfo()
 656:   {
 657:     if (userInfo != null)
 658:       return userInfo;
 659:     int at = (host == null) ? -1 : host.indexOf('@');
 660:     return at < 0 ? null : host.substring(0, at);
 661:   }
 662: 
 663:   /**
 664:    * Returns the query of the URL. This is the part of the file before the
 665:    * '?'.
 666:    *
 667:    * @return the query part of the file, or null when there is no query part.
 668:    */
 669:   public String getQuery()
 670:   {
 671:     int quest = (file == null) ? -1 : file.indexOf('?');
 672:     return quest < 0 ? null : file.substring(quest + 1, file.length());
 673:   }
 674: 
 675:   /**
 676:    * Returns a hashcode computed by the URLStreamHandler of this URL
 677:    *
 678:    * @return The hashcode for this URL.
 679:    */
 680:   public int hashCode()
 681:   {
 682:     if (hashCode != 0)
 683:       return hashCode; // Use cached value if available.
 684:     else
 685:       return ph.hashCode(this);
 686:   }
 687: 
 688:   /**
 689:    * Returns a URLConnection object that represents a connection to the remote
 690:    * object referred to by the URL. The URLConnection is created by calling the
 691:    * openConnection() method of the protocol handler
 692:    *
 693:    * @return A URLConnection for this URL
 694:    *
 695:    * @exception IOException If an error occurs
 696:    */
 697:   public URLConnection openConnection() throws IOException
 698:   {
 699:     return ph.openConnection(this);
 700:   }
 701: 
 702:   /**
 703:    * Opens a connection to this URL and returns an InputStream for reading
 704:    * from that connection
 705:    *
 706:    * @return An <code>InputStream</code> for this URL.
 707:    *
 708:    * @exception IOException If an error occurs
 709:    */
 710:   public InputStream openStream() throws IOException
 711:   {
 712:     return openConnection().getInputStream();
 713:   }
 714: 
 715:   /**
 716:    * Tests whether or not another URL refers to the same "file" as this one.
 717:    * This will be true if and only if the passed object is not null, is a
 718:    * URL, and matches all fields but the ref (ie, protocol, host, port,
 719:    * and file);
 720:    *
 721:    * @param url The URL object to test with
 722:    *
 723:    * @return true if URL matches this URL's file, false otherwise
 724:    */
 725:   public boolean sameFile(URL url)
 726:   {
 727:     return ph.sameFile(this, url);
 728:   }
 729: 
 730:   /**
 731:    * Sets the specified fields of the URL. This is not a public method so
 732:    * that only URLStreamHandlers can modify URL fields. This might be called
 733:    * by the <code>parseURL()</code> method in that class. URLs are otherwise
 734:    * constant. If the given protocol does not exist, it will keep the previously
 735:    * set protocol.
 736:    *
 737:    * @param protocol The protocol name for this URL
 738:    * @param host The hostname or IP address for this URL
 739:    * @param port The port number of this URL
 740:    * @param file The "file" portion of this URL.
 741:    * @param ref The anchor portion of this URL.
 742:    */
 743:   protected void set(String protocol, String host, int port, String file,
 744:                      String ref)
 745:   {
 746:     URLStreamHandler protocolHandler = null;
 747:     protocol = protocol.toLowerCase();
 748:     if (! this.protocol.equals(protocol))
 749:       protocolHandler = getURLStreamHandler(protocol);
 750:     
 751:     // It is an hidden feature of the JDK. If the protocol does not exist,
 752:     // we keep the previously initialized protocol.
 753:     if (protocolHandler != null)
 754:       {
 755:     this.ph = protocolHandler;
 756:     this.protocol = protocol;
 757:       }
 758:     this.authority = "";
 759:     this.port = port;
 760:     this.host = host;
 761:     this.file = file;
 762:     this.ref = ref;
 763: 
 764:     if (host != null)
 765:       this.authority += host;
 766:     if (port >= 0)
 767:       this.authority += ":" + port;
 768: 
 769:     hashCode = hashCode(); // Used for serialization.
 770:   }
 771: 
 772:   /**
 773:    * Sets the specified fields of the URL. This is not a public method so
 774:    * that only URLStreamHandlers can modify URL fields. URLs are otherwise
 775:    * constant. If the given protocol does not exist, it will keep the previously
 776:    * set protocol.
 777:    *
 778:    * @param protocol The protocol name for this URL.
 779:    * @param host The hostname or IP address for this URL.
 780:    * @param port The port number of this URL.
 781:    * @param authority The authority of this URL.
 782:    * @param userInfo The user and password (if needed) of this URL.
 783:    * @param path The "path" portion of this URL.
 784:    * @param query The query of this URL.
 785:    * @param ref The anchor portion of this URL.
 786:    *
 787:    * @since 1.3
 788:    */
 789:   protected void set(String protocol, String host, int port, String authority,
 790:                      String userInfo, String path, String query, String ref)
 791:   {
 792:     URLStreamHandler protocolHandler = null;
 793:     protocol = protocol.toLowerCase();
 794:     if (! this.protocol.equals(protocol))
 795:       protocolHandler = getURLStreamHandler(protocol);
 796:     
 797:     // It is an hidden feature of the JDK. If the protocol does not exist,
 798:     // we keep the previously initialized protocol.
 799:     if (protocolHandler != null)
 800:       {
 801:     this.ph = protocolHandler;
 802:     this.protocol = protocol;
 803:       }
 804:     this.host = host;
 805:     this.userInfo = userInfo;
 806:     this.port = port;
 807:     this.authority = authority;
 808:     if (query == null)
 809:       this.file = path;
 810:     else
 811:       this.file = path + "?" + query;
 812:     this.ref = ref;
 813:     hashCode = hashCode(); // Used for serialization.
 814:   }
 815: 
 816:   /**
 817:    * Sets the URLStreamHandlerFactory for this class.  This factory is
 818:    * responsible for returning the appropriate protocol handler for
 819:    * a given URL.
 820:    *
 821:    * @param fac The URLStreamHandlerFactory class to use
 822:    *
 823:    * @exception Error If the factory is alread set.
 824:    * @exception SecurityException If a security manager exists and its
 825:    * checkSetFactory method doesn't allow the operation
 826:    */
 827:   public static synchronized void setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
 828:   {
 829:     if (factory != null)
 830:       throw new Error("URLStreamHandlerFactory already set");
 831: 
 832:     // Throw an exception if an extant security mgr precludes
 833:     // setting the factory.
 834:     SecurityManager s = System.getSecurityManager();
 835:     if (s != null)
 836:       s.checkSetFactory();
 837:     factory = fac;
 838:   }
 839: 
 840:   /**
 841:    * Returns a String representing this URL.  The String returned is
 842:    * created by calling the protocol handler's toExternalForm() method.
 843:    *
 844:    * @return A string for this URL
 845:    */
 846:   public String toExternalForm()
 847:   {
 848:     // Identical to toString().
 849:     return ph.toExternalForm(this);
 850:   }
 851: 
 852:   /**
 853:    * Returns a String representing this URL.  Identical to toExternalForm().
 854:    * The value returned is created by the protocol handler's
 855:    * toExternalForm method.  Overrides Object.toString()
 856:    *
 857:    * @return A string for this URL
 858:    */
 859:   public String toString()
 860:   {
 861:     // Identical to toExternalForm().
 862:     return ph.toExternalForm(this);
 863:   }
 864: 
 865:   /**
 866:    * This internal method is used in two different constructors to load
 867:    * a protocol handler for this URL.
 868:    *
 869:    * @param protocol The protocol to load a handler for
 870:    *
 871:    * @return A URLStreamHandler for this protocol, or null when not found.
 872:    */
 873:   private static synchronized URLStreamHandler getURLStreamHandler(String protocol)
 874:   {
 875:     URLStreamHandler ph = null;
 876: 
 877:     // First, see if a protocol handler is in our cache.
 878:     if (cache_handlers)
 879:       {
 880:     if ((ph = (URLStreamHandler) ph_cache.get(protocol)) != null)
 881:       return ph;
 882:       }
 883: 
 884:     // If a non-default factory has been set, use it to find the protocol.
 885:     if (factory != null)
 886:       {
 887:     ph = factory.createURLStreamHandler(protocol);
 888:       }
 889: 
 890:     // Non-default factory may have returned null or a factory wasn't set.
 891:     // Use the default search algorithm to find a handler for this protocol.
 892:     if (ph == null)
 893:       {
 894:     // Get the list of packages to check and append our default handler
 895:     // to it, along with the JDK specified default as a last resort.
 896:     // Except in very unusual environments the JDK specified one shouldn't
 897:     // ever be needed (or available).
 898:     String ph_search_path =
 899:       SystemProperties.getProperty("java.protocol.handler.pkgs");
 900: 
 901:     // Tack our default package on at the ends.
 902:     if (ph_search_path != null)
 903:       ph_search_path += "|" + DEFAULT_SEARCH_PATH;
 904:     else
 905:       ph_search_path = DEFAULT_SEARCH_PATH;
 906: 
 907:     // Finally loop through our search path looking for a match.
 908:     StringTokenizer pkgPrefix = new StringTokenizer(ph_search_path, "|");
 909: 
 910:     // Cache the systemClassLoader
 911:     if (systemClassLoader == null)
 912:       {
 913:         systemClassLoader = (ClassLoader) AccessController.doPrivileged
 914:           (new PrivilegedAction() {
 915:           public Object run()
 916:               {
 917:             return ClassLoader.getSystemClassLoader();
 918:           }
 919:         });
 920:       }
 921: 
 922:     do
 923:       {
 924:         try
 925:           {
 926:         // Try to get a class from the system/application
 927:         // classloader, initialize it, make an instance
 928:         // and try to cast it to a URLStreamHandler.
 929:         String clsName =
 930:           (pkgPrefix.nextToken() + "." + protocol + ".Handler");
 931:         Class c = Class.forName(clsName, true, systemClassLoader);
 932:         ph = (URLStreamHandler) c.newInstance();
 933:           }
 934:             catch (ThreadDeath death)
 935:               {
 936:                 throw death;
 937:               }
 938:         catch (Throwable t)
 939:           {
 940:         // Ignored.
 941:           }
 942:       }
 943:      while (ph == null && pkgPrefix.hasMoreTokens());
 944:       }
 945: 
 946:     // Update the hashtable with the new protocol handler.
 947:     if (ph != null && cache_handlers)
 948:       ph_cache.put(protocol, ph);
 949:     else
 950:       ph = null;
 951: 
 952:     return ph;
 953:   }
 954: 
 955:   private void readObject(ObjectInputStream ois)
 956:     throws IOException, ClassNotFoundException
 957:   {
 958:     ois.defaultReadObject();
 959:     this.ph = getURLStreamHandler(protocol);
 960:     if (this.ph == null)
 961:       throw new IOException("Handler for protocol " + protocol + " not found");
 962:   }
 963: 
 964:   private void writeObject(ObjectOutputStream oos) throws IOException
 965:   {
 966:     oos.defaultWriteObject();
 967:   }
 968: 
 969:   /**
 970:    * Returns the equivalent <code>URI</code> object for this <code>URL</code>.
 971:    * This is the same as calling <code>new URI(this.toString())</code>.
 972:    * RFC2396-compliant URLs are guaranteed a successful conversion to
 973:    * a <code>URI</code> instance.  However, there are some values which
 974:    * form valid URLs, but which do not also form RFC2396-compliant URIs.
 975:    *
 976:    * @throws URISyntaxException if this URL is not RFC2396-compliant,
 977:    *         and thus can not be successfully converted to a URI.
 978:    */
 979:   public URI toURI()
 980:     throws URISyntaxException
 981:   {
 982:     return new URI(toString());
 983:   }
 984: 
 985: }