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