1 /*
   2  * Copyright (c) 2000, 2017, 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.InvalidObjectException;
  30 import java.io.ObjectInputStream;
  31 import java.io.ObjectOutputStream;
  32 import java.io.Serializable;
  33 import java.nio.ByteBuffer;
  34 import java.nio.CharBuffer;
  35 import java.nio.charset.CharsetDecoder;
  36 import java.nio.charset.CoderResult;
  37 import java.nio.charset.CodingErrorAction;
  38 import java.nio.charset.CharacterCodingException;
  39 import java.text.Normalizer;
  40 import jdk.internal.loader.URLClassPath;
  41 import jdk.internal.misc.JavaNetUriAccess;
  42 import jdk.internal.misc.SharedSecrets;
  43 import sun.nio.cs.ThreadLocalCoders;
  44 
  45 import java.lang.Character;             // for javadoc
  46 import java.lang.NullPointerException;  // for javadoc
  47 
  48 
  49 /**
  50  * Represents a Uniform Resource Identifier (URI) reference.
  51  *
  52  * <p> Aside from some minor deviations noted below, an instance of this
  53  * class represents a URI reference as defined by
  54  * <a href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
  55  * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
  56  * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
  57  * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
  58  * also supports scope_ids. The syntax and usage of scope_ids is described
  59  * <a href="Inet6Address.html#scoped">here</a>.
  60  * This class provides constructors for creating URI instances from
  61  * their components or by parsing their string forms, methods for accessing the
  62  * various components of an instance, and methods for normalizing, resolving,
  63  * and relativizing URI instances.  Instances of this class are immutable.
  64  *
  65  *
  66  * <h3> URI syntax and components </h3>
  67  *
  68  * At the highest level a URI reference (hereinafter simply "URI") in string
  69  * form has the syntax
  70  *
  71  * <blockquote>
  72  * [<i>scheme</i><b>{@code :}</b>]<i>scheme-specific-part</i>[<b>{@code #}</b><i>fragment</i>]
  73  * </blockquote>
  74  *
  75  * where square brackets [...] delineate optional components and the characters
  76  * <b>{@code :}</b> and <b>{@code #}</b> stand for themselves.
  77  *
  78  * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is
  79  * said to be <i>relative</i>.  URIs are also classified according to whether
  80  * they are <i>opaque</i> or <i>hierarchical</i>.
  81  *
  82  * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does
  83  * not begin with a slash character ({@code '/'}).  Opaque URIs are not
  84  * subject to further parsing.  Some examples of opaque URIs are:
  85  *
  86  * <blockquote><ul style="list-style-type:none">
  87  * <li>{@code mailto:java-net@java.sun.com}</li>
  88  * <li>{@code news:comp.lang.java}</li>
  89  * <li>{@code urn:isbn:096139210x}</li>
  90  * </ul></blockquote>
  91  *
  92  * <p> A <i>hierarchical</i> URI is either an absolute URI whose
  93  * scheme-specific part begins with a slash character, or a relative URI, that
  94  * is, a URI that does not specify a scheme.  Some examples of hierarchical
  95  * URIs are:
  96  *
  97  * <blockquote>
  98  * {@code http://example.com/languages/java/}<br>
  99  * {@code sample/a/index.html#28}<br>
 100  * {@code ../../demo/b/index.html}<br>
 101  * {@code file:///~/calendar}
 102  * </blockquote>
 103  *
 104  * <p> A hierarchical URI is subject to further parsing according to the syntax
 105  *
 106  * <blockquote>
 107  * [<i>scheme</i><b>{@code :}</b>][<b>{@code //}</b><i>authority</i>][<i>path</i>][<b>{@code ?}</b><i>query</i>][<b>{@code #}</b><i>fragment</i>]
 108  * </blockquote>
 109  *
 110  * where the characters <b>{@code :}</b>, <b>{@code /}</b>,
 111  * <b>{@code ?}</b>, and <b>{@code #}</b> stand for themselves.  The
 112  * scheme-specific part of a hierarchical URI consists of the characters
 113  * between the scheme and fragment components.
 114  *
 115  * <p> The authority component of a hierarchical URI is, if specified, either
 116  * <i>server-based</i> or <i>registry-based</i>.  A server-based authority
 117  * parses according to the familiar syntax
 118  *
 119  * <blockquote>
 120  * [<i>user-info</i><b>{@code @}</b>]<i>host</i>[<b>{@code :}</b><i>port</i>]
 121  * </blockquote>
 122  *
 123  * where the characters <b>{@code @}</b> and <b>{@code :}</b> stand for
 124  * themselves.  Nearly all URI schemes currently in use are server-based.  An
 125  * authority component that does not parse in this way is considered to be
 126  * registry-based.
 127  *
 128  * <p> The path component of a hierarchical URI is itself said to be absolute
 129  * if it begins with a slash character ({@code '/'}); otherwise it is
 130  * relative.  The path of a hierarchical URI that is either absolute or
 131  * specifies an authority is always absolute.
 132  *
 133  * <p> All told, then, a URI instance has the following nine components:
 134  *
 135  * <table class="striped" style="margin-left:2em">
 136  * <caption style="display:none">Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment</caption>
 137  * <thead>
 138  * <tr><th scope="col">Component</th><th scope="col">Type</th></tr>
 139  * </thead>
 140  * <tbody style="text-align:left">
 141  * <tr><th scope="row">scheme</th><td>{@code String}</td></tr>
 142  * <tr><th scope="row">scheme-specific-part</th><td>{@code String}</td></tr>
 143  * <tr><th scope="row">authority</th><td>{@code String}</td></tr>
 144  * <tr><th scope="row">user-info</th><td>{@code String}</td></tr>
 145  * <tr><th scope="row">host</th><td>{@code String}</td></tr>
 146  * <tr><th scope="row">port</th><td>{@code int}</td></tr>
 147  * <tr><th scope="row">path</th><td>{@code String}</td></tr>
 148  * <tr><th scope="row">query</th><td>{@code String}</td></tr>
 149  * <tr><th scope="row">fragment</th><td>{@code String}</td></tr>
 150  * </tbody>
 151  * </table>
 152  *
 153  * In a given instance any particular component is either <i>undefined</i> or
 154  * <i>defined</i> with a distinct value.  Undefined string components are
 155  * represented by {@code null}, while undefined integer components are
 156  * represented by {@code -1}.  A string component may be defined to have the
 157  * empty string as its value; this is not equivalent to that component being
 158  * undefined.
 159  *
 160  * <p> Whether a particular component is or is not defined in an instance
 161  * depends upon the type of the URI being represented.  An absolute URI has a
 162  * scheme component.  An opaque URI has a scheme, a scheme-specific part, and
 163  * possibly a fragment, but has no other components.  A hierarchical URI always
 164  * has a path (though it may be empty) and a scheme-specific-part (which at
 165  * least contains the path), and may have any of the other components.  If the
 166  * authority component is present and is server-based then the host component
 167  * will be defined and the user-information and port components may be defined.
 168  *
 169  *
 170  * <h4> Operations on URI instances </h4>
 171  *
 172  * The key operations supported by this class are those of
 173  * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>.
 174  *
 175  * <p> <i>Normalization</i> is the process of removing unnecessary {@code "."}
 176  * and {@code ".."} segments from the path component of a hierarchical URI.
 177  * Each {@code "."} segment is simply removed.  A {@code ".."} segment is
 178  * removed only if it is preceded by a non-{@code ".."} segment.
 179  * Normalization has no effect upon opaque URIs.
 180  *
 181  * <p> <i>Resolution</i> is the process of resolving one URI against another,
 182  * <i>base</i> URI.  The resulting URI is constructed from components of both
 183  * URIs in the manner specified by RFC&nbsp;2396, taking components from the
 184  * base URI for those not specified in the original.  For hierarchical URIs,
 185  * the path of the original is resolved against the path of the base and then
 186  * normalized.  The result, for example, of resolving
 187  *
 188  * <blockquote>
 189  * {@code sample/a/index.html#28}
 190  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 191  * &nbsp;&nbsp;&nbsp;&nbsp;(1)
 192  * </blockquote>
 193  *
 194  * against the base URI {@code http://example.com/languages/java/} is the result
 195  * URI
 196  *
 197  * <blockquote>
 198  * {@code http://example.com/languages/java/sample/a/index.html#28}
 199  * </blockquote>
 200  *
 201  * Resolving the relative URI
 202  *
 203  * <blockquote>
 204  * {@code ../../demo/b/index.html}&nbsp;&nbsp;&nbsp;&nbsp;(2)
 205  * </blockquote>
 206  *
 207  * against this result yields, in turn,
 208  *
 209  * <blockquote>
 210  * {@code http://example.com/languages/java/demo/b/index.html}
 211  * </blockquote>
 212  *
 213  * Resolution of both absolute and relative URIs, and of both absolute and
 214  * relative paths in the case of hierarchical URIs, is supported.  Resolving
 215  * the URI {@code file:///~calendar} against any other URI simply yields the
 216  * original URI, since it is absolute.  Resolving the relative URI (2) above
 217  * against the relative base URI (1) yields the normalized, but still relative,
 218  * URI
 219  *
 220  * <blockquote>
 221  * {@code demo/b/index.html}
 222  * </blockquote>
 223  *
 224  * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any
 225  * two normalized URIs <i>u</i> and&nbsp;<i>v</i>,
 226  *
 227  * <blockquote>
 228  *   <i>u</i>{@code .relativize(}<i>u</i>{@code .resolve(}<i>v</i>{@code )).equals(}<i>v</i>{@code )}&nbsp;&nbsp;and<br>
 229  *   <i>u</i>{@code .resolve(}<i>u</i>{@code .relativize(}<i>v</i>{@code )).equals(}<i>v</i>{@code )}&nbsp;&nbsp;.<br>
 230  * </blockquote>
 231  *
 232  * This operation is often useful when constructing a document containing URIs
 233  * that must be made relative to the base URI of the document wherever
 234  * possible.  For example, relativizing the URI
 235  *
 236  * <blockquote>
 237  * {@code http://example.com/languages/java/sample/a/index.html#28}
 238  * </blockquote>
 239  *
 240  * against the base URI
 241  *
 242  * <blockquote>
 243  * {@code http://example.com/languages/java/}
 244  * </blockquote>
 245  *
 246  * yields the relative URI {@code sample/a/index.html#28}.
 247  *
 248  *
 249  * <h4> Character categories </h4>
 250  *
 251  * RFC&nbsp;2396 specifies precisely which characters are permitted in the
 252  * various components of a URI reference.  The following categories, most of
 253  * which are taken from that specification, are used below to describe these
 254  * constraints:
 255  *
 256  * <table class="striped" style="margin-left:2em">
 257  * <caption style="display:none">Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other</caption>
 258  *   <thead>
 259  *   <tr><th scope="col">Category</th><th scope="col">Description</th></tr>
 260  *   </thead>
 261  *   <tbody style="text-align:left">
 262  *   <tr><th scope="row" style="vertical-align:top">alpha</th>
 263  *       <td>The US-ASCII alphabetic characters,
 264  *        {@code 'A'}&nbsp;through&nbsp;{@code 'Z'}
 265  *        and {@code 'a'}&nbsp;through&nbsp;{@code 'z'}</td></tr>
 266  *   <tr><th scope="row" style="vertical-align:top">digit</th>
 267  *       <td>The US-ASCII decimal digit characters,
 268  *       {@code '0'}&nbsp;through&nbsp;{@code '9'}</td></tr>
 269  *   <tr><th scope="row" style="vertical-align:top">alphanum</th>
 270  *       <td>All <i>alpha</i> and <i>digit</i> characters</td></tr>
 271  *   <tr><th scope="row" style="vertical-align:top">unreserved</th>
 272  *       <td>All <i>alphanum</i> characters together with those in the string
 273  *        {@code "_-!.~'()*"}</td></tr>
 274  *   <tr><th scope="row" style="vertical-align:top">punct</th>
 275  *       <td>The characters in the string {@code ",;:$&+="}</td></tr>
 276  *   <tr><th scope="row" style="vertical-align:top">reserved</th>
 277  *       <td>All <i>punct</i> characters together with those in the string
 278  *        {@code "?/[]@"}</td></tr>
 279  *   <tr><th scope="row" style="vertical-align:top">escaped</th>
 280  *       <td>Escaped octets, that is, triplets consisting of the percent
 281  *           character ({@code '%'}) followed by two hexadecimal digits
 282  *           ({@code '0'}-{@code '9'}, {@code 'A'}-{@code 'F'}, and
 283  *           {@code 'a'}-{@code 'f'})</td></tr>
 284  *   <tr><th scope="row" style="vertical-align:top">other</th>
 285  *       <td>The Unicode characters that are not in the US-ASCII character set,
 286  *           are not control characters (according to the {@link
 287  *           java.lang.Character#isISOControl(char) Character.isISOControl}
 288  *           method), and are not space characters (according to the {@link
 289  *           java.lang.Character#isSpaceChar(char) Character.isSpaceChar}
 290  *           method)&nbsp;&nbsp;<i>(<b>Deviation from RFC 2396</b>, which is
 291  *           limited to US-ASCII)</i></td></tr>
 292  * </tbody>
 293  * </table>
 294  *
 295  * <p><a id="legal-chars"></a> The set of all legal URI characters consists of
 296  * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i>
 297  * characters.
 298  *
 299  *
 300  * <h4> Escaped octets, quotation, encoding, and decoding </h4>
 301  *
 302  * RFC 2396 allows escaped octets to appear in the user-info, path, query, and
 303  * fragment components.  Escaping serves two purposes in URIs:
 304  *
 305  * <ul>
 306  *
 307  *   <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to
 308  *   conform strictly to RFC&nbsp;2396 by not containing any <i>other</i>
 309  *   characters.  </p></li>
 310  *
 311  *   <li><p> To <i>quote</i> characters that are otherwise illegal in a
 312  *   component.  The user-info, path, query, and fragment components differ
 313  *   slightly in terms of which characters are considered legal and illegal.
 314  *   </p></li>
 315  *
 316  * </ul>
 317  *
 318  * These purposes are served in this class by three related operations:
 319  *
 320  * <ul>
 321  *
 322  *   <li><p><a id="encode"></a> A character is <i>encoded</i> by replacing it
 323  *   with the sequence of escaped octets that represent that character in the
 324  *   UTF-8 character set.  The Euro currency symbol ({@code '\u005Cu20AC'}),
 325  *   for example, is encoded as {@code "%E2%82%AC"}.  <i>(<b>Deviation from
 326  *   RFC&nbsp;2396</b>, which does not specify any particular character
 327  *   set.)</i> </p></li>
 328  *
 329  *   <li><p><a id="quote"></a> An illegal character is <i>quoted</i> simply by
 330  *   encoding it.  The space character, for example, is quoted by replacing it
 331  *   with {@code "%20"}.  UTF-8 contains US-ASCII, hence for US-ASCII
 332  *   characters this transformation has exactly the effect required by
 333  *   RFC&nbsp;2396. </p></li>
 334  *
 335  *   <li><p><a id="decode"></a>
 336  *   A sequence of escaped octets is <i>decoded</i> by
 337  *   replacing it with the sequence of characters that it represents in the
 338  *   UTF-8 character set.  UTF-8 contains US-ASCII, hence decoding has the
 339  *   effect of de-quoting any quoted US-ASCII characters as well as that of
 340  *   decoding any encoded non-US-ASCII characters.  If a <a
 341  *   href="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs
 342  *   when decoding the escaped octets then the erroneous octets are replaced by
 343  *   {@code '\u005CuFFFD'}, the Unicode replacement character.  </p></li>
 344  *
 345  * </ul>
 346  *
 347  * These operations are exposed in the constructors and methods of this class
 348  * as follows:
 349  *
 350  * <ul>
 351  *
 352  *   <li><p> The {@linkplain #URI(java.lang.String) single-argument
 353  *   constructor} requires any illegal characters in its argument to be
 354  *   quoted and preserves any escaped octets and <i>other</i> characters that
 355  *   are present.  </p></li>
 356  *
 357  *   <li><p> The {@linkplain
 358  *   #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
 359  *   multi-argument constructors} quote illegal characters as
 360  *   required by the components in which they appear.  The percent character
 361  *   ({@code '%'}) is always quoted by these constructors.  Any <i>other</i>
 362  *   characters are preserved.  </p></li>
 363  *
 364  *   <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath()
 365  *   getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment()
 366  *   getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link
 367  *   #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the
 368  *   values of their corresponding components in raw form, without interpreting
 369  *   any escaped octets.  The strings returned by these methods may contain
 370  *   both escaped octets and <i>other</i> characters, and will not contain any
 371  *   illegal characters.  </p></li>
 372  *
 373  *   <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath()
 374  *   getPath}, {@link #getQuery() getQuery}, {@link #getFragment()
 375  *   getFragment}, {@link #getAuthority() getAuthority}, and {@link
 376  *   #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped
 377  *   octets in their corresponding components.  The strings returned by these
 378  *   methods may contain both <i>other</i> characters and illegal characters,
 379  *   and will not contain any escaped octets.  </p></li>
 380  *
 381  *   <li><p> The {@link #toString() toString} method returns a URI string with
 382  *   all necessary quotation but which may contain <i>other</i> characters.
 383  *   </p></li>
 384  *
 385  *   <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully
 386  *   quoted and encoded URI string that does not contain any <i>other</i>
 387  *   characters.  </p></li>
 388  *
 389  * </ul>
 390  *
 391  *
 392  * <h4> Identities </h4>
 393  *
 394  * For any URI <i>u</i>, it is always the case that
 395  *
 396  * <blockquote>
 397  * {@code new URI(}<i>u</i>{@code .toString()).equals(}<i>u</i>{@code )}&nbsp;.
 398  * </blockquote>
 399  *
 400  * For any URI <i>u</i> that does not contain redundant syntax such as two
 401  * slashes before an empty authority (as in {@code file:///tmp/}&nbsp;) or a
 402  * colon following a host name but no port (as in
 403  * {@code http://java.sun.com:}&nbsp;), and that does not encode characters
 404  * except those that must be quoted, the following identities also hold:
 405  * <pre>
 406  *     new URI(<i>u</i>.getScheme(),
 407  *             <i>u</i>.getSchemeSpecificPart(),
 408  *             <i>u</i>.getFragment())
 409  *     .equals(<i>u</i>)</pre>
 410  * in all cases,
 411  * <pre>
 412  *     new URI(<i>u</i>.getScheme(),
 413  *             <i>u</i>.getAuthority(),
 414  *             <i>u</i>.getPath(), <i>u</i>.getQuery(),
 415  *             <i>u</i>.getFragment())
 416  *     .equals(<i>u</i>)</pre>
 417  * if <i>u</i> is hierarchical, and
 418  * <pre>
 419  *     new URI(<i>u</i>.getScheme(),
 420  *             <i>u</i>.getUserInfo(), <i>u</i>.getHost(), <i>u</i>.getPort(),
 421  *             <i>u</i>.getPath(), <i>u</i>.getQuery(),
 422  *             <i>u</i>.getFragment())
 423  *     .equals(<i>u</i>)</pre>
 424  * if <i>u</i> is hierarchical and has either no authority or a server-based
 425  * authority.
 426  *
 427  *
 428  * <h4> URIs, URLs, and URNs </h4>
 429  *
 430  * A URI is a uniform resource <i>identifier</i> while a URL is a uniform
 431  * resource <i>locator</i>.  Hence every URL is a URI, abstractly speaking, but
 432  * not every URI is a URL.  This is because there is another subcategory of
 433  * URIs, uniform resource <i>names</i> (URNs), which name resources but do not
 434  * specify how to locate them.  The {@code mailto}, {@code news}, and
 435  * {@code isbn} URIs shown above are examples of URNs.
 436  *
 437  * <p> The conceptual distinction between URIs and URLs is reflected in the
 438  * differences between this class and the {@link URL} class.
 439  *
 440  * <p> An instance of this class represents a URI reference in the syntactic
 441  * sense defined by RFC&nbsp;2396.  A URI may be either absolute or relative.
 442  * A URI string is parsed according to the generic syntax without regard to the
 443  * scheme, if any, that it specifies.  No lookup of the host, if any, is
 444  * performed, and no scheme-dependent stream handler is constructed.  Equality,
 445  * hashing, and comparison are defined strictly in terms of the character
 446  * content of the instance.  In other words, a URI instance is little more than
 447  * a structured string that supports the syntactic, scheme-independent
 448  * operations of comparison, normalization, resolution, and relativization.
 449  *
 450  * <p> An instance of the {@link URL} class, by contrast, represents the
 451  * syntactic components of a URL together with some of the information required
 452  * to access the resource that it describes.  A URL must be absolute, that is,
 453  * it must always specify a scheme.  A URL string is parsed according to its
 454  * scheme.  A stream handler is always established for a URL, and in fact it is
 455  * impossible to create a URL instance for a scheme for which no handler is
 456  * available.  Equality and hashing depend upon both the scheme and the
 457  * Internet address of the host, if any; comparison is not defined.  In other
 458  * words, a URL is a structured string that supports the syntactic operation of
 459  * resolution as well as the network I/O operations of looking up the host and
 460  * opening a connection to the specified resource.
 461  *
 462  *
 463  * @author Mark Reinhold
 464  * @since 1.4
 465  *
 466  * @see <a href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279: UTF-8, a
 467  * transformation format of ISO 10646</i></a>, <br><a
 468  * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6 Addressing
 469  * Architecture</i></a>, <br><a
 470  * href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
 471  * Resource Identifiers (URI): Generic Syntax</i></a>, <br><a
 472  * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
 473  * Literal IPv6 Addresses in URLs</i></a>, <br><a
 474  * href="URISyntaxException.html">URISyntaxException</a>
 475  */
 476 
 477 public final class URI
 478     implements Comparable<URI>, Serializable
 479 {
 480 
 481     // Note: Comments containing the word "ASSERT" indicate places where a
 482     // throw of an InternalError should be replaced by an appropriate assertion
 483     // statement once asserts are enabled in the build.
 484 
 485     static final long serialVersionUID = -6052424284110960213L;
 486 
 487 
 488     // -- Properties and components of this instance --
 489 
 490     // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
 491     private transient String scheme;            // null ==> relative URI
 492     private transient String fragment;
 493 
 494     // Hierarchical URI components: [//<authority>]<path>[?<query>]
 495     private transient String authority;         // Registry or server
 496 
 497     // Server-based authority: [<userInfo>@]<host>[:<port>]
 498     private transient String userInfo;
 499     private transient String host;              // null ==> registry-based
 500     private transient int port = -1;            // -1 ==> undefined
 501 
 502     // Remaining components of hierarchical URIs
 503     private transient String path;              // null ==> opaque
 504     private transient String query;
 505 
 506     // The remaining fields may be computed on demand, which is safe even in
 507     // the face of multiple threads racing to initialize them
 508     private transient String schemeSpecificPart;
 509     private transient int hash;        // Zero ==> undefined
 510 
 511     private transient String decodedUserInfo;
 512     private transient String decodedAuthority;
 513     private transient String decodedPath;
 514     private transient String decodedQuery;
 515     private transient String decodedFragment;
 516     private transient String decodedSchemeSpecificPart;
 517 
 518     /**
 519      * The string form of this URI.
 520      *
 521      * @serial
 522      */
 523     private volatile String string;             // The only serializable field
 524 
 525 
 526 
 527     // -- Constructors and factories --
 528 
 529     private URI() { }                           // Used internally
 530 
 531     /**
 532      * Constructs a URI by parsing the given string.
 533      *
 534      * <p> This constructor parses the given string exactly as specified by the
 535      * grammar in <a
 536      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
 537      * Appendix&nbsp;A, <b><i>except for the following deviations:</i></b> </p>
 538      *
 539      * <ul>
 540      *
 541      *   <li><p> An empty authority component is permitted as long as it is
 542      *   followed by a non-empty path, a query component, or a fragment
 543      *   component.  This allows the parsing of URIs such as
 544      *   {@code "file:///foo/bar"}, which seems to be the intent of
 545      *   RFC&nbsp;2396 although the grammar does not permit it.  If the
 546      *   authority component is empty then the user-information, host, and port
 547      *   components are undefined. </p></li>
 548      *
 549      *   <li><p> Empty relative paths are permitted; this seems to be the
 550      *   intent of RFC&nbsp;2396 although the grammar does not permit it.  The
 551      *   primary consequence of this deviation is that a standalone fragment
 552      *   such as {@code "#foo"} parses as a relative URI with an empty path
 553      *   and the given fragment, and can be usefully <a
 554      *   href="#resolve-frag">resolved</a> against a base URI.
 555      *
 556      *   <li><p> IPv4 addresses in host components are parsed rigorously, as
 557      *   specified by <a
 558      *   href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>: Each
 559      *   element of a dotted-quad address must contain no more than three
 560      *   decimal digits.  Each element is further constrained to have a value
 561      *   no greater than 255. </p></li>
 562      *
 563      *   <li> <p> Hostnames in host components that comprise only a single
 564      *   domain label are permitted to start with an <i>alphanum</i>
 565      *   character. This seems to be the intent of <a
 566      *   href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
 567      *   section&nbsp;3.2.2 although the grammar does not permit it. The
 568      *   consequence of this deviation is that the authority component of a
 569      *   hierarchical URI such as {@code s://123}, will parse as a server-based
 570      *   authority. </p></li>
 571      *
 572      *   <li><p> IPv6 addresses are permitted for the host component.  An IPv6
 573      *   address must be enclosed in square brackets ({@code '['} and
 574      *   {@code ']'}) as specified by <a
 575      *   href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>.  The
 576      *   IPv6 address itself must parse according to <a
 577      *   href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>.  IPv6
 578      *   addresses are further constrained to describe no more than sixteen
 579      *   bytes of address information, a constraint implicit in RFC&nbsp;2373
 580      *   but not expressible in the grammar. </p></li>
 581      *
 582      *   <li><p> Characters in the <i>other</i> category are permitted wherever
 583      *   RFC&nbsp;2396 permits <i>escaped</i> octets, that is, in the
 584      *   user-information, path, query, and fragment components, as well as in
 585      *   the authority component if the authority is registry-based.  This
 586      *   allows URIs to contain Unicode characters beyond those in the US-ASCII
 587      *   character set. </p></li>
 588      *
 589      * </ul>
 590      *
 591      * @param  str   The string to be parsed into a URI
 592      *
 593      * @throws  NullPointerException
 594      *          If {@code str} is {@code null}
 595      *
 596      * @throws  URISyntaxException
 597      *          If the given string violates RFC&nbsp;2396, as augmented
 598      *          by the above deviations
 599      */
 600     public URI(String str) throws URISyntaxException {
 601         new Parser(str).parse(false);
 602     }
 603 
 604     /**
 605      * Constructs a hierarchical URI from the given components.
 606      *
 607      * <p> If a scheme is given then the path, if also given, must either be
 608      * empty or begin with a slash character ({@code '/'}).  Otherwise a
 609      * component of the new URI may be left undefined by passing {@code null}
 610      * for the corresponding parameter or, in the case of the {@code port}
 611      * parameter, by passing {@code -1}.
 612      *
 613      * <p> This constructor first builds a URI string from the given components
 614      * according to the rules specified in <a
 615      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
 616      * section&nbsp;5.2, step&nbsp;7: </p>
 617      *
 618      * <ol>
 619      *
 620      *   <li><p> Initially, the result string is empty. </p></li>
 621      *
 622      *   <li><p> If a scheme is given then it is appended to the result,
 623      *   followed by a colon character ({@code ':'}).  </p></li>
 624      *
 625      *   <li><p> If user information, a host, or a port are given then the
 626      *   string {@code "//"} is appended.  </p></li>
 627      *
 628      *   <li><p> If user information is given then it is appended, followed by
 629      *   a commercial-at character ({@code '@'}).  Any character not in the
 630      *   <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
 631      *   categories is <a href="#quote">quoted</a>.  </p></li>
 632      *
 633      *   <li><p> If a host is given then it is appended.  If the host is a
 634      *   literal IPv6 address but is not enclosed in square brackets
 635      *   ({@code '['} and {@code ']'}) then the square brackets are added.
 636      *   </p></li>
 637      *
 638      *   <li><p> If a port number is given then a colon character
 639      *   ({@code ':'}) is appended, followed by the port number in decimal.
 640      *   </p></li>
 641      *
 642      *   <li><p> If a path is given then it is appended.  Any character not in
 643      *   the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
 644      *   categories, and not equal to the slash character ({@code '/'}) or the
 645      *   commercial-at character ({@code '@'}), is quoted.  </p></li>
 646      *
 647      *   <li><p> If a query is given then a question-mark character
 648      *   ({@code '?'}) is appended, followed by the query.  Any character that
 649      *   is not a <a href="#legal-chars">legal URI character</a> is quoted.
 650      *   </p></li>
 651      *
 652      *   <li><p> Finally, if a fragment is given then a hash character
 653      *   ({@code '#'}) is appended, followed by the fragment.  Any character
 654      *   that is not a legal URI character is quoted.  </p></li>
 655      *
 656      * </ol>
 657      *
 658      * <p> The resulting URI string is then parsed as if by invoking the {@link
 659      * #URI(String)} constructor and then invoking the {@link
 660      * #parseServerAuthority()} method upon the result; this may cause a {@link
 661      * URISyntaxException} to be thrown.  </p>
 662      *
 663      * @param   scheme    Scheme name
 664      * @param   userInfo  User name and authorization information
 665      * @param   host      Host name
 666      * @param   port      Port number
 667      * @param   path      Path
 668      * @param   query     Query
 669      * @param   fragment  Fragment
 670      *
 671      * @throws URISyntaxException
 672      *         If both a scheme and a path are given but the path is relative,
 673      *         if the URI string constructed from the given components violates
 674      *         RFC&nbsp;2396, or if the authority component of the string is
 675      *         present but cannot be parsed as a server-based authority
 676      */
 677     public URI(String scheme,
 678                String userInfo, String host, int port,
 679                String path, String query, String fragment)
 680         throws URISyntaxException
 681     {
 682         String s = toString(scheme, null,
 683                             null, userInfo, host, port,
 684                             path, query, fragment);
 685         checkPath(s, scheme, path);
 686         new Parser(s).parse(true);
 687     }
 688 
 689     /**
 690      * Constructs a hierarchical URI from the given components.
 691      *
 692      * <p> If a scheme is given then the path, if also given, must either be
 693      * empty or begin with a slash character ({@code '/'}).  Otherwise a
 694      * component of the new URI may be left undefined by passing {@code null}
 695      * for the corresponding parameter.
 696      *
 697      * <p> This constructor first builds a URI string from the given components
 698      * according to the rules specified in <a
 699      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
 700      * section&nbsp;5.2, step&nbsp;7: </p>
 701      *
 702      * <ol>
 703      *
 704      *   <li><p> Initially, the result string is empty.  </p></li>
 705      *
 706      *   <li><p> If a scheme is given then it is appended to the result,
 707      *   followed by a colon character ({@code ':'}).  </p></li>
 708      *
 709      *   <li><p> If an authority is given then the string {@code "//"} is
 710      *   appended, followed by the authority.  If the authority contains a
 711      *   literal IPv6 address then the address must be enclosed in square
 712      *   brackets ({@code '['} and {@code ']'}).  Any character not in the
 713      *   <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
 714      *   categories, and not equal to the commercial-at character
 715      *   ({@code '@'}), is <a href="#quote">quoted</a>.  </p></li>
 716      *
 717      *   <li><p> If a path is given then it is appended.  Any character not in
 718      *   the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
 719      *   categories, and not equal to the slash character ({@code '/'}) or the
 720      *   commercial-at character ({@code '@'}), is quoted.  </p></li>
 721      *
 722      *   <li><p> If a query is given then a question-mark character
 723      *   ({@code '?'}) is appended, followed by the query.  Any character that
 724      *   is not a <a href="#legal-chars">legal URI character</a> is quoted.
 725      *   </p></li>
 726      *
 727      *   <li><p> Finally, if a fragment is given then a hash character
 728      *   ({@code '#'}) is appended, followed by the fragment.  Any character
 729      *   that is not a legal URI character is quoted.  </p></li>
 730      *
 731      * </ol>
 732      *
 733      * <p> The resulting URI string is then parsed as if by invoking the {@link
 734      * #URI(String)} constructor and then invoking the {@link
 735      * #parseServerAuthority()} method upon the result; this may cause a {@link
 736      * URISyntaxException} to be thrown.  </p>
 737      *
 738      * @param   scheme     Scheme name
 739      * @param   authority  Authority
 740      * @param   path       Path
 741      * @param   query      Query
 742      * @param   fragment   Fragment
 743      *
 744      * @throws URISyntaxException
 745      *         If both a scheme and a path are given but the path is relative,
 746      *         if the URI string constructed from the given components violates
 747      *         RFC&nbsp;2396, or if the authority component of the string is
 748      *         present but cannot be parsed as a server-based authority
 749      */
 750     public URI(String scheme,
 751                String authority,
 752                String path, String query, String fragment)
 753         throws URISyntaxException
 754     {
 755         String s = toString(scheme, null,
 756                             authority, null, null, -1,
 757                             path, query, fragment);
 758         checkPath(s, scheme, path);
 759         new Parser(s).parse(false);
 760     }
 761 
 762     /**
 763      * Constructs a hierarchical URI from the given components.
 764      *
 765      * <p> A component may be left undefined by passing {@code null}.
 766      *
 767      * <p> This convenience constructor works as if by invoking the
 768      * seven-argument constructor as follows:
 769      *
 770      * <blockquote>
 771      * {@code new} {@link #URI(String, String, String, int, String, String, String)
 772      * URI}{@code (scheme, null, host, -1, path, null, fragment);}
 773      * </blockquote>
 774      *
 775      * @param   scheme    Scheme name
 776      * @param   host      Host name
 777      * @param   path      Path
 778      * @param   fragment  Fragment
 779      *
 780      * @throws  URISyntaxException
 781      *          If the URI string constructed from the given components
 782      *          violates RFC&nbsp;2396
 783      */
 784     public URI(String scheme, String host, String path, String fragment)
 785         throws URISyntaxException
 786     {
 787         this(scheme, null, host, -1, path, null, fragment);
 788     }
 789 
 790     /**
 791      * Constructs a URI from the given components.
 792      *
 793      * <p> A component may be left undefined by passing {@code null}.
 794      *
 795      * <p> This constructor first builds a URI in string form using the given
 796      * components as follows:  </p>
 797      *
 798      * <ol>
 799      *
 800      *   <li><p> Initially, the result string is empty.  </p></li>
 801      *
 802      *   <li><p> If a scheme is given then it is appended to the result,
 803      *   followed by a colon character ({@code ':'}).  </p></li>
 804      *
 805      *   <li><p> If a scheme-specific part is given then it is appended.  Any
 806      *   character that is not a <a href="#legal-chars">legal URI character</a>
 807      *   is <a href="#quote">quoted</a>.  </p></li>
 808      *
 809      *   <li><p> Finally, if a fragment is given then a hash character
 810      *   ({@code '#'}) is appended to the string, followed by the fragment.
 811      *   Any character that is not a legal URI character is quoted.  </p></li>
 812      *
 813      * </ol>
 814      *
 815      * <p> The resulting URI string is then parsed in order to create the new
 816      * URI instance as if by invoking the {@link #URI(String)} constructor;
 817      * this may cause a {@link URISyntaxException} to be thrown.  </p>
 818      *
 819      * @param   scheme    Scheme name
 820      * @param   ssp       Scheme-specific part
 821      * @param   fragment  Fragment
 822      *
 823      * @throws  URISyntaxException
 824      *          If the URI string constructed from the given components
 825      *          violates RFC&nbsp;2396
 826      */
 827     public URI(String scheme, String ssp, String fragment)
 828         throws URISyntaxException
 829     {
 830         new Parser(toString(scheme, ssp,
 831                             null, null, null, -1,
 832                             null, null, fragment))
 833             .parse(false);
 834     }
 835 
 836     /**
 837      * Constructs a simple URI consisting of only a scheme and a pre-validated
 838      * path. Provides a fast-path for some internal cases.
 839      */
 840     URI(String scheme, String path) {
 841         assert validSchemeAndPath(scheme, path);
 842         this.scheme = scheme;
 843         this.path = path;
 844     }
 845 
 846     private static boolean validSchemeAndPath(String scheme, String path) {
 847         try {
 848             URI u = new URI(scheme + ":" + path);
 849             return scheme.equals(u.scheme) && path.equals(u.path);
 850         } catch (URISyntaxException e) {
 851             return false;
 852         }
 853     }
 854 
 855     /**
 856      * Creates a URI by parsing the given string.
 857      *
 858      * <p> This convenience factory method works as if by invoking the {@link
 859      * #URI(String)} constructor; any {@link URISyntaxException} thrown by the
 860      * constructor is caught and wrapped in a new {@link
 861      * IllegalArgumentException} object, which is then thrown.
 862      *
 863      * <p> This method is provided for use in situations where it is known that
 864      * the given string is a legal URI, for example for URI constants declared
 865      * within in a program, and so it would be considered a programming error
 866      * for the string not to parse as such.  The constructors, which throw
 867      * {@link URISyntaxException} directly, should be used situations where a
 868      * URI is being constructed from user input or from some other source that
 869      * may be prone to errors.  </p>
 870      *
 871      * @param  str   The string to be parsed into a URI
 872      * @return The new URI
 873      *
 874      * @throws  NullPointerException
 875      *          If {@code str} is {@code null}
 876      *
 877      * @throws  IllegalArgumentException
 878      *          If the given string violates RFC&nbsp;2396
 879      */
 880     public static URI create(String str) {
 881         try {
 882             return new URI(str);
 883         } catch (URISyntaxException x) {
 884             throw new IllegalArgumentException(x.getMessage(), x);
 885         }
 886     }
 887 
 888 
 889     // -- Operations --
 890 
 891     /**
 892      * Attempts to parse this URI's authority component, if defined, into
 893      * user-information, host, and port components.
 894      *
 895      * <p> If this URI's authority component has already been recognized as
 896      * being server-based then it will already have been parsed into
 897      * user-information, host, and port components.  In this case, or if this
 898      * URI has no authority component, this method simply returns this URI.
 899      *
 900      * <p> Otherwise this method attempts once more to parse the authority
 901      * component into user-information, host, and port components, and throws
 902      * an exception describing why the authority component could not be parsed
 903      * in that way.
 904      *
 905      * <p> This method is provided because the generic URI syntax specified in
 906      * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
 907      * cannot always distinguish a malformed server-based authority from a
 908      * legitimate registry-based authority.  It must therefore treat some
 909      * instances of the former as instances of the latter.  The authority
 910      * component in the URI string {@code "//foo:bar"}, for example, is not a
 911      * legal server-based authority but it is legal as a registry-based
 912      * authority.
 913      *
 914      * <p> In many common situations, for example when working URIs that are
 915      * known to be either URNs or URLs, the hierarchical URIs being used will
 916      * always be server-based.  They therefore must either be parsed as such or
 917      * treated as an error.  In these cases a statement such as
 918      *
 919      * <blockquote>
 920      * {@code URI }<i>u</i>{@code  = new URI(str).parseServerAuthority();}
 921      * </blockquote>
 922      *
 923      * <p> can be used to ensure that <i>u</i> always refers to a URI that, if
 924      * it has an authority component, has a server-based authority with proper
 925      * user-information, host, and port components.  Invoking this method also
 926      * ensures that if the authority could not be parsed in that way then an
 927      * appropriate diagnostic message can be issued based upon the exception
 928      * that is thrown. </p>
 929      *
 930      * @return  A URI whose authority field has been parsed
 931      *          as a server-based authority
 932      *
 933      * @throws  URISyntaxException
 934      *          If the authority component of this URI is defined
 935      *          but cannot be parsed as a server-based authority
 936      *          according to RFC&nbsp;2396
 937      */
 938     public URI parseServerAuthority()
 939         throws URISyntaxException
 940     {
 941         // We could be clever and cache the error message and index from the
 942         // exception thrown during the original parse, but that would require
 943         // either more fields or a more-obscure representation.
 944         if ((host != null) || (authority == null))
 945             return this;
 946         new Parser(toString()).parse(true);
 947         return this;
 948     }
 949 
 950     /**
 951      * Normalizes this URI's path.
 952      *
 953      * <p> If this URI is opaque, or if its path is already in normal form,
 954      * then this URI is returned.  Otherwise a new URI is constructed that is
 955      * identical to this URI except that its path is computed by normalizing
 956      * this URI's path in a manner consistent with <a
 957      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
 958      * section&nbsp;5.2, step&nbsp;6, sub-steps&nbsp;c through&nbsp;f; that is:
 959      * </p>
 960      *
 961      * <ol>
 962      *
 963      *   <li><p> All {@code "."} segments are removed. </p></li>
 964      *
 965      *   <li><p> If a {@code ".."} segment is preceded by a non-{@code ".."}
 966      *   segment then both of these segments are removed.  This step is
 967      *   repeated until it is no longer applicable. </p></li>
 968      *
 969      *   <li><p> If the path is relative, and if its first segment contains a
 970      *   colon character ({@code ':'}), then a {@code "."} segment is
 971      *   prepended.  This prevents a relative URI with a path such as
 972      *   {@code "a:b/c/d"} from later being re-parsed as an opaque URI with a
 973      *   scheme of {@code "a"} and a scheme-specific part of {@code "b/c/d"}.
 974      *   <b><i>(Deviation from RFC&nbsp;2396)</i></b> </p></li>
 975      *
 976      * </ol>
 977      *
 978      * <p> A normalized path will begin with one or more {@code ".."} segments
 979      * if there were insufficient non-{@code ".."} segments preceding them to
 980      * allow their removal.  A normalized path will begin with a {@code "."}
 981      * segment if one was inserted by step 3 above.  Otherwise, a normalized
 982      * path will not contain any {@code "."} or {@code ".."} segments. </p>
 983      *
 984      * @return  A URI equivalent to this URI,
 985      *          but whose path is in normal form
 986      */
 987     public URI normalize() {
 988         return normalize(this);
 989     }
 990 
 991     /**
 992      * Resolves the given URI against this URI.
 993      *
 994      * <p> If the given URI is already absolute, or if this URI is opaque, then
 995      * the given URI is returned.
 996      *
 997      * <p><a id="resolve-frag"></a> If the given URI's fragment component is
 998      * defined, its path component is empty, and its scheme, authority, and
 999      * query components are undefined, then a URI with the given fragment but
1000      * with all other components equal to those of this URI is returned.  This
1001      * allows a URI representing a standalone fragment reference, such as
1002      * {@code "#foo"}, to be usefully resolved against a base URI.
1003      *
1004      * <p> Otherwise this method constructs a new hierarchical URI in a manner
1005      * consistent with <a
1006      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
1007      * section&nbsp;5.2; that is: </p>
1008      *
1009      * <ol>
1010      *
1011      *   <li><p> A new URI is constructed with this URI's scheme and the given
1012      *   URI's query and fragment components. </p></li>
1013      *
1014      *   <li><p> If the given URI has an authority component then the new URI's
1015      *   authority and path are taken from the given URI. </p></li>
1016      *
1017      *   <li><p> Otherwise the new URI's authority component is copied from
1018      *   this URI, and its path is computed as follows: </p>
1019      *
1020      *   <ol>
1021      *
1022      *     <li><p> If the given URI's path is absolute then the new URI's path
1023      *     is taken from the given URI. </p></li>
1024      *
1025      *     <li><p> Otherwise the given URI's path is relative, and so the new
1026      *     URI's path is computed by resolving the path of the given URI
1027      *     against the path of this URI.  This is done by concatenating all but
1028      *     the last segment of this URI's path, if any, with the given URI's
1029      *     path and then normalizing the result as if by invoking the {@link
1030      *     #normalize() normalize} method. </p></li>
1031      *
1032      *   </ol></li>
1033      *
1034      * </ol>
1035      *
1036      * <p> The result of this method is absolute if, and only if, either this
1037      * URI is absolute or the given URI is absolute.  </p>
1038      *
1039      * @param  uri  The URI to be resolved against this URI
1040      * @return The resulting URI
1041      *
1042      * @throws  NullPointerException
1043      *          If {@code uri} is {@code null}
1044      */
1045     public URI resolve(URI uri) {
1046         return resolve(this, uri);
1047     }
1048 
1049     /**
1050      * Constructs a new URI by parsing the given string and then resolving it
1051      * against this URI.
1052      *
1053      * <p> This convenience method works as if invoking it were equivalent to
1054      * evaluating the expression {@link #resolve(java.net.URI)
1055      * resolve}{@code (URI.}{@link #create(String) create}{@code (str))}. </p>
1056      *
1057      * @param  str   The string to be parsed into a URI
1058      * @return The resulting URI
1059      *
1060      * @throws  NullPointerException
1061      *          If {@code str} is {@code null}
1062      *
1063      * @throws  IllegalArgumentException
1064      *          If the given string violates RFC&nbsp;2396
1065      */
1066     public URI resolve(String str) {
1067         return resolve(URI.create(str));
1068     }
1069 
1070     /**
1071      * Relativizes the given URI against this URI.
1072      *
1073      * <p> The relativization of the given URI against this URI is computed as
1074      * follows: </p>
1075      *
1076      * <ol>
1077      *
1078      *   <li><p> If either this URI or the given URI are opaque, or if the
1079      *   scheme and authority components of the two URIs are not identical, or
1080      *   if the path of this URI is not a prefix of the path of the given URI,
1081      *   then the given URI is returned. </p></li>
1082      *
1083      *   <li><p> Otherwise a new relative hierarchical URI is constructed with
1084      *   query and fragment components taken from the given URI and with a path
1085      *   component computed by removing this URI's path from the beginning of
1086      *   the given URI's path. </p></li>
1087      *
1088      * </ol>
1089      *
1090      * @param  uri  The URI to be relativized against this URI
1091      * @return The resulting URI
1092      *
1093      * @throws  NullPointerException
1094      *          If {@code uri} is {@code null}
1095      */
1096     public URI relativize(URI uri) {
1097         return relativize(this, uri);
1098     }
1099 
1100     /**
1101      * Constructs a URL from this URI.
1102      *
1103      * <p> This convenience method works as if invoking it were equivalent to
1104      * evaluating the expression {@code new URL(this.toString())} after
1105      * first checking that this URI is absolute. </p>
1106      *
1107      * @return  A URL constructed from this URI
1108      *
1109      * @throws  IllegalArgumentException
1110      *          If this URL is not absolute
1111      *
1112      * @throws  MalformedURLException
1113      *          If a protocol handler for the URL could not be found,
1114      *          or if some other error occurred while constructing the URL
1115      */
1116     public URL toURL() throws MalformedURLException {
1117         return URL.fromURI(this);
1118     }
1119 
1120     // -- Component access methods --
1121 
1122     /**
1123      * Returns the scheme component of this URI.
1124      *
1125      * <p> The scheme component of a URI, if defined, only contains characters
1126      * in the <i>alphanum</i> category and in the string {@code "-.+"}.  A
1127      * scheme always starts with an <i>alpha</i> character. <p>
1128      *
1129      * The scheme component of a URI cannot contain escaped octets, hence this
1130      * method does not perform any decoding.
1131      *
1132      * @return  The scheme component of this URI,
1133      *          or {@code null} if the scheme is undefined
1134      */
1135     public String getScheme() {
1136         return scheme;
1137     }
1138 
1139     /**
1140      * Tells whether or not this URI is absolute.
1141      *
1142      * <p> A URI is absolute if, and only if, it has a scheme component. </p>
1143      *
1144      * @return  {@code true} if, and only if, this URI is absolute
1145      */
1146     public boolean isAbsolute() {
1147         return scheme != null;
1148     }
1149 
1150     /**
1151      * Tells whether or not this URI is opaque.
1152      *
1153      * <p> A URI is opaque if, and only if, it is absolute and its
1154      * scheme-specific part does not begin with a slash character ('/').
1155      * An opaque URI has a scheme, a scheme-specific part, and possibly
1156      * a fragment; all other components are undefined. </p>
1157      *
1158      * @return  {@code true} if, and only if, this URI is opaque
1159      */
1160     public boolean isOpaque() {
1161         return path == null;
1162     }
1163 
1164     /**
1165      * Returns the raw scheme-specific part of this URI.  The scheme-specific
1166      * part is never undefined, though it may be empty.
1167      *
1168      * <p> The scheme-specific part of a URI only contains legal URI
1169      * characters. </p>
1170      *
1171      * @return  The raw scheme-specific part of this URI
1172      *          (never {@code null})
1173      */
1174     public String getRawSchemeSpecificPart() {
1175         String part = schemeSpecificPart;
1176         if (part != null) {
1177             return part;
1178         }
1179 
1180         String s = string;
1181         if (s != null) {
1182             // if string is defined, components will have been parsed
1183             int start = 0;
1184             int end = s.length();
1185             if (scheme != null) {
1186                 start = scheme.length() + 1;
1187             }
1188             if (fragment != null) {
1189                 end -= fragment.length() + 1;
1190             }
1191             if (path != null && path.length() == end - start) {
1192                 part = path;
1193             } else {
1194                 part = s.substring(start, end);
1195             }
1196         } else {
1197             StringBuilder sb = new StringBuilder();
1198             appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
1199                                  host, port, getPath(), getQuery());
1200             part = sb.toString();
1201         }
1202         return schemeSpecificPart = part;
1203     }
1204 
1205     /**
1206      * Returns the decoded scheme-specific part of this URI.
1207      *
1208      * <p> The string returned by this method is equal to that returned by the
1209      * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method
1210      * except that all sequences of escaped octets are <a
1211      * href="#decode">decoded</a>.  </p>
1212      *
1213      * @return  The decoded scheme-specific part of this URI
1214      *          (never {@code null})
1215      */
1216     public String getSchemeSpecificPart() {
1217         String part = decodedSchemeSpecificPart;
1218         if (part == null) {
1219             decodedSchemeSpecificPart = part = decode(getRawSchemeSpecificPart());
1220         }
1221         return part;
1222     }
1223 
1224     /**
1225      * Returns the raw authority component of this URI.
1226      *
1227      * <p> The authority component of a URI, if defined, only contains the
1228      * commercial-at character ({@code '@'}) and characters in the
1229      * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and <i>other</i>
1230      * categories.  If the authority is server-based then it is further
1231      * constrained to have valid user-information, host, and port
1232      * components. </p>
1233      *
1234      * @return  The raw authority component of this URI,
1235      *          or {@code null} if the authority is undefined
1236      */
1237     public String getRawAuthority() {
1238         return authority;
1239     }
1240 
1241     /**
1242      * Returns the decoded authority component of this URI.
1243      *
1244      * <p> The string returned by this method is equal to that returned by the
1245      * {@link #getRawAuthority() getRawAuthority} method except that all
1246      * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
1247      *
1248      * @return  The decoded authority component of this URI,
1249      *          or {@code null} if the authority is undefined
1250      */
1251     public String getAuthority() {
1252         String auth = decodedAuthority;
1253         if ((auth == null) && (authority != null)) {
1254             decodedAuthority = auth = decode(authority);
1255         }
1256         return auth;
1257     }
1258 
1259     /**
1260      * Returns the raw user-information component of this URI.
1261      *
1262      * <p> The user-information component of a URI, if defined, only contains
1263      * characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and
1264      * <i>other</i> categories. </p>
1265      *
1266      * @return  The raw user-information component of this URI,
1267      *          or {@code null} if the user information is undefined
1268      */
1269     public String getRawUserInfo() {
1270         return userInfo;
1271     }
1272 
1273     /**
1274      * Returns the decoded user-information component of this URI.
1275      *
1276      * <p> The string returned by this method is equal to that returned by the
1277      * {@link #getRawUserInfo() getRawUserInfo} method except that all
1278      * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
1279      *
1280      * @return  The decoded user-information component of this URI,
1281      *          or {@code null} if the user information is undefined
1282      */
1283     public String getUserInfo() {
1284         String user = decodedUserInfo;
1285         if ((user == null) && (userInfo != null)) {
1286             decodedUserInfo = user = decode(userInfo);
1287         }
1288         return user;
1289     }
1290 
1291     /**
1292      * Returns the host component of this URI.
1293      *
1294      * <p> The host component of a URI, if defined, will have one of the
1295      * following forms: </p>
1296      *
1297      * <ul>
1298      *
1299      *   <li><p> A domain name consisting of one or more <i>labels</i>
1300      *   separated by period characters ({@code '.'}), optionally followed by
1301      *   a period character.  Each label consists of <i>alphanum</i> characters
1302      *   as well as hyphen characters ({@code '-'}), though hyphens never
1303      *   occur as the first or last characters in a label. The rightmost
1304      *   label of a domain name consisting of two or more labels, begins
1305      *   with an <i>alpha</i> character. </li>
1306      *
1307      *   <li><p> A dotted-quad IPv4 address of the form
1308      *   <i>digit</i>{@code +.}<i>digit</i>{@code +.}<i>digit</i>{@code +.}<i>digit</i>{@code +},
1309      *   where no <i>digit</i> sequence is longer than three characters and no
1310      *   sequence has a value larger than 255. </p></li>
1311      *
1312      *   <li><p> An IPv6 address enclosed in square brackets ({@code '['} and
1313      *   {@code ']'}) and consisting of hexadecimal digits, colon characters
1314      *   ({@code ':'}), and possibly an embedded IPv4 address.  The full
1315      *   syntax of IPv6 addresses is specified in <a
1316      *   href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6
1317      *   Addressing Architecture</i></a>.  </p></li>
1318      *
1319      * </ul>
1320      *
1321      * The host component of a URI cannot contain escaped octets, hence this
1322      * method does not perform any decoding.
1323      *
1324      * @return  The host component of this URI,
1325      *          or {@code null} if the host is undefined
1326      */
1327     public String getHost() {
1328         return host;
1329     }
1330 
1331     /**
1332      * Returns the port number of this URI.
1333      *
1334      * <p> The port component of a URI, if defined, is a non-negative
1335      * integer. </p>
1336      *
1337      * @return  The port component of this URI,
1338      *          or {@code -1} if the port is undefined
1339      */
1340     public int getPort() {
1341         return port;
1342     }
1343 
1344     /**
1345      * Returns the raw path component of this URI.
1346      *
1347      * <p> The path component of a URI, if defined, only contains the slash
1348      * character ({@code '/'}), the commercial-at character ({@code '@'}),
1349      * and characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>,
1350      * and <i>other</i> categories. </p>
1351      *
1352      * @return  The path component of this URI,
1353      *          or {@code null} if the path is undefined
1354      */
1355     public String getRawPath() {
1356         return path;
1357     }
1358 
1359     /**
1360      * Returns the decoded path component of this URI.
1361      *
1362      * <p> The string returned by this method is equal to that returned by the
1363      * {@link #getRawPath() getRawPath} method except that all sequences of
1364      * escaped octets are <a href="#decode">decoded</a>.  </p>
1365      *
1366      * @return  The decoded path component of this URI,
1367      *          or {@code null} if the path is undefined
1368      */
1369     public String getPath() {
1370         String decoded = decodedPath;
1371         if ((decoded == null) && (path != null)) {
1372             decodedPath = decoded = decode(path);
1373         }
1374         return decoded;
1375     }
1376 
1377     /**
1378      * Returns the raw query component of this URI.
1379      *
1380      * <p> The query component of a URI, if defined, only contains legal URI
1381      * characters. </p>
1382      *
1383      * @return  The raw query component of this URI,
1384      *          or {@code null} if the query is undefined
1385      */
1386     public String getRawQuery() {
1387         return query;
1388     }
1389 
1390     /**
1391      * Returns the decoded query component of this URI.
1392      *
1393      * <p> The string returned by this method is equal to that returned by the
1394      * {@link #getRawQuery() getRawQuery} method except that all sequences of
1395      * escaped octets are <a href="#decode">decoded</a>.  </p>
1396      *
1397      * @return  The decoded query component of this URI,
1398      *          or {@code null} if the query is undefined
1399      */
1400     public String getQuery() {
1401         String decoded = decodedQuery;
1402         if ((decoded == null) && (query != null)) {
1403             decodedQuery = decoded = decode(query, false);
1404         }
1405         return decoded;
1406     }
1407 
1408     /**
1409      * Returns the raw fragment component of this URI.
1410      *
1411      * <p> The fragment component of a URI, if defined, only contains legal URI
1412      * characters. </p>
1413      *
1414      * @return  The raw fragment component of this URI,
1415      *          or {@code null} if the fragment is undefined
1416      */
1417     public String getRawFragment() {
1418         return fragment;
1419     }
1420 
1421     /**
1422      * Returns the decoded fragment component of this URI.
1423      *
1424      * <p> The string returned by this method is equal to that returned by the
1425      * {@link #getRawFragment() getRawFragment} method except that all
1426      * sequences of escaped octets are <a href="#decode">decoded</a>.  </p>
1427      *
1428      * @return  The decoded fragment component of this URI,
1429      *          or {@code null} if the fragment is undefined
1430      */
1431     public String getFragment() {
1432         String decoded = decodedFragment;
1433         if ((decoded == null) && (fragment != null)) {
1434             decodedFragment = decoded = decode(fragment, false);
1435         }
1436         return decoded;
1437     }
1438 
1439 
1440     // -- Equality, comparison, hash code, toString, and serialization --
1441 
1442     /**
1443      * Tests this URI for equality with another object.
1444      *
1445      * <p> If the given object is not a URI then this method immediately
1446      * returns {@code false}.
1447      *
1448      * <p> For two URIs to be considered equal requires that either both are
1449      * opaque or both are hierarchical.  Their schemes must either both be
1450      * undefined or else be equal without regard to case. Their fragments
1451      * must either both be undefined or else be equal.
1452      *
1453      * <p> For two opaque URIs to be considered equal, their scheme-specific
1454      * parts must be equal.
1455      *
1456      * <p> For two hierarchical URIs to be considered equal, their paths must
1457      * be equal and their queries must either both be undefined or else be
1458      * equal.  Their authorities must either both be undefined, or both be
1459      * registry-based, or both be server-based.  If their authorities are
1460      * defined and are registry-based, then they must be equal.  If their
1461      * authorities are defined and are server-based, then their hosts must be
1462      * equal without regard to case, their port numbers must be equal, and
1463      * their user-information components must be equal.
1464      *
1465      * <p> When testing the user-information, path, query, fragment, authority,
1466      * or scheme-specific parts of two URIs for equality, the raw forms rather
1467      * than the encoded forms of these components are compared and the
1468      * hexadecimal digits of escaped octets are compared without regard to
1469      * case.
1470      *
1471      * <p> This method satisfies the general contract of the {@link
1472      * java.lang.Object#equals(Object) Object.equals} method. </p>
1473      *
1474      * @param   ob   The object to which this object is to be compared
1475      *
1476      * @return  {@code true} if, and only if, the given object is a URI that
1477      *          is identical to this URI
1478      */
1479     public boolean equals(Object ob) {
1480         if (ob == this)
1481             return true;
1482         if (!(ob instanceof URI))
1483             return false;
1484         URI that = (URI)ob;
1485         if (this.isOpaque() != that.isOpaque()) return false;
1486         if (!equalIgnoringCase(this.scheme, that.scheme)) return false;
1487         if (!equal(this.fragment, that.fragment)) return false;
1488 
1489         // Opaque
1490         if (this.isOpaque())
1491             return equal(this.schemeSpecificPart, that.schemeSpecificPart);
1492 
1493         // Hierarchical
1494         if (!equal(this.path, that.path)) return false;
1495         if (!equal(this.query, that.query)) return false;
1496 
1497         // Authorities
1498         if (this.authority == that.authority) return true;
1499         if (this.host != null) {
1500             // Server-based
1501             if (!equal(this.userInfo, that.userInfo)) return false;
1502             if (!equalIgnoringCase(this.host, that.host)) return false;
1503             if (this.port != that.port) return false;
1504         } else if (this.authority != null) {
1505             // Registry-based
1506             if (!equal(this.authority, that.authority)) return false;
1507         } else if (this.authority != that.authority) {
1508             return false;
1509         }
1510 
1511         return true;
1512     }
1513 
1514     /**
1515      * Returns a hash-code value for this URI.  The hash code is based upon all
1516      * of the URI's components, and satisfies the general contract of the
1517      * {@link java.lang.Object#hashCode() Object.hashCode} method.
1518      *
1519      * @return  A hash-code value for this URI
1520      */
1521     public int hashCode() {
1522         int h = hash;
1523         if (h == 0) {
1524             h = hashIgnoringCase(0, scheme);
1525             h = hash(h, fragment);
1526             if (isOpaque()) {
1527                 h = hash(h, schemeSpecificPart);
1528             } else {
1529                 h = hash(h, path);
1530                 h = hash(h, query);
1531                 if (host != null) {
1532                     h = hash(h, userInfo);
1533                     h = hashIgnoringCase(h, host);
1534                     h += 1949 * port;
1535                 } else {
1536                     h = hash(h, authority);
1537                 }
1538             }
1539             if (h != 0) {
1540                 hash = h;
1541             }
1542         }
1543         return h;
1544     }
1545 
1546     /**
1547      * Compares this URI to another object, which must be a URI.
1548      *
1549      * <p> When comparing corresponding components of two URIs, if one
1550      * component is undefined but the other is defined then the first is
1551      * considered to be less than the second.  Unless otherwise noted, string
1552      * components are ordered according to their natural, case-sensitive
1553      * ordering as defined by the {@link java.lang.String#compareTo(Object)
1554      * String.compareTo} method.  String components that are subject to
1555      * encoding are compared by comparing their raw forms rather than their
1556      * encoded forms.
1557      *
1558      * <p> The ordering of URIs is defined as follows: </p>
1559      *
1560      * <ul>
1561      *
1562      *   <li><p> Two URIs with different schemes are ordered according the
1563      *   ordering of their schemes, without regard to case. </p></li>
1564      *
1565      *   <li><p> A hierarchical URI is considered to be less than an opaque URI
1566      *   with an identical scheme. </p></li>
1567      *
1568      *   <li><p> Two opaque URIs with identical schemes are ordered according
1569      *   to the ordering of their scheme-specific parts. </p></li>
1570      *
1571      *   <li><p> Two opaque URIs with identical schemes and scheme-specific
1572      *   parts are ordered according to the ordering of their
1573      *   fragments. </p></li>
1574      *
1575      *   <li><p> Two hierarchical URIs with identical schemes are ordered
1576      *   according to the ordering of their authority components: </p>
1577      *
1578      *   <ul>
1579      *
1580      *     <li><p> If both authority components are server-based then the URIs
1581      *     are ordered according to their user-information components; if these
1582      *     components are identical then the URIs are ordered according to the
1583      *     ordering of their hosts, without regard to case; if the hosts are
1584      *     identical then the URIs are ordered according to the ordering of
1585      *     their ports. </p></li>
1586      *
1587      *     <li><p> If one or both authority components are registry-based then
1588      *     the URIs are ordered according to the ordering of their authority
1589      *     components. </p></li>
1590      *
1591      *   </ul></li>
1592      *
1593      *   <li><p> Finally, two hierarchical URIs with identical schemes and
1594      *   authority components are ordered according to the ordering of their
1595      *   paths; if their paths are identical then they are ordered according to
1596      *   the ordering of their queries; if the queries are identical then they
1597      *   are ordered according to the order of their fragments. </p></li>
1598      *
1599      * </ul>
1600      *
1601      * <p> This method satisfies the general contract of the {@link
1602      * java.lang.Comparable#compareTo(Object) Comparable.compareTo}
1603      * method. </p>
1604      *
1605      * @param   that
1606      *          The object to which this URI is to be compared
1607      *
1608      * @return  A negative integer, zero, or a positive integer as this URI is
1609      *          less than, equal to, or greater than the given URI
1610      *
1611      * @throws  ClassCastException
1612      *          If the given object is not a URI
1613      */
1614     public int compareTo(URI that) {
1615         int c;
1616 
1617         if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0)
1618             return c;
1619 
1620         if (this.isOpaque()) {
1621             if (that.isOpaque()) {
1622                 // Both opaque
1623                 if ((c = compare(this.schemeSpecificPart,
1624                                  that.schemeSpecificPart)) != 0)
1625                     return c;
1626                 return compare(this.fragment, that.fragment);
1627             }
1628             return +1;                  // Opaque > hierarchical
1629         } else if (that.isOpaque()) {
1630             return -1;                  // Hierarchical < opaque
1631         }
1632 
1633         // Hierarchical
1634         if ((this.host != null) && (that.host != null)) {
1635             // Both server-based
1636             if ((c = compare(this.userInfo, that.userInfo)) != 0)
1637                 return c;
1638             if ((c = compareIgnoringCase(this.host, that.host)) != 0)
1639                 return c;
1640             if ((c = this.port - that.port) != 0)
1641                 return c;
1642         } else {
1643             // If one or both authorities are registry-based then we simply
1644             // compare them in the usual, case-sensitive way.  If one is
1645             // registry-based and one is server-based then the strings are
1646             // guaranteed to be unequal, hence the comparison will never return
1647             // zero and the compareTo and equals methods will remain
1648             // consistent.
1649             if ((c = compare(this.authority, that.authority)) != 0) return c;
1650         }
1651 
1652         if ((c = compare(this.path, that.path)) != 0) return c;
1653         if ((c = compare(this.query, that.query)) != 0) return c;
1654         return compare(this.fragment, that.fragment);
1655     }
1656 
1657     /**
1658      * Returns the content of this URI as a string.
1659      *
1660      * <p> If this URI was created by invoking one of the constructors in this
1661      * class then a string equivalent to the original input string, or to the
1662      * string computed from the originally-given components, as appropriate, is
1663      * returned.  Otherwise this URI was created by normalization, resolution,
1664      * or relativization, and so a string is constructed from this URI's
1665      * components according to the rules specified in <a
1666      * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
1667      * section&nbsp;5.2, step&nbsp;7. </p>
1668      *
1669      * @return  The string form of this URI
1670      */
1671     public String toString() {
1672         String s = string;
1673         if (s == null) {
1674             s = defineString();
1675         }
1676         return s;
1677     }
1678 
1679     private String defineString() {
1680         String s = string;
1681         if (s != null) {
1682             return s;
1683         }
1684 
1685         StringBuilder sb = new StringBuilder();
1686         if (scheme != null) {
1687             sb.append(scheme);
1688             sb.append(':');
1689         }
1690         if (isOpaque()) {
1691             sb.append(schemeSpecificPart);
1692         } else {
1693             if (host != null) {
1694                 sb.append("//");
1695                 if (userInfo != null) {
1696                     sb.append(userInfo);
1697                     sb.append('@');
1698                 }
1699                 boolean needBrackets = ((host.indexOf(':') >= 0)
1700                         && !host.startsWith("[")
1701                         && !host.endsWith("]"));
1702                 if (needBrackets) sb.append('[');
1703                 sb.append(host);
1704                 if (needBrackets) sb.append(']');
1705                 if (port != -1) {
1706                     sb.append(':');
1707                     sb.append(port);
1708                 }
1709             } else if (authority != null) {
1710                 sb.append("//");
1711                 sb.append(authority);
1712             }
1713             if (path != null)
1714                 sb.append(path);
1715             if (query != null) {
1716                 sb.append('?');
1717                 sb.append(query);
1718             }
1719         }
1720         if (fragment != null) {
1721             sb.append('#');
1722             sb.append(fragment);
1723         }
1724         return string = sb.toString();
1725     }
1726 
1727     /**
1728      * Returns the content of this URI as a US-ASCII string.
1729      *
1730      * <p> If this URI does not contain any characters in the <i>other</i>
1731      * category then an invocation of this method will return the same value as
1732      * an invocation of the {@link #toString() toString} method.  Otherwise
1733      * this method works as if by invoking that method and then <a
1734      * href="#encode">encoding</a> the result.  </p>
1735      *
1736      * @return  The string form of this URI, encoded as needed
1737      *          so that it only contains characters in the US-ASCII
1738      *          charset
1739      */
1740     public String toASCIIString() {
1741         return encode(toString());
1742     }
1743 
1744 
1745     // -- Serialization support --
1746 
1747     /**
1748      * Saves the content of this URI to the given serial stream.
1749      *
1750      * <p> The only serializable field of a URI instance is its {@code string}
1751      * field.  That field is given a value, if it does not have one already,
1752      * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()}
1753      * method of the given object-output stream is invoked. </p>
1754      *
1755      * @param  os  The object-output stream to which this object
1756      *             is to be written
1757      */
1758     private void writeObject(ObjectOutputStream os)
1759         throws IOException
1760     {
1761         defineString();
1762         os.defaultWriteObject();        // Writes the string field only
1763     }
1764 
1765     /**
1766      * Reconstitutes a URI from the given serial stream.
1767      *
1768      * <p> The {@link java.io.ObjectInputStream#defaultReadObject()} method is
1769      * invoked to read the value of the {@code string} field.  The result is
1770      * then parsed in the usual way.
1771      *
1772      * @param  is  The object-input stream from which this object
1773      *             is being read
1774      */
1775     private void readObject(ObjectInputStream is)
1776         throws ClassNotFoundException, IOException
1777     {
1778         port = -1;                      // Argh
1779         is.defaultReadObject();
1780         try {
1781             new Parser(string).parse(false);
1782         } catch (URISyntaxException x) {
1783             IOException y = new InvalidObjectException("Invalid URI");
1784             y.initCause(x);
1785             throw y;
1786         }
1787     }
1788 
1789 
1790     // -- End of public methods --
1791 
1792 
1793     // -- Utility methods for string-field comparison and hashing --
1794 
1795     // These methods return appropriate values for null string arguments,
1796     // thereby simplifying the equals, hashCode, and compareTo methods.
1797     //
1798     // The case-ignoring methods should only be applied to strings whose
1799     // characters are all known to be US-ASCII.  Because of this restriction,
1800     // these methods are faster than the similar methods in the String class.
1801 
1802     // US-ASCII only
1803     private static int toLower(char c) {
1804         if ((c >= 'A') && (c <= 'Z'))
1805             return c + ('a' - 'A');
1806         return c;
1807     }
1808 
1809     // US-ASCII only
1810     private static int toUpper(char c) {
1811         if ((c >= 'a') && (c <= 'z'))
1812             return c - ('a' - 'A');
1813         return c;
1814     }
1815 
1816     private static boolean equal(String s, String t) {
1817         if (s == t) return true;
1818         if ((s != null) && (t != null)) {
1819             if (s.length() != t.length())
1820                 return false;
1821             if (s.indexOf('%') < 0)
1822                 return s.equals(t);
1823             int n = s.length();
1824             for (int i = 0; i < n;) {
1825                 char c = s.charAt(i);
1826                 char d = t.charAt(i);
1827                 if (c != '%') {
1828                     if (c != d)
1829                         return false;
1830                     i++;
1831                     continue;
1832                 }
1833                 if (d != '%')
1834                     return false;
1835                 i++;
1836                 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
1837                     return false;
1838                 i++;
1839                 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
1840                     return false;
1841                 i++;
1842             }
1843             return true;
1844         }
1845         return false;
1846     }
1847 
1848     // US-ASCII only
1849     private static boolean equalIgnoringCase(String s, String t) {
1850         if (s == t) return true;
1851         if ((s != null) && (t != null)) {
1852             int n = s.length();
1853             if (t.length() != n)
1854                 return false;
1855             for (int i = 0; i < n; i++) {
1856                 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
1857                     return false;
1858             }
1859             return true;
1860         }
1861         return false;
1862     }
1863 
1864     private static int hash(int hash, String s) {
1865         if (s == null) return hash;
1866         return s.indexOf('%') < 0 ? hash * 127 + s.hashCode()
1867                                   : normalizedHash(hash, s);
1868     }
1869 
1870 
1871     private static int normalizedHash(int hash, String s) {
1872         int h = 0;
1873         for (int index = 0; index < s.length(); index++) {
1874             char ch = s.charAt(index);
1875             h = 31 * h + ch;
1876             if (ch == '%') {
1877                 /*
1878                  * Process the next two encoded characters
1879                  */
1880                 for (int i = index + 1; i < index + 3; i++)
1881                     h = 31 * h + toUpper(s.charAt(i));
1882                 index += 2;
1883             }
1884         }
1885         return hash * 127 + h;
1886     }
1887 
1888     // US-ASCII only
1889     private static int hashIgnoringCase(int hash, String s) {
1890         if (s == null) return hash;
1891         int h = hash;
1892         int n = s.length();
1893         for (int i = 0; i < n; i++)
1894             h = 31 * h + toLower(s.charAt(i));
1895         return h;
1896     }
1897 
1898     private static int compare(String s, String t) {
1899         if (s == t) return 0;
1900         if (s != null) {
1901             if (t != null)
1902                 return s.compareTo(t);
1903             else
1904                 return +1;
1905         } else {
1906             return -1;
1907         }
1908     }
1909 
1910     // US-ASCII only
1911     private static int compareIgnoringCase(String s, String t) {
1912         if (s == t) return 0;
1913         if (s != null) {
1914             if (t != null) {
1915                 int sn = s.length();
1916                 int tn = t.length();
1917                 int n = sn < tn ? sn : tn;
1918                 for (int i = 0; i < n; i++) {
1919                     int c = toLower(s.charAt(i)) - toLower(t.charAt(i));
1920                     if (c != 0)
1921                         return c;
1922                 }
1923                 return sn - tn;
1924             }
1925             return +1;
1926         } else {
1927             return -1;
1928         }
1929     }
1930 
1931 
1932     // -- String construction --
1933 
1934     // If a scheme is given then the path, if given, must be absolute
1935     //
1936     private static void checkPath(String s, String scheme, String path)
1937         throws URISyntaxException
1938     {
1939         if (scheme != null) {
1940             if ((path != null)
1941                 && ((path.length() > 0) && (path.charAt(0) != '/')))
1942                 throw new URISyntaxException(s,
1943                                              "Relative path in absolute URI");
1944         }
1945     }
1946 
1947     private void appendAuthority(StringBuilder sb,
1948                                  String authority,
1949                                  String userInfo,
1950                                  String host,
1951                                  int port)
1952     {
1953         if (host != null) {
1954             sb.append("//");
1955             if (userInfo != null) {
1956                 sb.append(quote(userInfo, L_USERINFO, H_USERINFO));
1957                 sb.append('@');
1958             }
1959             boolean needBrackets = ((host.indexOf(':') >= 0)
1960                                     && !host.startsWith("[")
1961                                     && !host.endsWith("]"));
1962             if (needBrackets) sb.append('[');
1963             sb.append(host);
1964             if (needBrackets) sb.append(']');
1965             if (port != -1) {
1966                 sb.append(':');
1967                 sb.append(port);
1968             }
1969         } else if (authority != null) {
1970             sb.append("//");
1971             if (authority.startsWith("[")) {
1972                 // authority should (but may not) contain an embedded IPv6 address
1973                 int end = authority.indexOf(']');
1974                 String doquote = authority, dontquote = "";
1975                 if (end != -1 && authority.indexOf(':') != -1) {
1976                     // the authority contains an IPv6 address
1977                     if (end == authority.length()) {
1978                         dontquote = authority;
1979                         doquote = "";
1980                     } else {
1981                         dontquote = authority.substring(0 , end + 1);
1982                         doquote = authority.substring(end + 1);
1983                     }
1984                 }
1985                 sb.append(dontquote);
1986                 sb.append(quote(doquote,
1987                             L_REG_NAME | L_SERVER,
1988                             H_REG_NAME | H_SERVER));
1989             } else {
1990                 sb.append(quote(authority,
1991                             L_REG_NAME | L_SERVER,
1992                             H_REG_NAME | H_SERVER));
1993             }
1994         }
1995     }
1996 
1997     private void appendSchemeSpecificPart(StringBuilder sb,
1998                                           String opaquePart,
1999                                           String authority,
2000                                           String userInfo,
2001                                           String host,
2002                                           int port,
2003                                           String path,
2004                                           String query)
2005     {
2006         if (opaquePart != null) {
2007             /* check if SSP begins with an IPv6 address
2008              * because we must not quote a literal IPv6 address
2009              */
2010             if (opaquePart.startsWith("//[")) {
2011                 int end =  opaquePart.indexOf(']');
2012                 if (end != -1 && opaquePart.indexOf(':')!=-1) {
2013                     String doquote, dontquote;
2014                     if (end == opaquePart.length()) {
2015                         dontquote = opaquePart;
2016                         doquote = "";
2017                     } else {
2018                         dontquote = opaquePart.substring(0,end+1);
2019                         doquote = opaquePart.substring(end+1);
2020                     }
2021                     sb.append (dontquote);
2022                     sb.append(quote(doquote, L_URIC, H_URIC));
2023                 }
2024             } else {
2025                 sb.append(quote(opaquePart, L_URIC, H_URIC));
2026             }
2027         } else {
2028             appendAuthority(sb, authority, userInfo, host, port);
2029             if (path != null)
2030                 sb.append(quote(path, L_PATH, H_PATH));
2031             if (query != null) {
2032                 sb.append('?');
2033                 sb.append(quote(query, L_URIC, H_URIC));
2034             }
2035         }
2036     }
2037 
2038     private void appendFragment(StringBuilder sb, String fragment) {
2039         if (fragment != null) {
2040             sb.append('#');
2041             sb.append(quote(fragment, L_URIC, H_URIC));
2042         }
2043     }
2044 
2045     private String toString(String scheme,
2046                             String opaquePart,
2047                             String authority,
2048                             String userInfo,
2049                             String host,
2050                             int port,
2051                             String path,
2052                             String query,
2053                             String fragment)
2054     {
2055         StringBuilder sb = new StringBuilder();
2056         if (scheme != null) {
2057             sb.append(scheme);
2058             sb.append(':');
2059         }
2060         appendSchemeSpecificPart(sb, opaquePart,
2061                                  authority, userInfo, host, port,
2062                                  path, query);
2063         appendFragment(sb, fragment);
2064         return sb.toString();
2065     }
2066 
2067     // -- Normalization, resolution, and relativization --
2068 
2069     // RFC2396 5.2 (6)
2070     private static String resolvePath(String base, String child,
2071                                       boolean absolute)
2072     {
2073         int i = base.lastIndexOf('/');
2074         int cn = child.length();
2075         String path = "";
2076 
2077         if (cn == 0) {
2078             // 5.2 (6a)
2079             if (i >= 0)
2080                 path = base.substring(0, i + 1);
2081         } else {
2082             StringBuilder sb = new StringBuilder(base.length() + cn);
2083             // 5.2 (6a)
2084             if (i >= 0)
2085                 sb.append(base, 0, i + 1);
2086             // 5.2 (6b)
2087             sb.append(child);
2088             path = sb.toString();
2089         }
2090 
2091         // 5.2 (6c-f)
2092         String np = normalize(path);
2093 
2094         // 5.2 (6g): If the result is absolute but the path begins with "../",
2095         // then we simply leave the path as-is
2096 
2097         return np;
2098     }
2099 
2100     // RFC2396 5.2
2101     private static URI resolve(URI base, URI child) {
2102         // check if child if opaque first so that NPE is thrown
2103         // if child is null.
2104         if (child.isOpaque() || base.isOpaque())
2105             return child;
2106 
2107         // 5.2 (2): Reference to current document (lone fragment)
2108         if ((child.scheme == null) && (child.authority == null)
2109             && child.path.isEmpty() && (child.fragment != null)
2110             && (child.query == null)) {
2111             if ((base.fragment != null)
2112                 && child.fragment.equals(base.fragment)) {
2113                 return base;
2114             }
2115             URI ru = new URI();
2116             ru.scheme = base.scheme;
2117             ru.authority = base.authority;
2118             ru.userInfo = base.userInfo;
2119             ru.host = base.host;
2120             ru.port = base.port;
2121             ru.path = base.path;
2122             ru.fragment = child.fragment;
2123             ru.query = base.query;
2124             return ru;
2125         }
2126 
2127         // 5.2 (3): Child is absolute
2128         if (child.scheme != null)
2129             return child;
2130 
2131         URI ru = new URI();             // Resolved URI
2132         ru.scheme = base.scheme;
2133         ru.query = child.query;
2134         ru.fragment = child.fragment;
2135 
2136         // 5.2 (4): Authority
2137         if (child.authority == null) {
2138             ru.authority = base.authority;
2139             ru.host = base.host;
2140             ru.userInfo = base.userInfo;
2141             ru.port = base.port;
2142 
2143             String cp = (child.path == null) ? "" : child.path;
2144             if ((cp.length() > 0) && (cp.charAt(0) == '/')) {
2145                 // 5.2 (5): Child path is absolute
2146                 ru.path = child.path;
2147             } else {
2148                 // 5.2 (6): Resolve relative path
2149                 ru.path = resolvePath(base.path, cp, base.isAbsolute());
2150             }
2151         } else {
2152             ru.authority = child.authority;
2153             ru.host = child.host;
2154             ru.userInfo = child.userInfo;
2155             ru.host = child.host;
2156             ru.port = child.port;
2157             ru.path = child.path;
2158         }
2159 
2160         // 5.2 (7): Recombine (nothing to do here)
2161         return ru;
2162     }
2163 
2164     // If the given URI's path is normal then return the URI;
2165     // o.w., return a new URI containing the normalized path.
2166     //
2167     private static URI normalize(URI u) {
2168         if (u.isOpaque() || (u.path == null) || (u.path.length() == 0))
2169             return u;
2170 
2171         String np = normalize(u.path);
2172         if (np == u.path)
2173             return u;
2174 
2175         URI v = new URI();
2176         v.scheme = u.scheme;
2177         v.fragment = u.fragment;
2178         v.authority = u.authority;
2179         v.userInfo = u.userInfo;
2180         v.host = u.host;
2181         v.port = u.port;
2182         v.path = np;
2183         v.query = u.query;
2184         return v;
2185     }
2186 
2187     // If both URIs are hierarchical, their scheme and authority components are
2188     // identical, and the base path is a prefix of the child's path, then
2189     // return a relative URI that, when resolved against the base, yields the
2190     // child; otherwise, return the child.
2191     //
2192     private static URI relativize(URI base, URI child) {
2193         // check if child if opaque first so that NPE is thrown
2194         // if child is null.
2195         if (child.isOpaque() || base.isOpaque())
2196             return child;
2197         if (!equalIgnoringCase(base.scheme, child.scheme)
2198             || !equal(base.authority, child.authority))
2199             return child;
2200 
2201         String bp = normalize(base.path);
2202         String cp = normalize(child.path);
2203         if (!bp.equals(cp)) {
2204             if (!bp.endsWith("/"))
2205                 bp = bp + "/";
2206             if (!cp.startsWith(bp))
2207                 return child;
2208         }
2209 
2210         URI v = new URI();
2211         v.path = cp.substring(bp.length());
2212         v.query = child.query;
2213         v.fragment = child.fragment;
2214         return v;
2215     }
2216 
2217 
2218 
2219     // -- Path normalization --
2220 
2221     // The following algorithm for path normalization avoids the creation of a
2222     // string object for each segment, as well as the use of a string buffer to
2223     // compute the final result, by using a single char array and editing it in
2224     // place.  The array is first split into segments, replacing each slash
2225     // with '\0' and creating a segment-index array, each element of which is
2226     // the index of the first char in the corresponding segment.  We then walk
2227     // through both arrays, removing ".", "..", and other segments as necessary
2228     // by setting their entries in the index array to -1.  Finally, the two
2229     // arrays are used to rejoin the segments and compute the final result.
2230     //
2231     // This code is based upon src/solaris/native/java/io/canonicalize_md.c
2232 
2233 
2234     // Check the given path to see if it might need normalization.  A path
2235     // might need normalization if it contains duplicate slashes, a "."
2236     // segment, or a ".." segment.  Return -1 if no further normalization is
2237     // possible, otherwise return the number of segments found.
2238     //
2239     // This method takes a string argument rather than a char array so that
2240     // this test can be performed without invoking path.toCharArray().
2241     //
2242     private static int needsNormalization(String path) {
2243         boolean normal = true;
2244         int ns = 0;                     // Number of segments
2245         int end = path.length() - 1;    // Index of last char in path
2246         int p = 0;                      // Index of next char in path
2247 
2248         // Skip initial slashes
2249         while (p <= end) {
2250             if (path.charAt(p) != '/') break;
2251             p++;
2252         }
2253         if (p > 1) normal = false;
2254 
2255         // Scan segments
2256         while (p <= end) {
2257 
2258             // Looking at "." or ".." ?
2259             if ((path.charAt(p) == '.')
2260                 && ((p == end)
2261                     || ((path.charAt(p + 1) == '/')
2262                         || ((path.charAt(p + 1) == '.')
2263                             && ((p + 1 == end)
2264                                 || (path.charAt(p + 2) == '/')))))) {
2265                 normal = false;
2266             }
2267             ns++;
2268 
2269             // Find beginning of next segment
2270             while (p <= end) {
2271                 if (path.charAt(p++) != '/')
2272                     continue;
2273 
2274                 // Skip redundant slashes
2275                 while (p <= end) {
2276                     if (path.charAt(p) != '/') break;
2277                     normal = false;
2278                     p++;
2279                 }
2280 
2281                 break;
2282             }
2283         }
2284 
2285         return normal ? -1 : ns;
2286     }
2287 
2288 
2289     // Split the given path into segments, replacing slashes with nulls and
2290     // filling in the given segment-index array.
2291     //
2292     // Preconditions:
2293     //   segs.length == Number of segments in path
2294     //
2295     // Postconditions:
2296     //   All slashes in path replaced by '\0'
2297     //   segs[i] == Index of first char in segment i (0 <= i < segs.length)
2298     //
2299     private static void split(char[] path, int[] segs) {
2300         int end = path.length - 1;      // Index of last char in path
2301         int p = 0;                      // Index of next char in path
2302         int i = 0;                      // Index of current segment
2303 
2304         // Skip initial slashes
2305         while (p <= end) {
2306             if (path[p] != '/') break;
2307             path[p] = '\0';
2308             p++;
2309         }
2310 
2311         while (p <= end) {
2312 
2313             // Note start of segment
2314             segs[i++] = p++;
2315 
2316             // Find beginning of next segment
2317             while (p <= end) {
2318                 if (path[p++] != '/')
2319                     continue;
2320                 path[p - 1] = '\0';
2321 
2322                 // Skip redundant slashes
2323                 while (p <= end) {
2324                     if (path[p] != '/') break;
2325                     path[p++] = '\0';
2326                 }
2327                 break;
2328             }
2329         }
2330 
2331         if (i != segs.length)
2332             throw new InternalError();  // ASSERT
2333     }
2334 
2335 
2336     // Join the segments in the given path according to the given segment-index
2337     // array, ignoring those segments whose index entries have been set to -1,
2338     // and inserting slashes as needed.  Return the length of the resulting
2339     // path.
2340     //
2341     // Preconditions:
2342     //   segs[i] == -1 implies segment i is to be ignored
2343     //   path computed by split, as above, with '\0' having replaced '/'
2344     //
2345     // Postconditions:
2346     //   path[0] .. path[return value] == Resulting path
2347     //
2348     private static int join(char[] path, int[] segs) {
2349         int ns = segs.length;           // Number of segments
2350         int end = path.length - 1;      // Index of last char in path
2351         int p = 0;                      // Index of next path char to write
2352 
2353         if (path[p] == '\0') {
2354             // Restore initial slash for absolute paths
2355             path[p++] = '/';
2356         }
2357 
2358         for (int i = 0; i < ns; i++) {
2359             int q = segs[i];            // Current segment
2360             if (q == -1)
2361                 // Ignore this segment
2362                 continue;
2363 
2364             if (p == q) {
2365                 // We're already at this segment, so just skip to its end
2366                 while ((p <= end) && (path[p] != '\0'))
2367                     p++;
2368                 if (p <= end) {
2369                     // Preserve trailing slash
2370                     path[p++] = '/';
2371                 }
2372             } else if (p < q) {
2373                 // Copy q down to p
2374                 while ((q <= end) && (path[q] != '\0'))
2375                     path[p++] = path[q++];
2376                 if (q <= end) {
2377                     // Preserve trailing slash
2378                     path[p++] = '/';
2379                 }
2380             } else
2381                 throw new InternalError(); // ASSERT false
2382         }
2383 
2384         return p;
2385     }
2386 
2387 
2388     // Remove "." segments from the given path, and remove segment pairs
2389     // consisting of a non-".." segment followed by a ".." segment.
2390     //
2391     private static void removeDots(char[] path, int[] segs) {
2392         int ns = segs.length;
2393         int end = path.length - 1;
2394 
2395         for (int i = 0; i < ns; i++) {
2396             int dots = 0;               // Number of dots found (0, 1, or 2)
2397 
2398             // Find next occurrence of "." or ".."
2399             do {
2400                 int p = segs[i];
2401                 if (path[p] == '.') {
2402                     if (p == end) {
2403                         dots = 1;
2404                         break;
2405                     } else if (path[p + 1] == '\0') {
2406                         dots = 1;
2407                         break;
2408                     } else if ((path[p + 1] == '.')
2409                                && ((p + 1 == end)
2410                                    || (path[p + 2] == '\0'))) {
2411                         dots = 2;
2412                         break;
2413                     }
2414                 }
2415                 i++;
2416             } while (i < ns);
2417             if ((i > ns) || (dots == 0))
2418                 break;
2419 
2420             if (dots == 1) {
2421                 // Remove this occurrence of "."
2422                 segs[i] = -1;
2423             } else {
2424                 // If there is a preceding non-".." segment, remove both that
2425                 // segment and this occurrence of ".."; otherwise, leave this
2426                 // ".." segment as-is.
2427                 int j;
2428                 for (j = i - 1; j >= 0; j--) {
2429                     if (segs[j] != -1) break;
2430                 }
2431                 if (j >= 0) {
2432                     int q = segs[j];
2433                     if (!((path[q] == '.')
2434                           && (path[q + 1] == '.')
2435                           && (path[q + 2] == '\0'))) {
2436                         segs[i] = -1;
2437                         segs[j] = -1;
2438                     }
2439                 }
2440             }
2441         }
2442     }
2443 
2444 
2445     // DEVIATION: If the normalized path is relative, and if the first
2446     // segment could be parsed as a scheme name, then prepend a "." segment
2447     //
2448     private static void maybeAddLeadingDot(char[] path, int[] segs) {
2449 
2450         if (path[0] == '\0')
2451             // The path is absolute
2452             return;
2453 
2454         int ns = segs.length;
2455         int f = 0;                      // Index of first segment
2456         while (f < ns) {
2457             if (segs[f] >= 0)
2458                 break;
2459             f++;
2460         }
2461         if ((f >= ns) || (f == 0))
2462             // The path is empty, or else the original first segment survived,
2463             // in which case we already know that no leading "." is needed
2464             return;
2465 
2466         int p = segs[f];
2467         while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++;
2468         if (p >= path.length || path[p] == '\0')
2469             // No colon in first segment, so no "." needed
2470             return;
2471 
2472         // At this point we know that the first segment is unused,
2473         // hence we can insert a "." segment at that position
2474         path[0] = '.';
2475         path[1] = '\0';
2476         segs[0] = 0;
2477     }
2478 
2479 
2480     // Normalize the given path string.  A normal path string has no empty
2481     // segments (i.e., occurrences of "//"), no segments equal to ".", and no
2482     // segments equal to ".." that are preceded by a segment not equal to "..".
2483     // In contrast to Unix-style pathname normalization, for URI paths we
2484     // always retain trailing slashes.
2485     //
2486     private static String normalize(String ps) {
2487 
2488         // Does this path need normalization?
2489         int ns = needsNormalization(ps);        // Number of segments
2490         if (ns < 0)
2491             // Nope -- just return it
2492             return ps;
2493 
2494         char[] path = ps.toCharArray();         // Path in char-array form
2495 
2496         // Split path into segments
2497         int[] segs = new int[ns];               // Segment-index array
2498         split(path, segs);
2499 
2500         // Remove dots
2501         removeDots(path, segs);
2502 
2503         // Prevent scheme-name confusion
2504         maybeAddLeadingDot(path, segs);
2505 
2506         // Join the remaining segments and return the result
2507         String s = new String(path, 0, join(path, segs));
2508         if (s.equals(ps)) {
2509             // string was already normalized
2510             return ps;
2511         }
2512         return s;
2513     }
2514 
2515 
2516 
2517     // -- Character classes for parsing --
2518 
2519     // RFC2396 precisely specifies which characters in the US-ASCII charset are
2520     // permissible in the various components of a URI reference.  We here
2521     // define a set of mask pairs to aid in enforcing these restrictions.  Each
2522     // mask pair consists of two longs, a low mask and a high mask.  Taken
2523     // together they represent a 128-bit mask, where bit i is set iff the
2524     // character with value i is permitted.
2525     //
2526     // This approach is more efficient than sequentially searching arrays of
2527     // permitted characters.  It could be made still more efficient by
2528     // precompiling the mask information so that a character's presence in a
2529     // given mask could be determined by a single table lookup.
2530 
2531     // Compute the low-order mask for the characters in the given string
2532     private static long lowMask(String chars) {
2533         int n = chars.length();
2534         long m = 0;
2535         for (int i = 0; i < n; i++) {
2536             char c = chars.charAt(i);
2537             if (c < 64)
2538                 m |= (1L << c);
2539         }
2540         return m;
2541     }
2542 
2543     // Compute the high-order mask for the characters in the given string
2544     private static long highMask(String chars) {
2545         int n = chars.length();
2546         long m = 0;
2547         for (int i = 0; i < n; i++) {
2548             char c = chars.charAt(i);
2549             if ((c >= 64) && (c < 128))
2550                 m |= (1L << (c - 64));
2551         }
2552         return m;
2553     }
2554 
2555     // Compute a low-order mask for the characters
2556     // between first and last, inclusive
2557     private static long lowMask(char first, char last) {
2558         long m = 0;
2559         int f = Math.max(Math.min(first, 63), 0);
2560         int l = Math.max(Math.min(last, 63), 0);
2561         for (int i = f; i <= l; i++)
2562             m |= 1L << i;
2563         return m;
2564     }
2565 
2566     // Compute a high-order mask for the characters
2567     // between first and last, inclusive
2568     private static long highMask(char first, char last) {
2569         long m = 0;
2570         int f = Math.max(Math.min(first, 127), 64) - 64;
2571         int l = Math.max(Math.min(last, 127), 64) - 64;
2572         for (int i = f; i <= l; i++)
2573             m |= 1L << i;
2574         return m;
2575     }
2576 
2577     // Tell whether the given character is permitted by the given mask pair
2578     private static boolean match(char c, long lowMask, long highMask) {
2579         if (c == 0) // 0 doesn't have a slot in the mask. So, it never matches.
2580             return false;
2581         if (c < 64)
2582             return ((1L << c) & lowMask) != 0;
2583         if (c < 128)
2584             return ((1L << (c - 64)) & highMask) != 0;
2585         return false;
2586     }
2587 
2588     // Character-class masks, in reverse order from RFC2396 because
2589     // initializers for static fields cannot make forward references.
2590 
2591     // digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
2592     //            "8" | "9"
2593     private static final long L_DIGIT = lowMask('0', '9');
2594     private static final long H_DIGIT = 0L;
2595 
2596     // upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
2597     //            "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
2598     //            "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
2599     private static final long L_UPALPHA = 0L;
2600     private static final long H_UPALPHA = highMask('A', 'Z');
2601 
2602     // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
2603     //            "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
2604     //            "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
2605     private static final long L_LOWALPHA = 0L;
2606     private static final long H_LOWALPHA = highMask('a', 'z');
2607 
2608     // alpha         = lowalpha | upalpha
2609     private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
2610     private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
2611 
2612     // alphanum      = alpha | digit
2613     private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
2614     private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
2615 
2616     // hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
2617     //                         "a" | "b" | "c" | "d" | "e" | "f"
2618     private static final long L_HEX = L_DIGIT;
2619     private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f');
2620 
2621     // mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
2622     //                 "(" | ")"
2623     private static final long L_MARK = lowMask("-_.!~*'()");
2624     private static final long H_MARK = highMask("-_.!~*'()");
2625 
2626     // unreserved    = alphanum | mark
2627     private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
2628     private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
2629 
2630     // reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
2631     //                 "$" | "," | "[" | "]"
2632     // Added per RFC2732: "[", "]"
2633     private static final long L_RESERVED = lowMask(";/?:@&=+$,[]");
2634     private static final long H_RESERVED = highMask(";/?:@&=+$,[]");
2635 
2636     // The zero'th bit is used to indicate that escape pairs and non-US-ASCII
2637     // characters are allowed; this is handled by the scanEscape method below.
2638     private static final long L_ESCAPED = 1L;
2639     private static final long H_ESCAPED = 0L;
2640 
2641     // uric          = reserved | unreserved | escaped
2642     private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED;
2643     private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED;
2644 
2645     // pchar         = unreserved | escaped |
2646     //                 ":" | "@" | "&" | "=" | "+" | "$" | ","
2647     private static final long L_PCHAR
2648         = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,");
2649     private static final long H_PCHAR
2650         = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,");
2651 
2652     // All valid path characters
2653     private static final long L_PATH = L_PCHAR | lowMask(";/");
2654     private static final long H_PATH = H_PCHAR | highMask(";/");
2655 
2656     // Dash, for use in domainlabel and toplabel
2657     private static final long L_DASH = lowMask("-");
2658     private static final long H_DASH = highMask("-");
2659 
2660     // Dot, for use in hostnames
2661     private static final long L_DOT = lowMask(".");
2662     private static final long H_DOT = highMask(".");
2663 
2664     // userinfo      = *( unreserved | escaped |
2665     //                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
2666     private static final long L_USERINFO
2667         = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,");
2668     private static final long H_USERINFO
2669         = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,");
2670 
2671     // reg_name      = 1*( unreserved | escaped | "$" | "," |
2672     //                     ";" | ":" | "@" | "&" | "=" | "+" )
2673     private static final long L_REG_NAME
2674         = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+");
2675     private static final long H_REG_NAME
2676         = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+");
2677 
2678     // All valid characters for server-based authorities
2679     private static final long L_SERVER
2680         = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]");
2681     private static final long H_SERVER
2682         = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]");
2683 
2684     // Special case of server authority that represents an IPv6 address
2685     // In this case, a % does not signify an escape sequence
2686     private static final long L_SERVER_PERCENT
2687         = L_SERVER | lowMask("%");
2688     private static final long H_SERVER_PERCENT
2689         = H_SERVER | highMask("%");
2690     private static final long L_LEFT_BRACKET = lowMask("[");
2691     private static final long H_LEFT_BRACKET = highMask("[");
2692 
2693     // scheme        = alpha *( alpha | digit | "+" | "-" | "." )
2694     private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-.");
2695     private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-.");
2696 
2697     // scope_id = alpha | digit | "_" | "."
2698     private static final long L_SCOPE_ID
2699         = L_ALPHANUM | lowMask("_.");
2700     private static final long H_SCOPE_ID
2701         = H_ALPHANUM | highMask("_.");
2702 
2703     // -- Escaping and encoding --
2704 
2705     private static final char[] hexDigits = {
2706         '0', '1', '2', '3', '4', '5', '6', '7',
2707         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
2708     };
2709 
2710     private static void appendEscape(StringBuilder sb, byte b) {
2711         sb.append('%');
2712         sb.append(hexDigits[(b >> 4) & 0x0f]);
2713         sb.append(hexDigits[(b >> 0) & 0x0f]);
2714     }
2715 
2716     private static void appendEncoded(StringBuilder sb, char c) {
2717         ByteBuffer bb = null;
2718         try {
2719             bb = ThreadLocalCoders.encoderFor("UTF-8")
2720                 .encode(CharBuffer.wrap("" + c));
2721         } catch (CharacterCodingException x) {
2722             assert false;
2723         }
2724         while (bb.hasRemaining()) {
2725             int b = bb.get() & 0xff;
2726             if (b >= 0x80)
2727                 appendEscape(sb, (byte)b);
2728             else
2729                 sb.append((char)b);
2730         }
2731     }
2732 
2733     // Quote any characters in s that are not permitted
2734     // by the given mask pair
2735     //
2736     private static String quote(String s, long lowMask, long highMask) {
2737         StringBuilder sb = null;
2738         boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
2739         for (int i = 0; i < s.length(); i++) {
2740             char c = s.charAt(i);
2741             if (c < '\u0080') {
2742                 if (!match(c, lowMask, highMask)) {
2743                     if (sb == null) {
2744                         sb = new StringBuilder();
2745                         sb.append(s, 0, i);
2746                     }
2747                     appendEscape(sb, (byte)c);
2748                 } else {
2749                     if (sb != null)
2750                         sb.append(c);
2751                 }
2752             } else if (allowNonASCII
2753                        && (Character.isSpaceChar(c)
2754                            || Character.isISOControl(c))) {
2755                 if (sb == null) {
2756                     sb = new StringBuilder();
2757                     sb.append(s, 0, i);
2758                 }
2759                 appendEncoded(sb, c);
2760             } else {
2761                 if (sb != null)
2762                     sb.append(c);
2763             }
2764         }
2765         return (sb == null) ? s : sb.toString();
2766     }
2767 
2768     // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets,
2769     // assuming that s is otherwise legal
2770     //
2771     private static String encode(String s) {
2772         int n = s.length();
2773         if (n == 0)
2774             return s;
2775 
2776         // First check whether we actually need to encode
2777         for (int i = 0;;) {
2778             if (s.charAt(i) >= '\u0080')
2779                 break;
2780             if (++i >= n)
2781                 return s;
2782         }
2783 
2784         String ns = Normalizer.normalize(s, Normalizer.Form.NFC);
2785         ByteBuffer bb = null;
2786         try {
2787             bb = ThreadLocalCoders.encoderFor("UTF-8")
2788                 .encode(CharBuffer.wrap(ns));
2789         } catch (CharacterCodingException x) {
2790             assert false;
2791         }
2792 
2793         StringBuilder sb = new StringBuilder();
2794         while (bb.hasRemaining()) {
2795             int b = bb.get() & 0xff;
2796             if (b >= 0x80)
2797                 appendEscape(sb, (byte)b);
2798             else
2799                 sb.append((char)b);
2800         }
2801         return sb.toString();
2802     }
2803 
2804     private static int decode(char c) {
2805         if ((c >= '0') && (c <= '9'))
2806             return c - '0';
2807         if ((c >= 'a') && (c <= 'f'))
2808             return c - 'a' + 10;
2809         if ((c >= 'A') && (c <= 'F'))
2810             return c - 'A' + 10;
2811         assert false;
2812         return -1;
2813     }
2814 
2815     private static byte decode(char c1, char c2) {
2816         return (byte)(  ((decode(c1) & 0xf) << 4)
2817                       | ((decode(c2) & 0xf) << 0));
2818     }
2819 
2820     // Evaluates all escapes in s, applying UTF-8 decoding if needed.  Assumes
2821     // that escapes are well-formed syntactically, i.e., of the form %XX.  If a
2822     // sequence of escaped octets is not valid UTF-8 then the erroneous octets
2823     // are replaced with '\uFFFD'.
2824     // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal
2825     //            with a scope_id
2826     //
2827     private static String decode(String s) {
2828         return decode(s, true);
2829     }
2830 
2831     // This method was introduced as a generalization of URI.decode method
2832     // to provide a fix for JDK-8037396
2833     private static String decode(String s, boolean ignorePercentInBrackets) {
2834         if (s == null)
2835             return s;
2836         int n = s.length();
2837         if (n == 0)
2838             return s;
2839         if (s.indexOf('%') < 0)
2840             return s;
2841 
2842         StringBuilder sb = new StringBuilder(n);
2843         ByteBuffer bb = ByteBuffer.allocate(n);
2844         CharBuffer cb = CharBuffer.allocate(n);
2845         CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8")
2846                 .onMalformedInput(CodingErrorAction.REPLACE)
2847                 .onUnmappableCharacter(CodingErrorAction.REPLACE);
2848 
2849         // This is not horribly efficient, but it will do for now
2850         char c = s.charAt(0);
2851         boolean betweenBrackets = false;
2852 
2853         for (int i = 0; i < n;) {
2854             assert c == s.charAt(i);    // Loop invariant
2855             if (c == '[') {
2856                 betweenBrackets = true;
2857             } else if (betweenBrackets && c == ']') {
2858                 betweenBrackets = false;
2859             }
2860             if (c != '%' || (betweenBrackets && ignorePercentInBrackets)) {
2861                 sb.append(c);
2862                 if (++i >= n)
2863                     break;
2864                 c = s.charAt(i);
2865                 continue;
2866             }
2867             bb.clear();
2868             int ui = i;
2869             for (;;) {
2870                 assert (n - i >= 2);
2871                 bb.put(decode(s.charAt(++i), s.charAt(++i)));
2872                 if (++i >= n)
2873                     break;
2874                 c = s.charAt(i);
2875                 if (c != '%')
2876                     break;
2877             }
2878             bb.flip();
2879             cb.clear();
2880             dec.reset();
2881             CoderResult cr = dec.decode(bb, cb, true);
2882             assert cr.isUnderflow();
2883             cr = dec.flush(cb);
2884             assert cr.isUnderflow();
2885             sb.append(cb.flip().toString());
2886         }
2887 
2888         return sb.toString();
2889     }
2890 
2891 
2892     // -- Parsing --
2893 
2894     // For convenience we wrap the input URI string in a new instance of the
2895     // following internal class.  This saves always having to pass the input
2896     // string as an argument to each internal scan/parse method.
2897 
2898     private class Parser {
2899 
2900         private String input;           // URI input string
2901         private boolean requireServerAuthority = false;
2902 
2903         Parser(String s) {
2904             input = s;
2905             string = s;
2906         }
2907 
2908         // -- Methods for throwing URISyntaxException in various ways --
2909 
2910         private void fail(String reason) throws URISyntaxException {
2911             throw new URISyntaxException(input, reason);
2912         }
2913 
2914         private void fail(String reason, int p) throws URISyntaxException {
2915             throw new URISyntaxException(input, reason, p);
2916         }
2917 
2918         private void failExpecting(String expected, int p)
2919             throws URISyntaxException
2920         {
2921             fail("Expected " + expected, p);
2922         }
2923 
2924 
2925         // -- Simple access to the input string --
2926 
2927         // Tells whether start < end and, if so, whether charAt(start) == c
2928         //
2929         private boolean at(int start, int end, char c) {
2930             return (start < end) && (input.charAt(start) == c);
2931         }
2932 
2933         // Tells whether start + s.length() < end and, if so,
2934         // whether the chars at the start position match s exactly
2935         //
2936         private boolean at(int start, int end, String s) {
2937             int p = start;
2938             int sn = s.length();
2939             if (sn > end - p)
2940                 return false;
2941             int i = 0;
2942             while (i < sn) {
2943                 if (input.charAt(p++) != s.charAt(i)) {
2944                     break;
2945                 }
2946                 i++;
2947             }
2948             return (i == sn);
2949         }
2950 
2951 
2952         // -- Scanning --
2953 
2954         // The various scan and parse methods that follow use a uniform
2955         // convention of taking the current start position and end index as
2956         // their first two arguments.  The start is inclusive while the end is
2957         // exclusive, just as in the String class, i.e., a start/end pair
2958         // denotes the left-open interval [start, end) of the input string.
2959         //
2960         // These methods never proceed past the end position.  They may return
2961         // -1 to indicate outright failure, but more often they simply return
2962         // the position of the first char after the last char scanned.  Thus
2963         // a typical idiom is
2964         //
2965         //     int p = start;
2966         //     int q = scan(p, end, ...);
2967         //     if (q > p)
2968         //         // We scanned something
2969         //         ...;
2970         //     else if (q == p)
2971         //         // We scanned nothing
2972         //         ...;
2973         //     else if (q == -1)
2974         //         // Something went wrong
2975         //         ...;
2976 
2977 
2978         // Scan a specific char: If the char at the given start position is
2979         // equal to c, return the index of the next char; otherwise, return the
2980         // start position.
2981         //
2982         private int scan(int start, int end, char c) {
2983             if ((start < end) && (input.charAt(start) == c))
2984                 return start + 1;
2985             return start;
2986         }
2987 
2988         // Scan forward from the given start position.  Stop at the first char
2989         // in the err string (in which case -1 is returned), or the first char
2990         // in the stop string (in which case the index of the preceding char is
2991         // returned), or the end of the input string (in which case the length
2992         // of the input string is returned).  May return the start position if
2993         // nothing matches.
2994         //
2995         private int scan(int start, int end, String err, String stop) {
2996             int p = start;
2997             while (p < end) {
2998                 char c = input.charAt(p);
2999                 if (err.indexOf(c) >= 0)
3000                     return -1;
3001                 if (stop.indexOf(c) >= 0)
3002                     break;
3003                 p++;
3004             }
3005             return p;
3006         }
3007 
3008         // Scan forward from the given start position.  Stop at the first char
3009         // in the stop string (in which case the index of the preceding char is
3010         // returned), or the end of the input string (in which case the length
3011         // of the input string is returned).  May return the start position if
3012         // nothing matches.
3013         //
3014         private int scan(int start, int end, String stop) {
3015             int p = start;
3016             while (p < end) {
3017                 char c = input.charAt(p);
3018                 if (stop.indexOf(c) >= 0)
3019                     break;
3020                 p++;
3021             }
3022             return p;
3023         }
3024 
3025         // Scan a potential escape sequence, starting at the given position,
3026         // with the given first char (i.e., charAt(start) == c).
3027         //
3028         // This method assumes that if escapes are allowed then visible
3029         // non-US-ASCII chars are also allowed.
3030         //
3031         private int scanEscape(int start, int n, char first)
3032             throws URISyntaxException
3033         {
3034             int p = start;
3035             char c = first;
3036             if (c == '%') {
3037                 // Process escape pair
3038                 if ((p + 3 <= n)
3039                     && match(input.charAt(p + 1), L_HEX, H_HEX)
3040                     && match(input.charAt(p + 2), L_HEX, H_HEX)) {
3041                     return p + 3;
3042                 }
3043                 fail("Malformed escape pair", p);
3044             } else if ((c > 128)
3045                        && !Character.isSpaceChar(c)
3046                        && !Character.isISOControl(c)) {
3047                 // Allow unescaped but visible non-US-ASCII chars
3048                 return p + 1;
3049             }
3050             return p;
3051         }
3052 
3053         // Scan chars that match the given mask pair
3054         //
3055         private int scan(int start, int n, long lowMask, long highMask)
3056             throws URISyntaxException
3057         {
3058             int p = start;
3059             while (p < n) {
3060                 char c = input.charAt(p);
3061                 if (match(c, lowMask, highMask)) {
3062                     p++;
3063                     continue;
3064                 }
3065                 if ((lowMask & L_ESCAPED) != 0) {
3066                     int q = scanEscape(p, n, c);
3067                     if (q > p) {
3068                         p = q;
3069                         continue;
3070                     }
3071                 }
3072                 break;
3073             }
3074             return p;
3075         }
3076 
3077         // Check that each of the chars in [start, end) matches the given mask
3078         //
3079         private void checkChars(int start, int end,
3080                                 long lowMask, long highMask,
3081                                 String what)
3082             throws URISyntaxException
3083         {
3084             int p = scan(start, end, lowMask, highMask);
3085             if (p < end)
3086                 fail("Illegal character in " + what, p);
3087         }
3088 
3089         // Check that the char at position p matches the given mask
3090         //
3091         private void checkChar(int p,
3092                                long lowMask, long highMask,
3093                                String what)
3094             throws URISyntaxException
3095         {
3096             checkChars(p, p + 1, lowMask, highMask, what);
3097         }
3098 
3099 
3100         // -- Parsing --
3101 
3102         // [<scheme>:]<scheme-specific-part>[#<fragment>]
3103         //
3104         void parse(boolean rsa) throws URISyntaxException {
3105             requireServerAuthority = rsa;
3106             int n = input.length();
3107             int p = scan(0, n, "/?#", ":");
3108             if ((p >= 0) && at(p, n, ':')) {
3109                 if (p == 0)
3110                     failExpecting("scheme name", 0);
3111                 checkChar(0, L_ALPHA, H_ALPHA, "scheme name");
3112                 checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name");
3113                 scheme = input.substring(0, p);
3114                 p++;                    // Skip ':'
3115                 if (at(p, n, '/')) {
3116                     p = parseHierarchical(p, n);
3117                 } else {
3118                     // opaque; need to create the schemeSpecificPart
3119                     int q = scan(p, n, "#");
3120                     if (q <= p)
3121                         failExpecting("scheme-specific part", p);
3122                     checkChars(p, q, L_URIC, H_URIC, "opaque part");
3123                     schemeSpecificPart = input.substring(p, q);
3124                     p = q;
3125                 }
3126             } else {
3127                 p = parseHierarchical(0, n);
3128             }
3129             if (at(p, n, '#')) {
3130                 checkChars(p + 1, n, L_URIC, H_URIC, "fragment");
3131                 fragment = input.substring(p + 1, n);
3132                 p = n;
3133             }
3134             if (p < n)
3135                 fail("end of URI", p);
3136         }
3137 
3138         // [//authority]<path>[?<query>]
3139         //
3140         // DEVIATION from RFC2396: We allow an empty authority component as
3141         // long as it's followed by a non-empty path, query component, or
3142         // fragment component.  This is so that URIs such as "file:///foo/bar"
3143         // will parse.  This seems to be the intent of RFC2396, though the
3144         // grammar does not permit it.  If the authority is empty then the
3145         // userInfo, host, and port components are undefined.
3146         //
3147         // DEVIATION from RFC2396: We allow empty relative paths.  This seems
3148         // to be the intent of RFC2396, but the grammar does not permit it.
3149         // The primary consequence of this deviation is that "#f" parses as a
3150         // relative URI with an empty path.
3151         //
3152         private int parseHierarchical(int start, int n)
3153             throws URISyntaxException
3154         {
3155             int p = start;
3156             if (at(p, n, '/') && at(p + 1, n, '/')) {
3157                 p += 2;
3158                 int q = scan(p, n, "/?#");
3159                 if (q > p) {
3160                     p = parseAuthority(p, q);
3161                 } else if (q < n) {
3162                     // DEVIATION: Allow empty authority prior to non-empty
3163                     // path, query component or fragment identifier
3164                 } else
3165                     failExpecting("authority", p);
3166             }
3167             int q = scan(p, n, "?#"); // DEVIATION: May be empty
3168             checkChars(p, q, L_PATH, H_PATH, "path");
3169             path = input.substring(p, q);
3170             p = q;
3171             if (at(p, n, '?')) {
3172                 p++;
3173                 q = scan(p, n, "#");
3174                 checkChars(p, q, L_URIC, H_URIC, "query");
3175                 query = input.substring(p, q);
3176                 p = q;
3177             }
3178             return p;
3179         }
3180 
3181         // authority     = server | reg_name
3182         //
3183         // Ambiguity: An authority that is a registry name rather than a server
3184         // might have a prefix that parses as a server.  We use the fact that
3185         // the authority component is always followed by '/' or the end of the
3186         // input string to resolve this: If the complete authority did not
3187         // parse as a server then we try to parse it as a registry name.
3188         //
3189         private int parseAuthority(int start, int n)
3190             throws URISyntaxException
3191         {
3192             int p = start;
3193             int q = p;
3194             URISyntaxException ex = null;
3195 
3196             boolean serverChars;
3197             boolean regChars;
3198 
3199             if (scan(p, n, "]") > p) {
3200                 // contains a literal IPv6 address, therefore % is allowed
3201                 serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n);
3202             } else {
3203                 serverChars = (scan(p, n, L_SERVER, H_SERVER) == n);
3204             }
3205             regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n);
3206 
3207             if (regChars && !serverChars) {
3208                 // Must be a registry-based authority
3209                 authority = input.substring(p, n);
3210                 return n;
3211             }
3212 
3213             if (serverChars) {
3214                 // Might be (probably is) a server-based authority, so attempt
3215                 // to parse it as such.  If the attempt fails, try to treat it
3216                 // as a registry-based authority.
3217                 try {
3218                     q = parseServer(p, n);
3219                     if (q < n)
3220                         failExpecting("end of authority", q);
3221                     authority = input.substring(p, n);
3222                 } catch (URISyntaxException x) {
3223                     // Undo results of failed parse
3224                     userInfo = null;
3225                     host = null;
3226                     port = -1;
3227                     if (requireServerAuthority) {
3228                         // If we're insisting upon a server-based authority,
3229                         // then just re-throw the exception
3230                         throw x;
3231                     } else {
3232                         // Save the exception in case it doesn't parse as a
3233                         // registry either
3234                         ex = x;
3235                         q = p;
3236                     }
3237                 }
3238             }
3239 
3240             if (q < n) {
3241                 if (regChars) {
3242                     // Registry-based authority
3243                     authority = input.substring(p, n);
3244                 } else if (ex != null) {
3245                     // Re-throw exception; it was probably due to
3246                     // a malformed IPv6 address
3247                     throw ex;
3248                 } else {
3249                     fail("Illegal character in authority", q);
3250                 }
3251             }
3252 
3253             return n;
3254         }
3255 
3256 
3257         // [<userinfo>@]<host>[:<port>]
3258         //
3259         private int parseServer(int start, int n)
3260             throws URISyntaxException
3261         {
3262             int p = start;
3263             int q;
3264 
3265             // userinfo
3266             q = scan(p, n, "/?#", "@");
3267             if ((q >= p) && at(q, n, '@')) {
3268                 checkChars(p, q, L_USERINFO, H_USERINFO, "user info");
3269                 userInfo = input.substring(p, q);
3270                 p = q + 1;              // Skip '@'
3271             }
3272 
3273             // hostname, IPv4 address, or IPv6 address
3274             if (at(p, n, '[')) {
3275                 // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732
3276                 p++;
3277                 q = scan(p, n, "/?#", "]");
3278                 if ((q > p) && at(q, n, ']')) {
3279                     // look for a "%" scope id
3280                     int r = scan (p, q, "%");
3281                     if (r > p) {
3282                         parseIPv6Reference(p, r);
3283                         if (r+1 == q) {
3284                             fail ("scope id expected");
3285                         }
3286                         checkChars (r+1, q, L_SCOPE_ID, H_SCOPE_ID,
3287                                                 "scope id");
3288                     } else {
3289                         parseIPv6Reference(p, q);
3290                     }
3291                     host = input.substring(p-1, q+1);
3292                     p = q + 1;
3293                 } else {
3294                     failExpecting("closing bracket for IPv6 address", q);
3295                 }
3296             } else {
3297                 q = parseIPv4Address(p, n);
3298                 if (q <= p)
3299                     q = parseHostname(p, n);
3300                 p = q;
3301             }
3302 
3303             // port
3304             if (at(p, n, ':')) {
3305                 p++;
3306                 q = scan(p, n, "/");
3307                 if (q > p) {
3308                     checkChars(p, q, L_DIGIT, H_DIGIT, "port number");
3309                     try {
3310                         port = Integer.parseInt(input, p, q, 10);
3311                     } catch (NumberFormatException x) {
3312                         fail("Malformed port number", p);
3313                     }
3314                     p = q;
3315                 }
3316             }
3317             if (p < n)
3318                 failExpecting("port number", p);
3319 
3320             return p;
3321         }
3322 
3323         // Scan a string of decimal digits whose value fits in a byte
3324         //
3325         private int scanByte(int start, int n)
3326             throws URISyntaxException
3327         {
3328             int p = start;
3329             int q = scan(p, n, L_DIGIT, H_DIGIT);
3330             if (q <= p) return q;
3331             if (Integer.parseInt(input, p, q, 10) > 255) return p;
3332             return q;
3333         }
3334 
3335         // Scan an IPv4 address.
3336         //
3337         // If the strict argument is true then we require that the given
3338         // interval contain nothing besides an IPv4 address; if it is false
3339         // then we only require that it start with an IPv4 address.
3340         //
3341         // If the interval does not contain or start with (depending upon the
3342         // strict argument) a legal IPv4 address characters then we return -1
3343         // immediately; otherwise we insist that these characters parse as a
3344         // legal IPv4 address and throw an exception on failure.
3345         //
3346         // We assume that any string of decimal digits and dots must be an IPv4
3347         // address.  It won't parse as a hostname anyway, so making that
3348         // assumption here allows more meaningful exceptions to be thrown.
3349         //
3350         private int scanIPv4Address(int start, int n, boolean strict)
3351             throws URISyntaxException
3352         {
3353             int p = start;
3354             int q;
3355             int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT);
3356             if ((m <= p) || (strict && (m != n)))
3357                 return -1;
3358             for (;;) {
3359                 // Per RFC2732: At most three digits per byte
3360                 // Further constraint: Each element fits in a byte
3361                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3362                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3363                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3364                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3365                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3366                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3367                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3368                 if (q < m) break;
3369                 return q;
3370             }
3371             fail("Malformed IPv4 address", q);
3372             return -1;
3373         }
3374 
3375         // Take an IPv4 address: Throw an exception if the given interval
3376         // contains anything except an IPv4 address
3377         //
3378         private int takeIPv4Address(int start, int n, String expected)
3379             throws URISyntaxException
3380         {
3381             int p = scanIPv4Address(start, n, true);
3382             if (p <= start)
3383                 failExpecting(expected, start);
3384             return p;
3385         }
3386 
3387         // Attempt to parse an IPv4 address, returning -1 on failure but
3388         // allowing the given interval to contain [:<characters>] after
3389         // the IPv4 address.
3390         //
3391         private int parseIPv4Address(int start, int n) {
3392             int p;
3393 
3394             try {
3395                 p = scanIPv4Address(start, n, false);
3396             } catch (URISyntaxException x) {
3397                 return -1;
3398             } catch (NumberFormatException nfe) {
3399                 return -1;
3400             }
3401 
3402             if (p > start && p < n) {
3403                 // IPv4 address is followed by something - check that
3404                 // it's a ":" as this is the only valid character to
3405                 // follow an address.
3406                 if (input.charAt(p) != ':') {
3407                     p = -1;
3408                 }
3409             }
3410 
3411             if (p > start)
3412                 host = input.substring(start, p);
3413 
3414             return p;
3415         }
3416 
3417         // hostname      = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ]
3418         // domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
3419         // toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
3420         //
3421         private int parseHostname(int start, int n)
3422             throws URISyntaxException
3423         {
3424             int p = start;
3425             int q;
3426             int l = -1;                 // Start of last parsed label
3427 
3428             do {
3429                 // domainlabel = alphanum [ *( alphanum | "-" ) alphanum ]
3430                 q = scan(p, n, L_ALPHANUM, H_ALPHANUM);
3431                 if (q <= p)
3432                     break;
3433                 l = p;
3434                 if (q > p) {
3435                     p = q;
3436                     q = scan(p, n, L_ALPHANUM | L_DASH, H_ALPHANUM | H_DASH);
3437                     if (q > p) {
3438                         if (input.charAt(q - 1) == '-')
3439                             fail("Illegal character in hostname", q - 1);
3440                         p = q;
3441                     }
3442                 }
3443                 q = scan(p, n, '.');
3444                 if (q <= p)
3445                     break;
3446                 p = q;
3447             } while (p < n);
3448 
3449             if ((p < n) && !at(p, n, ':'))
3450                 fail("Illegal character in hostname", p);
3451 
3452             if (l < 0)
3453                 failExpecting("hostname", start);
3454 
3455             // for a fully qualified hostname check that the rightmost
3456             // label starts with an alpha character.
3457             if (l > start && !match(input.charAt(l), L_ALPHA, H_ALPHA)) {
3458                 fail("Illegal character in hostname", l);
3459             }
3460 
3461             host = input.substring(start, p);
3462             return p;
3463         }
3464 
3465 
3466         // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture
3467         //
3468         // Bug: The grammar in RFC2373 Appendix B does not allow addresses of
3469         // the form ::12.34.56.78, which are clearly shown in the examples
3470         // earlier in the document.  Here is the original grammar:
3471         //
3472         //   IPv6address = hexpart [ ":" IPv4address ]
3473         //   hexpart     = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
3474         //   hexseq      = hex4 *( ":" hex4)
3475         //   hex4        = 1*4HEXDIG
3476         //
3477         // We therefore use the following revised grammar:
3478         //
3479         //   IPv6address = hexseq [ ":" IPv4address ]
3480         //                 | hexseq [ "::" [ hexpost ] ]
3481         //                 | "::" [ hexpost ]
3482         //   hexpost     = hexseq | hexseq ":" IPv4address | IPv4address
3483         //   hexseq      = hex4 *( ":" hex4)
3484         //   hex4        = 1*4HEXDIG
3485         //
3486         // This covers all and only the following cases:
3487         //
3488         //   hexseq
3489         //   hexseq : IPv4address
3490         //   hexseq ::
3491         //   hexseq :: hexseq
3492         //   hexseq :: hexseq : IPv4address
3493         //   hexseq :: IPv4address
3494         //   :: hexseq
3495         //   :: hexseq : IPv4address
3496         //   :: IPv4address
3497         //   ::
3498         //
3499         // Additionally we constrain the IPv6 address as follows :-
3500         //
3501         //  i.  IPv6 addresses without compressed zeros should contain
3502         //      exactly 16 bytes.
3503         //
3504         //  ii. IPv6 addresses with compressed zeros should contain
3505         //      less than 16 bytes.
3506 
3507         private int ipv6byteCount = 0;
3508 
3509         private int parseIPv6Reference(int start, int n)
3510             throws URISyntaxException
3511         {
3512             int p = start;
3513             int q;
3514             boolean compressedZeros = false;
3515 
3516             q = scanHexSeq(p, n);
3517 
3518             if (q > p) {
3519                 p = q;
3520                 if (at(p, n, "::")) {
3521                     compressedZeros = true;
3522                     p = scanHexPost(p + 2, n);
3523                 } else if (at(p, n, ':')) {
3524                     p = takeIPv4Address(p + 1,  n, "IPv4 address");
3525                     ipv6byteCount += 4;
3526                 }
3527             } else if (at(p, n, "::")) {
3528                 compressedZeros = true;
3529                 p = scanHexPost(p + 2, n);
3530             }
3531             if (p < n)
3532                 fail("Malformed IPv6 address", start);
3533             if (ipv6byteCount > 16)
3534                 fail("IPv6 address too long", start);
3535             if (!compressedZeros && ipv6byteCount < 16)
3536                 fail("IPv6 address too short", start);
3537             if (compressedZeros && ipv6byteCount == 16)
3538                 fail("Malformed IPv6 address", start);
3539 
3540             return p;
3541         }
3542 
3543         private int scanHexPost(int start, int n)
3544             throws URISyntaxException
3545         {
3546             int p = start;
3547             int q;
3548 
3549             if (p == n)
3550                 return p;
3551 
3552             q = scanHexSeq(p, n);
3553             if (q > p) {
3554                 p = q;
3555                 if (at(p, n, ':')) {
3556                     p++;
3557                     p = takeIPv4Address(p, n, "hex digits or IPv4 address");
3558                     ipv6byteCount += 4;
3559                 }
3560             } else {
3561                 p = takeIPv4Address(p, n, "hex digits or IPv4 address");
3562                 ipv6byteCount += 4;
3563             }
3564             return p;
3565         }
3566 
3567         // Scan a hex sequence; return -1 if one could not be scanned
3568         //
3569         private int scanHexSeq(int start, int n)
3570             throws URISyntaxException
3571         {
3572             int p = start;
3573             int q;
3574 
3575             q = scan(p, n, L_HEX, H_HEX);
3576             if (q <= p)
3577                 return -1;
3578             if (at(q, n, '.'))          // Beginning of IPv4 address
3579                 return -1;
3580             if (q > p + 4)
3581                 fail("IPv6 hexadecimal digit sequence too long", p);
3582             ipv6byteCount += 2;
3583             p = q;
3584             while (p < n) {
3585                 if (!at(p, n, ':'))
3586                     break;
3587                 if (at(p + 1, n, ':'))
3588                     break;              // "::"
3589                 p++;
3590                 q = scan(p, n, L_HEX, H_HEX);
3591                 if (q <= p)
3592                     failExpecting("digits for an IPv6 address", p);
3593                 if (at(q, n, '.')) {    // Beginning of IPv4 address
3594                     p--;
3595                     break;
3596                 }
3597                 if (q > p + 4)
3598                     fail("IPv6 hexadecimal digit sequence too long", p);
3599                 ipv6byteCount += 2;
3600                 p = q;
3601             }
3602 
3603             return p;
3604         }
3605 
3606     }
3607     static {
3608         SharedSecrets.setJavaNetUriAccess(
3609             new JavaNetUriAccess() {
3610                 public URI create(String scheme, String path) {
3611                     return new URI(scheme, path);
3612                 }
3613             }
3614         );
3615     }
3616 }