• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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@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 '&#92;u20AC'}),
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 '&#92;uFFFD'}, 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 
URI()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      */
URI(String str)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      */
URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)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      */
URI(String scheme, String authority, String path, String query, String fragment)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      */
URI(String scheme, String host, String path, String fragment)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      */
URI(String scheme, String ssp, String fragment)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      */
create(String str)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      */
parseServerAuthority()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      */
normalize()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      */
resolve(URI uri)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      */
resolve(String str)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      */
relativize(URI uri)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&nbsp;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      */
toURL()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      */
getScheme()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      */
isAbsolute()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      */
isOpaque()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      */
getRawSchemeSpecificPart()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      */
getSchemeSpecificPart()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      */
getRawAuthority()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      */
getAuthority()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      */
getRawUserInfo()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      */
getUserInfo()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      */
getHost()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      */
getPort()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      */
getRawPath()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      */
getPath()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      */
getRawQuery()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      */
getQuery()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      */
getRawFragment()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      */
getFragment()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      */
equals(Object ob)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      */
hashCode()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 type=disc>
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 type=disc>
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      */
compareTo(URI that)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      */
toString()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      */
toASCIIString()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      */
writeObject(ObjectOutputStream os)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      */
readObject(ObjectInputStream is)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
toLower(char c)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
toUpper(char c)1686     private static int toUpper(char c) {
1687         if ((c >= 'a') && (c <= 'z'))
1688             return c - ('a' - 'A');
1689         return c;
1690     }
1691 
equal(String s, String t)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
equalIgnoringCase(String s, String t)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 
hash(int hash, String s)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 
normalizedHash(int hash, String s)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
hashIgnoringCase(int hash, String s)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 
compare(String s, String t)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
compareIgnoringCase(String s, String t)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 
appendSchemeSpecificPart(StringBuffer sb, String opaquePart, String authority, String userInfo, String host, int port, String path, String query)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 
appendFragment(StringBuffer sb, String fragment)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 
toString(String scheme, String opaquePart, String authority, String userInfo, String host, int port, String path, String query, String fragment)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 
defineSchemeSpecificPart()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 
defineString()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)
resolvePath(String base, String child, boolean absolute)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         String np = normalize(path, true);
2024 
2025         // 5.2 (6g): If the result is absolute but the path begins with "../",
2026         // then we simply leave the path as-is
2027 
2028         return np;
2029     }
2030 
2031     // RFC2396 5.2
resolve(URI base, URI child)2032     private static URI resolve(URI base, URI child) {
2033         // check if child if opaque first so that NPE is thrown
2034         // if child is null.
2035         if (child.isOpaque() || base.isOpaque())
2036             return child;
2037 
2038         // 5.2 (2): Reference to current document (lone fragment)
2039         if ((child.scheme == null) && (child.authority == null)
2040             && child.path.equals("") && (child.fragment != null)
2041             && (child.query == null)) {
2042             if ((base.fragment != null)
2043                 && child.fragment.equals(base.fragment)) {
2044                 return base;
2045             }
2046             URI ru = new URI();
2047             ru.scheme = base.scheme;
2048             ru.authority = base.authority;
2049             ru.userInfo = base.userInfo;
2050             ru.host = base.host;
2051             ru.port = base.port;
2052             ru.path = base.path;
2053             ru.fragment = child.fragment;
2054             ru.query = base.query;
2055             return ru;
2056         }
2057 
2058         // 5.2 (3): Child is absolute
2059         if (child.scheme != null)
2060             return child;
2061 
2062         URI ru = new URI();             // Resolved URI
2063         ru.scheme = base.scheme;
2064         ru.query = child.query;
2065         ru.fragment = child.fragment;
2066 
2067         // 5.2 (4): Authority
2068         if (child.authority == null) {
2069             ru.authority = base.authority;
2070             ru.host = base.host;
2071             ru.userInfo = base.userInfo;
2072             ru.port = base.port;
2073 
2074             if (child.path == null || child.path.isEmpty()) {
2075                 // This is an addtional path from RFC 3986 RI, which fixes following RFC 2396
2076                 // "normal" examples:
2077                 // Base: http://a/b/c/d;p?q
2078                 //   "?y" = "http://a/b/c/d;p?y"
2079                 //   ""   = "http://a/b/c/d;p?q"
2080                 // http://b/25897693
2081                 ru.path = base.path;
2082                 ru.query = child.query != null ? child.query : base.query;
2083             } else if ((child.path.length() > 0) && (child.path.charAt(0) == '/')) {
2084                 // 5.2 (5): Child path is absolute
2085                 //
2086                 // There is an additional step from RFC 3986 RI, requiring to remove dots for
2087                 // absolute path as well.
2088                 // http://b/25897693
2089                 ru.path = normalize(child.path, true);
2090             } else {
2091                 // 5.2 (6): Resolve relative path
2092                 ru.path = resolvePath(base.path, child.path, base.isAbsolute());
2093             }
2094         } else {
2095             ru.authority = child.authority;
2096             ru.host = child.host;
2097             ru.userInfo = child.userInfo;
2098             ru.host = child.host;
2099             ru.port = child.port;
2100             ru.path = child.path;
2101         }
2102 
2103         // 5.2 (7): Recombine (nothing to do here)
2104         return ru;
2105     }
2106 
2107     // If the given URI's path is normal then return the URI;
2108     // o.w., return a new URI containing the normalized path.
2109     //
normalize(URI u)2110     private static URI normalize(URI u) {
2111         if (u.isOpaque() || (u.path == null) || (u.path.length() == 0))
2112             return u;
2113 
2114         String np = normalize(u.path);
2115         if (np == u.path)
2116             return u;
2117 
2118         URI v = new URI();
2119         v.scheme = u.scheme;
2120         v.fragment = u.fragment;
2121         v.authority = u.authority;
2122         v.userInfo = u.userInfo;
2123         v.host = u.host;
2124         v.port = u.port;
2125         v.path = np;
2126         v.query = u.query;
2127         return v;
2128     }
2129 
2130     // If both URIs are hierarchical, their scheme and authority components are
2131     // identical, and the base path is a prefix of the child's path, then
2132     // return a relative URI that, when resolved against the base, yields the
2133     // child; otherwise, return the child.
2134     //
relativize(URI base, URI child)2135     private static URI relativize(URI base, URI child) {
2136         // check if child if opaque first so that NPE is thrown
2137         // if child is null.
2138         if (child.isOpaque() || base.isOpaque())
2139             return child;
2140         if (!equalIgnoringCase(base.scheme, child.scheme)
2141             || !equal(base.authority, child.authority))
2142             return child;
2143 
2144         String bp = normalize(base.path);
2145         String cp = normalize(child.path);
2146         if (!bp.equals(cp)) {
2147             // Android-changed: The original OpenJdk implementation would append a trailing slash
2148             // to paths like "/a/b" before relativizing them. This would relativize /a/b/c to
2149             // "/c" against "/a/b" the android implementation did not do this. It would assume that
2150             // "b" wasn't a directory and relativize the path to "/b/c". The spec is pretty vague
2151             // about this but this change is being made because we have several tests that expect
2152             // this behaviour.
2153             if (bp.indexOf('/') != -1) {
2154                 bp = bp.substring(0, bp.lastIndexOf('/') + 1);
2155             }
2156 
2157             if (!cp.startsWith(bp))
2158                 return child;
2159         }
2160 
2161         URI v = new URI();
2162         v.path = cp.substring(bp.length());
2163         v.query = child.query;
2164         v.fragment = child.fragment;
2165         return v;
2166     }
2167 
2168 
2169 
2170     // -- Path normalization --
2171 
2172     // The following algorithm for path normalization avoids the creation of a
2173     // string object for each segment, as well as the use of a string buffer to
2174     // compute the final result, by using a single char array and editing it in
2175     // place.  The array is first split into segments, replacing each slash
2176     // with '\0' and creating a segment-index array, each element of which is
2177     // the index of the first char in the corresponding segment.  We then walk
2178     // through both arrays, removing ".", "..", and other segments as necessary
2179     // by setting their entries in the index array to -1.  Finally, the two
2180     // arrays are used to rejoin the segments and compute the final result.
2181     //
2182     // This code is based upon src/solaris/native/java/io/canonicalize_md.c
2183 
2184 
2185     // Check the given path to see if it might need normalization.  A path
2186     // might need normalization if it contains duplicate slashes, a "."
2187     // segment, or a ".." segment.  Return -1 if no further normalization is
2188     // possible, otherwise return the number of segments found.
2189     //
2190     // This method takes a string argument rather than a char array so that
2191     // this test can be performed without invoking path.toCharArray().
2192     //
needsNormalization(String path)2193     static private int needsNormalization(String path) {
2194         boolean normal = true;
2195         int ns = 0;                     // Number of segments
2196         int end = path.length() - 1;    // Index of last char in path
2197         int p = 0;                      // Index of next char in path
2198 
2199         // Skip initial slashes
2200         while (p <= end) {
2201             if (path.charAt(p) != '/') break;
2202             p++;
2203         }
2204         if (p > 1) normal = false;
2205 
2206         // Scan segments
2207         while (p <= end) {
2208 
2209             // Looking at "." or ".." ?
2210             if ((path.charAt(p) == '.')
2211                 && ((p == end)
2212                     || ((path.charAt(p + 1) == '/')
2213                         || ((path.charAt(p + 1) == '.')
2214                             && ((p + 1 == end)
2215                                 || (path.charAt(p + 2) == '/')))))) {
2216                 normal = false;
2217             }
2218             ns++;
2219 
2220             // Find beginning of next segment
2221             while (p <= end) {
2222                 if (path.charAt(p++) != '/')
2223                     continue;
2224 
2225                 // Skip redundant slashes
2226                 while (p <= end) {
2227                     if (path.charAt(p) != '/') break;
2228                     normal = false;
2229                     p++;
2230                 }
2231 
2232                 break;
2233             }
2234         }
2235 
2236         return normal ? -1 : ns;
2237     }
2238 
2239 
2240     // Split the given path into segments, replacing slashes with nulls and
2241     // filling in the given segment-index array.
2242     //
2243     // Preconditions:
2244     //   segs.length == Number of segments in path
2245     //
2246     // Postconditions:
2247     //   All slashes in path replaced by '\0'
2248     //   segs[i] == Index of first char in segment i (0 <= i < segs.length)
2249     //
split(char[] path, int[] segs)2250     static private void split(char[] path, int[] segs) {
2251         int end = path.length - 1;      // Index of last char in path
2252         int p = 0;                      // Index of next char in path
2253         int i = 0;                      // Index of current segment
2254 
2255         // Skip initial slashes
2256         while (p <= end) {
2257             if (path[p] != '/') break;
2258             path[p] = '\0';
2259             p++;
2260         }
2261 
2262         while (p <= end) {
2263 
2264             // Note start of segment
2265             segs[i++] = p++;
2266 
2267             // Find beginning of next segment
2268             while (p <= end) {
2269                 if (path[p++] != '/')
2270                     continue;
2271                 path[p - 1] = '\0';
2272 
2273                 // Skip redundant slashes
2274                 while (p <= end) {
2275                     if (path[p] != '/') break;
2276                     path[p++] = '\0';
2277                 }
2278                 break;
2279             }
2280         }
2281 
2282         if (i != segs.length)
2283             throw new InternalError();  // ASSERT
2284     }
2285 
2286 
2287     // Join the segments in the given path according to the given segment-index
2288     // array, ignoring those segments whose index entries have been set to -1,
2289     // and inserting slashes as needed.  Return the length of the resulting
2290     // path.
2291     //
2292     // Preconditions:
2293     //   segs[i] == -1 implies segment i is to be ignored
2294     //   path computed by split, as above, with '\0' having replaced '/'
2295     //
2296     // Postconditions:
2297     //   path[0] .. path[return value] == Resulting path
2298     //
join(char[] path, int[] segs)2299     static private int join(char[] path, int[] segs) {
2300         int ns = segs.length;           // Number of segments
2301         int end = path.length - 1;      // Index of last char in path
2302         int p = 0;                      // Index of next path char to write
2303 
2304         if (path[p] == '\0') {
2305             // Restore initial slash for absolute paths
2306             path[p++] = '/';
2307         }
2308 
2309         for (int i = 0; i < ns; i++) {
2310             int q = segs[i];            // Current segment
2311             if (q == -1)
2312                 // Ignore this segment
2313                 continue;
2314 
2315             if (p == q) {
2316                 // We're already at this segment, so just skip to its end
2317                 while ((p <= end) && (path[p] != '\0'))
2318                     p++;
2319                 if (p <= end) {
2320                     // Preserve trailing slash
2321                     path[p++] = '/';
2322                 }
2323             } else if (p < q) {
2324                 // Copy q down to p
2325                 while ((q <= end) && (path[q] != '\0'))
2326                     path[p++] = path[q++];
2327                 if (q <= end) {
2328                     // Preserve trailing slash
2329                     path[p++] = '/';
2330                 }
2331             } else
2332                 throw new InternalError(); // ASSERT false
2333         }
2334 
2335         return p;
2336     }
2337 
2338 
2339     // Remove "." segments from the given path, and remove segment pairs
2340     // consisting of a non-".." segment followed by a ".." segment.
2341     //
removeDots(char[] path, int[] segs, boolean removeLeading)2342     private static void removeDots(char[] path, int[] segs, boolean removeLeading) {
2343         int ns = segs.length;
2344         int end = path.length - 1;
2345 
2346         for (int i = 0; i < ns; i++) {
2347             int dots = 0;               // Number of dots found (0, 1, or 2)
2348 
2349             // Find next occurrence of "." or ".."
2350             do {
2351                 int p = segs[i];
2352                 if (path[p] == '.') {
2353                     if (p == end) {
2354                         dots = 1;
2355                         break;
2356                     } else if (path[p + 1] == '\0') {
2357                         dots = 1;
2358                         break;
2359                     } else if ((path[p + 1] == '.')
2360                                && ((p + 1 == end)
2361                                    || (path[p + 2] == '\0'))) {
2362                         dots = 2;
2363                         break;
2364                     }
2365                 }
2366                 i++;
2367             } while (i < ns);
2368             if ((i > ns) || (dots == 0))
2369                 break;
2370 
2371             if (dots == 1) {
2372                 // Remove this occurrence of "."
2373                 segs[i] = -1;
2374             } else {
2375                 // If there is a preceding non-".." segment, remove both that
2376                 // segment and this occurrence of ".."
2377                 int j;
2378                 for (j = i - 1; j >= 0; j--) {
2379                     if (segs[j] != -1) break;
2380                 }
2381                 if (j >= 0) {
2382                     int q = segs[j];
2383                     if (!((path[q] == '.')
2384                           && (path[q + 1] == '.')
2385                           && (path[q + 2] == '\0'))) {
2386                         segs[i] = -1;
2387                         segs[j] = -1;
2388                     }
2389                 } else if (removeLeading) {
2390                     // This is a leading ".." segment. Per RFC 3986 RI, this should be removed as
2391                     // well. This fixes RFC 2396 "abnormal" examples.
2392                     // http://b/25897693
2393                     segs[i] = -1;
2394                 }
2395             }
2396         }
2397     }
2398 
2399 
2400     // DEVIATION: If the normalized path is relative, and if the first
2401     // segment could be parsed as a scheme name, then prepend a "." segment
2402     //
maybeAddLeadingDot(char[] path, int[] segs)2403     private static void maybeAddLeadingDot(char[] path, int[] segs) {
2404 
2405         if (path[0] == '\0')
2406             // The path is absolute
2407             return;
2408 
2409         int ns = segs.length;
2410         int f = 0;                      // Index of first segment
2411         while (f < ns) {
2412             if (segs[f] >= 0)
2413                 break;
2414             f++;
2415         }
2416         if ((f >= ns) || (f == 0))
2417             // The path is empty, or else the original first segment survived,
2418             // in which case we already know that no leading "." is needed
2419             return;
2420 
2421         int p = segs[f];
2422         while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++;
2423         if (p >= path.length || path[p] == '\0')
2424             // No colon in first segment, so no "." needed
2425             return;
2426 
2427         // At this point we know that the first segment is unused,
2428         // hence we can insert a "." segment at that position
2429         path[0] = '.';
2430         path[1] = '\0';
2431         segs[0] = 0;
2432     }
2433 
2434 
2435     // Normalize the given path string.  A normal path string has no empty
2436     // segments (i.e., occurrences of "//"), no segments equal to ".", and no
2437     // segments equal to ".." that are preceded by a segment not equal to "..".
2438     // In contrast to Unix-style pathname normalization, for URI paths we
2439     // always retain trailing slashes.
2440     //
normalize(String ps)2441     private static String normalize(String ps) {
2442         return normalize(ps, false);
2443     }
2444 
normalize(String ps, boolean removeLeading)2445     private static String normalize(String ps, boolean removeLeading) {
2446 
2447         // Does this path need normalization?
2448         int ns = needsNormalization(ps);        // Number of segments
2449         if (ns < 0)
2450             // Nope -- just return it
2451             return ps;
2452 
2453         char[] path = ps.toCharArray();         // Path in char-array form
2454 
2455         // Split path into segments
2456         int[] segs = new int[ns];               // Segment-index array
2457         split(path, segs);
2458 
2459         // Remove dots
2460         removeDots(path, segs, removeLeading);
2461 
2462         // Prevent scheme-name confusion
2463         maybeAddLeadingDot(path, segs);
2464 
2465         // Join the remaining segments and return the result
2466         String s = new String(path, 0, join(path, segs));
2467         if (s.equals(ps)) {
2468             // string was already normalized
2469             return ps;
2470         }
2471         return s;
2472     }
2473 
2474 
2475 
2476     // -- Character classes for parsing --
2477 
2478     // RFC2396 precisely specifies which characters in the US-ASCII charset are
2479     // permissible in the various components of a URI reference.  We here
2480     // define a set of mask pairs to aid in enforcing these restrictions.  Each
2481     // mask pair consists of two longs, a low mask and a high mask.  Taken
2482     // together they represent a 128-bit mask, where bit i is set iff the
2483     // character with value i is permitted.
2484     //
2485     // This approach is more efficient than sequentially searching arrays of
2486     // permitted characters.  It could be made still more efficient by
2487     // precompiling the mask information so that a character's presence in a
2488     // given mask could be determined by a single table lookup.
2489 
2490     // Compute the low-order mask for the characters in the given string
lowMask(String chars)2491     private static long lowMask(String chars) {
2492         int n = chars.length();
2493         long m = 0;
2494         for (int i = 0; i < n; i++) {
2495             char c = chars.charAt(i);
2496             if (c < 64)
2497                 m |= (1L << c);
2498         }
2499         return m;
2500     }
2501 
2502     // Compute the high-order mask for the characters in the given string
highMask(String chars)2503     private static long highMask(String chars) {
2504         int n = chars.length();
2505         long m = 0;
2506         for (int i = 0; i < n; i++) {
2507             char c = chars.charAt(i);
2508             if ((c >= 64) && (c < 128))
2509                 m |= (1L << (c - 64));
2510         }
2511         return m;
2512     }
2513 
2514     // Compute a low-order mask for the characters
2515     // between first and last, inclusive
lowMask(char first, char last)2516     private static long lowMask(char first, char last) {
2517         long m = 0;
2518         int f = Math.max(Math.min(first, 63), 0);
2519         int l = Math.max(Math.min(last, 63), 0);
2520         for (int i = f; i <= l; i++)
2521             m |= 1L << i;
2522         return m;
2523     }
2524 
2525     // Compute a high-order mask for the characters
2526     // between first and last, inclusive
highMask(char first, char last)2527     private static long highMask(char first, char last) {
2528         long m = 0;
2529         int f = Math.max(Math.min(first, 127), 64) - 64;
2530         int l = Math.max(Math.min(last, 127), 64) - 64;
2531         for (int i = f; i <= l; i++)
2532             m |= 1L << i;
2533         return m;
2534     }
2535 
2536     // Tell whether the given character is permitted by the given mask pair
match(char c, long lowMask, long highMask)2537     private static boolean match(char c, long lowMask, long highMask) {
2538         if (c == 0) // 0 doesn't have a slot in the mask. So, it never matches.
2539             return false;
2540         if (c < 64)
2541             return ((1L << c) & lowMask) != 0;
2542         if (c < 128)
2543             return ((1L << (c - 64)) & highMask) != 0;
2544         return false;
2545     }
2546 
2547     // Character-class masks, in reverse order from RFC2396 because
2548     // initializers for static fields cannot make forward references.
2549 
2550     // digit    = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
2551     //            "8" | "9"
2552     private static final long L_DIGIT = lowMask('0', '9');
2553     private static final long H_DIGIT = 0L;
2554 
2555     // upalpha  = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
2556     //            "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
2557     //            "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
2558     private static final long L_UPALPHA = 0L;
2559     private static final long H_UPALPHA = highMask('A', 'Z');
2560 
2561     // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
2562     //            "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
2563     //            "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
2564     private static final long L_LOWALPHA = 0L;
2565     private static final long H_LOWALPHA = highMask('a', 'z');
2566 
2567     // alpha         = lowalpha | upalpha
2568     private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
2569     private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
2570 
2571     // alphanum      = alpha | digit
2572     private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
2573     private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
2574 
2575     // hex           = digit | "A" | "B" | "C" | "D" | "E" | "F" |
2576     //                         "a" | "b" | "c" | "d" | "e" | "f"
2577     private static final long L_HEX = L_DIGIT;
2578     private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f');
2579 
2580     // mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" |
2581     //                 "(" | ")"
2582     private static final long L_MARK = lowMask("-_.!~*'()");
2583     private static final long H_MARK = highMask("-_.!~*'()");
2584 
2585     // unreserved    = alphanum | mark
2586     private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
2587     private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
2588 
2589     // reserved      = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
2590     //                 "$" | "," | "[" | "]"
2591     // Added per RFC2732: "[", "]"
2592     private static final long L_RESERVED = lowMask(";/?:@&=+$,[]");
2593     private static final long H_RESERVED = highMask(";/?:@&=+$,[]");
2594 
2595     // The zero'th bit is used to indicate that escape pairs and non-US-ASCII
2596     // characters are allowed; this is handled by the scanEscape method below.
2597     private static final long L_ESCAPED = 1L;
2598     private static final long H_ESCAPED = 0L;
2599 
2600     // uric          = reserved | unreserved | escaped
2601     private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED;
2602     private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED;
2603 
2604     // pchar         = unreserved | escaped |
2605     //                 ":" | "@" | "&" | "=" | "+" | "$" | ","
2606     private static final long L_PCHAR
2607         = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,");
2608     private static final long H_PCHAR
2609         = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,");
2610 
2611     // All valid path characters
2612     private static final long L_PATH = L_PCHAR | lowMask(";/");
2613     private static final long H_PATH = H_PCHAR | highMask(";/");
2614 
2615     // Dash, for use in domainlabel and toplabel
2616     private static final long L_DASH = lowMask("-");
2617     private static final long H_DASH = highMask("-");
2618 
2619     // UNDERSCORE, for use in domainlabel and toplabel
2620     private static final long L_UNDERSCORE = lowMask("_");
2621     private static final long H_UNDERSCORE = highMask("_");
2622 
2623     // Dot, for use in hostnames
2624     private static final long L_DOT = lowMask(".");
2625     private static final long H_DOT = highMask(".");
2626 
2627     // userinfo      = *( unreserved | escaped |
2628     //                    ";" | ":" | "&" | "=" | "+" | "$" | "," )
2629     private static final long L_USERINFO
2630         = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,");
2631     private static final long H_USERINFO
2632         = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,");
2633 
2634     // reg_name      = 1*( unreserved | escaped | "$" | "," |
2635     //                     ";" | ":" | "@" | "&" | "=" | "+" )
2636     private static final long L_REG_NAME
2637         = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+");
2638     private static final long H_REG_NAME
2639         = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+");
2640 
2641     // All valid characters for server-based authorities
2642     private static final long L_SERVER
2643         = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]");
2644     private static final long H_SERVER
2645         = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]");
2646 
2647     // Special case of server authority that represents an IPv6 address
2648     // In this case, a % does not signify an escape sequence
2649     private static final long L_SERVER_PERCENT
2650         = L_SERVER | lowMask("%");
2651     private static final long H_SERVER_PERCENT
2652         = H_SERVER | highMask("%");
2653     private static final long L_LEFT_BRACKET = lowMask("[");
2654     private static final long H_LEFT_BRACKET = highMask("[");
2655 
2656     // scheme        = alpha *( alpha | digit | "+" | "-" | "." )
2657     private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-.");
2658     private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-.");
2659 
2660     // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
2661     //                 "&" | "=" | "+" | "$" | ","
2662     private static final long L_URIC_NO_SLASH
2663         = L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,");
2664     private static final long H_URIC_NO_SLASH
2665         = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,");
2666 
2667 
2668     // -- Escaping and encoding --
2669 
2670     private final static char[] hexDigits = {
2671         '0', '1', '2', '3', '4', '5', '6', '7',
2672         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
2673     };
2674 
appendEscape(StringBuffer sb, byte b)2675     private static void appendEscape(StringBuffer sb, byte b) {
2676         sb.append('%');
2677         sb.append(hexDigits[(b >> 4) & 0x0f]);
2678         sb.append(hexDigits[(b >> 0) & 0x0f]);
2679     }
2680 
appendEncoded(StringBuffer sb, char c)2681     private static void appendEncoded(StringBuffer sb, char c) {
2682         ByteBuffer bb = null;
2683         try {
2684             bb = ThreadLocalCoders.encoderFor("UTF-8")
2685                 .encode(CharBuffer.wrap("" + c));
2686         } catch (CharacterCodingException x) {
2687             assert false;
2688         }
2689         while (bb.hasRemaining()) {
2690             int b = bb.get() & 0xff;
2691             if (b >= 0x80)
2692                 appendEscape(sb, (byte)b);
2693             else
2694                 sb.append((char)b);
2695         }
2696     }
2697 
2698     // Quote any characters in s that are not permitted
2699     // by the given mask pair
2700     //
quote(String s, long lowMask, long highMask)2701     private static String quote(String s, long lowMask, long highMask) {
2702         int n = s.length();
2703         StringBuffer sb = null;
2704         boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
2705         for (int i = 0; i < s.length(); i++) {
2706             char c = s.charAt(i);
2707             if (c < '\u0080') {
2708                 if (!match(c, lowMask, highMask)) {
2709                     if (sb == null) {
2710                         sb = new StringBuffer();
2711                         sb.append(s.substring(0, i));
2712                     }
2713                     appendEscape(sb, (byte)c);
2714                 } else {
2715                     if (sb != null)
2716                         sb.append(c);
2717                 }
2718             } else if (allowNonASCII
2719                        && (Character.isSpaceChar(c)
2720                            || Character.isISOControl(c))) {
2721                 if (sb == null) {
2722                     sb = new StringBuffer();
2723                     sb.append(s.substring(0, i));
2724                 }
2725                 appendEncoded(sb, c);
2726             } else {
2727                 if (sb != null)
2728                     sb.append(c);
2729             }
2730         }
2731         return (sb == null) ? s : sb.toString();
2732     }
2733 
2734     // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets,
2735     // assuming that s is otherwise legal
2736     //
encode(String s)2737     private static String encode(String s) {
2738         int n = s.length();
2739         if (n == 0)
2740             return s;
2741 
2742         // First check whether we actually need to encode
2743         for (int i = 0;;) {
2744             if (s.charAt(i) >= '\u0080')
2745                 break;
2746             if (++i >= n)
2747                 return s;
2748         }
2749 
2750         String ns = Normalizer.normalize(s, Normalizer.Form.NFC);
2751         ByteBuffer bb = null;
2752         try {
2753             bb = ThreadLocalCoders.encoderFor("UTF-8")
2754                 .encode(CharBuffer.wrap(ns));
2755         } catch (CharacterCodingException x) {
2756             assert false;
2757         }
2758 
2759         StringBuffer sb = new StringBuffer();
2760         while (bb.hasRemaining()) {
2761             int b = bb.get() & 0xff;
2762             if (b >= 0x80)
2763                 appendEscape(sb, (byte)b);
2764             else
2765                 sb.append((char)b);
2766         }
2767         return sb.toString();
2768     }
2769 
decode(char c)2770     private static int decode(char c) {
2771         if ((c >= '0') && (c <= '9'))
2772             return c - '0';
2773         if ((c >= 'a') && (c <= 'f'))
2774             return c - 'a' + 10;
2775         if ((c >= 'A') && (c <= 'F'))
2776             return c - 'A' + 10;
2777         assert false;
2778         return -1;
2779     }
2780 
decode(char c1, char c2)2781     private static byte decode(char c1, char c2) {
2782         return (byte)(  ((decode(c1) & 0xf) << 4)
2783                       | ((decode(c2) & 0xf) << 0));
2784     }
2785 
2786     // Evaluates all escapes in s, applying UTF-8 decoding if needed.  Assumes
2787     // that escapes are well-formed syntactically, i.e., of the form %XX.  If a
2788     // sequence of escaped octets is not valid UTF-8 then the erroneous octets
2789     // are replaced with '\uFFFD'.
2790     // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal
2791     //            with a scope_id
2792     //
decode(String s)2793     private static String decode(String s) {
2794         if (s == null)
2795             return s;
2796         int n = s.length();
2797         if (n == 0)
2798             return s;
2799         if (s.indexOf('%') < 0)
2800             return s;
2801 
2802         StringBuffer sb = new StringBuffer(n);
2803         ByteBuffer bb = ByteBuffer.allocate(n);
2804         CharBuffer cb = CharBuffer.allocate(n);
2805         CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8")
2806             .onMalformedInput(CodingErrorAction.REPLACE)
2807             .onUnmappableCharacter(CodingErrorAction.REPLACE);
2808 
2809         // This is not horribly efficient, but it will do for now
2810         char c = s.charAt(0);
2811         boolean betweenBrackets = false;
2812 
2813         for (int i = 0; i < n;) {
2814             assert c == s.charAt(i);    // Loop invariant
2815             if (c == '[') {
2816                 betweenBrackets = true;
2817             } else if (betweenBrackets && c == ']') {
2818                 betweenBrackets = false;
2819             }
2820             if (c != '%' || betweenBrackets) {
2821                 sb.append(c);
2822                 if (++i >= n)
2823                     break;
2824                 c = s.charAt(i);
2825                 continue;
2826             }
2827             bb.clear();
2828             int ui = i;
2829             for (;;) {
2830                 assert (n - i >= 2);
2831                 bb.put(decode(s.charAt(++i), s.charAt(++i)));
2832                 if (++i >= n)
2833                     break;
2834                 c = s.charAt(i);
2835                 if (c != '%')
2836                     break;
2837             }
2838             bb.flip();
2839             cb.clear();
2840             dec.reset();
2841             CoderResult cr = dec.decode(bb, cb, true);
2842             assert cr.isUnderflow();
2843             cr = dec.flush(cb);
2844             assert cr.isUnderflow();
2845             sb.append(cb.flip().toString());
2846         }
2847 
2848         return sb.toString();
2849     }
2850 
2851 
2852     // -- Parsing --
2853 
2854     // For convenience we wrap the input URI string in a new instance of the
2855     // following internal class.  This saves always having to pass the input
2856     // string as an argument to each internal scan/parse method.
2857 
2858     private class Parser {
2859 
2860         private String input;           // URI input string
2861         private boolean requireServerAuthority = false;
2862 
Parser(String s)2863         Parser(String s) {
2864             input = s;
2865             string = s;
2866         }
2867 
2868         // -- Methods for throwing URISyntaxException in various ways --
2869 
fail(String reason)2870         private void fail(String reason) throws URISyntaxException {
2871             throw new URISyntaxException(input, reason);
2872         }
2873 
fail(String reason, int p)2874         private void fail(String reason, int p) throws URISyntaxException {
2875             throw new URISyntaxException(input, reason, p);
2876         }
2877 
failExpecting(String expected, int p)2878         private void failExpecting(String expected, int p)
2879             throws URISyntaxException
2880         {
2881             fail("Expected " + expected, p);
2882         }
2883 
failExpecting(String expected, String prior, int p)2884         private void failExpecting(String expected, String prior, int p)
2885             throws URISyntaxException
2886         {
2887             fail("Expected " + expected + " following " + prior, p);
2888         }
2889 
2890 
2891         // -- Simple access to the input string --
2892 
2893         // Return a substring of the input string
2894         //
substring(int start, int end)2895         private String substring(int start, int end) {
2896             return input.substring(start, end);
2897         }
2898 
2899         // Return the char at position p,
2900         // assuming that p < input.length()
2901         //
charAt(int p)2902         private char charAt(int p) {
2903             return input.charAt(p);
2904         }
2905 
2906         // Tells whether start < end and, if so, whether charAt(start) == c
2907         //
at(int start, int end, char c)2908         private boolean at(int start, int end, char c) {
2909             return (start < end) && (charAt(start) == c);
2910         }
2911 
2912         // Tells whether start + s.length() < end and, if so,
2913         // whether the chars at the start position match s exactly
2914         //
at(int start, int end, String s)2915         private boolean at(int start, int end, String s) {
2916             int p = start;
2917             int sn = s.length();
2918             if (sn > end - p)
2919                 return false;
2920             int i = 0;
2921             while (i < sn) {
2922                 if (charAt(p++) != s.charAt(i)) {
2923                     break;
2924                 }
2925                 i++;
2926             }
2927             return (i == sn);
2928         }
2929 
2930 
2931         // -- Scanning --
2932 
2933         // The various scan and parse methods that follow use a uniform
2934         // convention of taking the current start position and end index as
2935         // their first two arguments.  The start is inclusive while the end is
2936         // exclusive, just as in the String class, i.e., a start/end pair
2937         // denotes the left-open interval [start, end) of the input string.
2938         //
2939         // These methods never proceed past the end position.  They may return
2940         // -1 to indicate outright failure, but more often they simply return
2941         // the position of the first char after the last char scanned.  Thus
2942         // a typical idiom is
2943         //
2944         //     int p = start;
2945         //     int q = scan(p, end, ...);
2946         //     if (q > p)
2947         //         // We scanned something
2948         //         ...;
2949         //     else if (q == p)
2950         //         // We scanned nothing
2951         //         ...;
2952         //     else if (q == -1)
2953         //         // Something went wrong
2954         //         ...;
2955 
2956 
2957         // Scan a specific char: If the char at the given start position is
2958         // equal to c, return the index of the next char; otherwise, return the
2959         // start position.
2960         //
scan(int start, int end, char c)2961         private int scan(int start, int end, char c) {
2962             if ((start < end) && (charAt(start) == c))
2963                 return start + 1;
2964             return start;
2965         }
2966 
2967         // Scan forward from the given start position.  Stop at the first char
2968         // in the err string (in which case -1 is returned), or the first char
2969         // in the stop string (in which case the index of the preceding char is
2970         // returned), or the end of the input string (in which case the length
2971         // of the input string is returned).  May return the start position if
2972         // nothing matches.
2973         //
scan(int start, int end, String err, String stop)2974         private int scan(int start, int end, String err, String stop) {
2975             int p = start;
2976             while (p < end) {
2977                 char c = charAt(p);
2978                 if (err.indexOf(c) >= 0)
2979                     return -1;
2980                 if (stop.indexOf(c) >= 0)
2981                     break;
2982                 p++;
2983             }
2984             return p;
2985         }
2986 
2987         // Scan a potential escape sequence, starting at the given position,
2988         // with the given first char (i.e., charAt(start) == c).
2989         //
2990         // This method assumes that if escapes are allowed then visible
2991         // non-US-ASCII chars are also allowed.
2992         //
scanEscape(int start, int n, char first)2993         private int scanEscape(int start, int n, char first)
2994             throws URISyntaxException
2995         {
2996             int p = start;
2997             char c = first;
2998             if (c == '%') {
2999                 // Process escape pair
3000                 if ((p + 3 <= n)
3001                     && match(charAt(p + 1), L_HEX, H_HEX)
3002                     && match(charAt(p + 2), L_HEX, H_HEX)) {
3003                     return p + 3;
3004                 }
3005                 fail("Malformed escape pair", p);
3006             } else if ((c > 128)
3007                        && !Character.isSpaceChar(c)
3008                        && !Character.isISOControl(c)) {
3009                 // Allow unescaped but visible non-US-ASCII chars
3010                 return p + 1;
3011             }
3012             return p;
3013         }
3014 
3015         // Scan chars that match the given mask pair
3016         //
scan(int start, int n, long lowMask, long highMask)3017         private int scan(int start, int n, long lowMask, long highMask)
3018             throws URISyntaxException
3019         {
3020             int p = start;
3021             while (p < n) {
3022                 char c = charAt(p);
3023                 if (match(c, lowMask, highMask)) {
3024                     p++;
3025                     continue;
3026                 }
3027                 if ((lowMask & L_ESCAPED) != 0) {
3028                     int q = scanEscape(p, n, c);
3029                     if (q > p) {
3030                         p = q;
3031                         continue;
3032                     }
3033                 }
3034                 break;
3035             }
3036             return p;
3037         }
3038 
3039         // Check that each of the chars in [start, end) matches the given mask
3040         //
checkChars(int start, int end, long lowMask, long highMask, String what)3041         private void checkChars(int start, int end,
3042                                 long lowMask, long highMask,
3043                                 String what)
3044             throws URISyntaxException
3045         {
3046             int p = scan(start, end, lowMask, highMask);
3047             if (p < end)
3048                 fail("Illegal character in " + what, p);
3049         }
3050 
3051         // Check that the char at position p matches the given mask
3052         //
checkChar(int p, long lowMask, long highMask, String what)3053         private void checkChar(int p,
3054                                long lowMask, long highMask,
3055                                String what)
3056             throws URISyntaxException
3057         {
3058             checkChars(p, p + 1, lowMask, highMask, what);
3059         }
3060 
3061 
3062         // -- Parsing --
3063 
3064         // [<scheme>:]<scheme-specific-part>[#<fragment>]
3065         //
parse(boolean rsa)3066         void parse(boolean rsa) throws URISyntaxException {
3067             requireServerAuthority = rsa;
3068             int ssp;                    // Start of scheme-specific part
3069             int n = input.length();
3070             int p = scan(0, n, "/?#", ":");
3071             if ((p >= 0) && at(p, n, ':')) {
3072                 if (p == 0)
3073                     failExpecting("scheme name", 0);
3074                 checkChar(0, L_ALPHA, H_ALPHA, "scheme name");
3075                 checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name");
3076                 scheme = substring(0, p);
3077                 p++;                    // Skip ':'
3078                 ssp = p;
3079                 if (at(p, n, '/')) {
3080                     p = parseHierarchical(p, n);
3081                 } else {
3082                     int q = scan(p, n, "", "#");
3083                     if (q <= p)
3084                         failExpecting("scheme-specific part", p);
3085                     checkChars(p, q, L_URIC, H_URIC, "opaque part");
3086                     p = q;
3087                 }
3088             } else {
3089                 ssp = 0;
3090                 p = parseHierarchical(0, n);
3091             }
3092             schemeSpecificPart = substring(ssp, p);
3093             if (at(p, n, '#')) {
3094                 checkChars(p + 1, n, L_URIC, H_URIC, "fragment");
3095                 fragment = substring(p + 1, n);
3096                 p = n;
3097             }
3098             if (p < n)
3099                 fail("end of URI", p);
3100         }
3101 
3102         // [//authority]<path>[?<query>]
3103         //
3104         // DEVIATION from RFC2396: We allow an empty authority component as
3105         // long as it's followed by a non-empty path, query component, or
3106         // fragment component.  This is so that URIs such as "file:///foo/bar"
3107         // will parse.  This seems to be the intent of RFC2396, though the
3108         // grammar does not permit it.  If the authority is empty then the
3109         // userInfo, host, and port components are undefined.
3110         //
3111         // DEVIATION from RFC2396: We allow empty relative paths.  This seems
3112         // to be the intent of RFC2396, but the grammar does not permit it.
3113         // The primary consequence of this deviation is that "#f" parses as a
3114         // relative URI with an empty path.
3115         //
parseHierarchical(int start, int n)3116         private int parseHierarchical(int start, int n)
3117             throws URISyntaxException
3118         {
3119             int p = start;
3120             if (at(p, n, '/') && at(p + 1, n, '/')) {
3121                 p += 2;
3122                 int q = scan(p, n, "", "/?#");
3123                 if (q > p) {
3124                     p = parseAuthority(p, q);
3125                 } else if (q < n) {
3126                     // DEVIATION: Allow empty authority prior to non-empty
3127                     // path, query component or fragment identifier
3128                 } else
3129                     failExpecting("authority", p);
3130             }
3131             int q = scan(p, n, "", "?#"); // DEVIATION: May be empty
3132             checkChars(p, q, L_PATH, H_PATH, "path");
3133             path = substring(p, q);
3134             p = q;
3135             if (at(p, n, '?')) {
3136                 p++;
3137                 q = scan(p, n, "", "#");
3138                 checkChars(p, q, L_URIC, H_URIC, "query");
3139                 query = substring(p, q);
3140                 p = q;
3141             }
3142             return p;
3143         }
3144 
3145         // authority     = server | reg_name
3146         //
3147         // Ambiguity: An authority that is a registry name rather than a server
3148         // might have a prefix that parses as a server.  We use the fact that
3149         // the authority component is always followed by '/' or the end of the
3150         // input string to resolve this: If the complete authority did not
3151         // parse as a server then we try to parse it as a registry name.
3152         //
parseAuthority(int start, int n)3153         private int parseAuthority(int start, int n)
3154             throws URISyntaxException
3155         {
3156             int p = start;
3157             int q = p;
3158             URISyntaxException ex = null;
3159 
3160             boolean serverChars;
3161             boolean regChars;
3162 
3163             if (scan(p, n, "", "]") > p) {
3164                 // contains a literal IPv6 address, therefore % is allowed
3165                 serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n);
3166             } else {
3167                 serverChars = (scan(p, n, L_SERVER, H_SERVER) == n);
3168             }
3169             regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n);
3170 
3171             if (regChars && !serverChars) {
3172                 // Must be a registry-based authority
3173                 authority = substring(p, n);
3174                 return n;
3175             }
3176 
3177             if (serverChars) {
3178                 // Might be (probably is) a server-based authority, so attempt
3179                 // to parse it as such.  If the attempt fails, try to treat it
3180                 // as a registry-based authority.
3181                 try {
3182                     q = parseServer(p, n);
3183                     if (q < n)
3184                         failExpecting("end of authority", q);
3185                     authority = substring(p, n);
3186                 } catch (URISyntaxException x) {
3187                     // Undo results of failed parse
3188                     userInfo = null;
3189                     host = null;
3190                     port = -1;
3191                     if (requireServerAuthority) {
3192                         // If we're insisting upon a server-based authority,
3193                         // then just re-throw the exception
3194                         throw x;
3195                     } else {
3196                         // Save the exception in case it doesn't parse as a
3197                         // registry either
3198                         ex = x;
3199                         q = p;
3200                     }
3201                 }
3202             }
3203 
3204             if (q < n) {
3205                 if (regChars) {
3206                     // Registry-based authority
3207                     authority = substring(p, n);
3208                 } else if (ex != null) {
3209                     // Re-throw exception; it was probably due to
3210                     // a malformed IPv6 address
3211                     throw ex;
3212                 } else {
3213                     fail("Illegal character in authority", q);
3214                 }
3215             }
3216 
3217             return n;
3218         }
3219 
3220 
3221         // [<userinfo>@]<host>[:<port>]
3222         //
parseServer(int start, int n)3223         private int parseServer(int start, int n)
3224             throws URISyntaxException
3225         {
3226             int p = start;
3227             int q;
3228 
3229             // userinfo
3230             q = scan(p, n, "/?#", "@");
3231             if ((q >= p) && at(q, n, '@')) {
3232                 checkChars(p, q, L_USERINFO, H_USERINFO, "user info");
3233                 userInfo = substring(p, q);
3234                 p = q + 1;              // Skip '@'
3235             }
3236 
3237             // hostname, IPv4 address, or IPv6 address
3238             if (at(p, n, '[')) {
3239                 // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732
3240                 p++;
3241                 q = scan(p, n, "/?#", "]");
3242                 if ((q > p) && at(q, n, ']')) {
3243                     // look for a "%" scope id
3244                     int r = scan (p, q, "", "%");
3245                     if (r > p) {
3246                         parseIPv6Reference(p, r);
3247                         if (r+1 == q) {
3248                             fail ("scope id expected");
3249                         }
3250                         checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM,
3251                                                 "scope id");
3252                     } else {
3253                         parseIPv6Reference(p, q);
3254                     }
3255                     host = substring(p-1, q+1);
3256                     p = q + 1;
3257                 } else {
3258                     failExpecting("closing bracket for IPv6 address", q);
3259                 }
3260             } else {
3261                 q = parseIPv4Address(p, n);
3262                 if (q <= p)
3263                     q = parseHostname(p, n);
3264                 p = q;
3265             }
3266 
3267             // port
3268             if (at(p, n, ':')) {
3269                 p++;
3270                 q = scan(p, n, "", "/");
3271                 if (q > p) {
3272                     checkChars(p, q, L_DIGIT, H_DIGIT, "port number");
3273                     try {
3274                         port = Integer.parseInt(substring(p, q));
3275                     } catch (NumberFormatException x) {
3276                         fail("Malformed port number", p);
3277                     }
3278                     p = q;
3279                 }
3280             }
3281             if (p < n)
3282                 failExpecting("port number", p);
3283 
3284             return p;
3285         }
3286 
3287         // Scan a string of decimal digits whose value fits in a byte
3288         //
scanByte(int start, int n)3289         private int scanByte(int start, int n)
3290             throws URISyntaxException
3291         {
3292             int p = start;
3293             int q = scan(p, n, L_DIGIT, H_DIGIT);
3294             if (q <= p) return q;
3295             if (Integer.parseInt(substring(p, q)) > 255) return p;
3296             return q;
3297         }
3298 
3299         // Scan an IPv4 address.
3300         //
3301         // If the strict argument is true then we require that the given
3302         // interval contain nothing besides an IPv4 address; if it is false
3303         // then we only require that it start with an IPv4 address.
3304         //
3305         // If the interval does not contain or start with (depending upon the
3306         // strict argument) a legal IPv4 address characters then we return -1
3307         // immediately; otherwise we insist that these characters parse as a
3308         // legal IPv4 address and throw an exception on failure.
3309         //
3310         // We assume that any string of decimal digits and dots must be an IPv4
3311         // address.  It won't parse as a hostname anyway, so making that
3312         // assumption here allows more meaningful exceptions to be thrown.
3313         //
scanIPv4Address(int start, int n, boolean strict)3314         private int scanIPv4Address(int start, int n, boolean strict)
3315             throws URISyntaxException
3316         {
3317             int p = start;
3318             int q;
3319             int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT);
3320             if ((m <= p) || (strict && (m != n)))
3321                 return -1;
3322             for (;;) {
3323                 // Per RFC2732: At most three digits per byte
3324                 // Further constraint: Each element fits in a byte
3325                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3326                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3327                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3328                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3329                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3330                 if ((q = scan(p, m, '.')) <= p) break;  p = q;
3331                 if ((q = scanByte(p, m)) <= p) break;   p = q;
3332                 if (q < m) break;
3333                 return q;
3334             }
3335             fail("Malformed IPv4 address", q);
3336             return -1;
3337         }
3338 
3339         // Take an IPv4 address: Throw an exception if the given interval
3340         // contains anything except an IPv4 address
3341         //
takeIPv4Address(int start, int n, String expected)3342         private int takeIPv4Address(int start, int n, String expected)
3343             throws URISyntaxException
3344         {
3345             int p = scanIPv4Address(start, n, true);
3346             if (p <= start)
3347                 failExpecting(expected, start);
3348             return p;
3349         }
3350 
3351         // Attempt to parse an IPv4 address, returning -1 on failure but
3352         // allowing the given interval to contain [:<characters>] after
3353         // the IPv4 address.
3354         //
parseIPv4Address(int start, int n)3355         private int parseIPv4Address(int start, int n) {
3356             int p;
3357 
3358             try {
3359                 p = scanIPv4Address(start, n, false);
3360             } catch (URISyntaxException x) {
3361                 return -1;
3362             } catch (NumberFormatException nfe) {
3363                 return -1;
3364             }
3365 
3366             if (p > start && p < n) {
3367                 // IPv4 address is followed by something - check that
3368                 // it's a ":" as this is the only valid character to
3369                 // follow an address.
3370                 if (charAt(p) != ':') {
3371                     p = -1;
3372                 }
3373             }
3374 
3375             if (p > start)
3376                 host = substring(start, p);
3377 
3378             return p;
3379         }
3380 
3381         // hostname      = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ]
3382         // domainlabel   = alphanum | alphanum *( alphanum | "-" | "_" ) alphanum
3383         // toplabel      = alpha | alpha *( alphanum | "-" | "_" ) alphanum
3384         //
parseHostname(int start, int n)3385         private int parseHostname(int start, int n)
3386             throws URISyntaxException
3387         {
3388             int p = start;
3389             int q;
3390             int l = -1;                 // Start of last parsed label
3391 
3392             do {
3393                 // domainlabel = alphanum [ *( alphanum | "-" | "_" ) alphanum ]
3394                 //
3395                 // The RFCs don't permit underscores in hostnames, but URI has to because a certain
3396                 // large website doesn't seem to care about standards and specs.
3397                 // http://code.google.com/p/android/issues/detail?id=37577
3398                 // http://b/17579865
3399                 // http://b/18016625
3400                 // http://b/18023709
3401                 q = scan(p, n, L_ALPHANUM, H_ALPHANUM);
3402                 if (q <= p)
3403                     break;
3404                 l = p;
3405                 if (q > p) {
3406                     p = q;
3407                     q = scan(p, n, L_ALPHANUM | L_DASH | L_UNDERSCORE, H_ALPHANUM | H_DASH | H_UNDERSCORE);
3408                     if (q > p) {
3409                         if (charAt(q - 1) == '-')
3410                             fail("Illegal character in hostname", q - 1);
3411                         p = q;
3412                     }
3413                 }
3414                 q = scan(p, n, '.');
3415                 if (q <= p)
3416                     break;
3417                 p = q;
3418             } while (p < n);
3419 
3420             if ((p < n) && !at(p, n, ':'))
3421                 fail("Illegal character in hostname", p);
3422 
3423             if (l < 0)
3424                 failExpecting("hostname", start);
3425 
3426             // for a fully qualified hostname check that the rightmost
3427             // label starts with an alpha character.
3428             if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) {
3429                 fail("Illegal character in hostname", l);
3430             }
3431 
3432             host = substring(start, p);
3433             return p;
3434         }
3435 
3436 
3437         // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture
3438         //
3439         // Bug: The grammar in RFC2373 Appendix B does not allow addresses of
3440         // the form ::12.34.56.78, which are clearly shown in the examples
3441         // earlier in the document.  Here is the original grammar:
3442         //
3443         //   IPv6address = hexpart [ ":" IPv4address ]
3444         //   hexpart     = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
3445         //   hexseq      = hex4 *( ":" hex4)
3446         //   hex4        = 1*4HEXDIG
3447         //
3448         // We therefore use the following revised grammar:
3449         //
3450         //   IPv6address = hexseq [ ":" IPv4address ]
3451         //                 | hexseq [ "::" [ hexpost ] ]
3452         //                 | "::" [ hexpost ]
3453         //   hexpost     = hexseq | hexseq ":" IPv4address | IPv4address
3454         //   hexseq      = hex4 *( ":" hex4)
3455         //   hex4        = 1*4HEXDIG
3456         //
3457         // This covers all and only the following cases:
3458         //
3459         //   hexseq
3460         //   hexseq : IPv4address
3461         //   hexseq ::
3462         //   hexseq :: hexseq
3463         //   hexseq :: hexseq : IPv4address
3464         //   hexseq :: IPv4address
3465         //   :: hexseq
3466         //   :: hexseq : IPv4address
3467         //   :: IPv4address
3468         //   ::
3469         //
3470         // Additionally we constrain the IPv6 address as follows :-
3471         //
3472         //  i.  IPv6 addresses without compressed zeros should contain
3473         //      exactly 16 bytes.
3474         //
3475         //  ii. IPv6 addresses with compressed zeros should contain
3476         //      less than 16 bytes.
3477 
3478         private int ipv6byteCount = 0;
3479 
parseIPv6Reference(int start, int n)3480         private int parseIPv6Reference(int start, int n)
3481             throws URISyntaxException
3482         {
3483             int p = start;
3484             int q;
3485             boolean compressedZeros = false;
3486 
3487             q = scanHexSeq(p, n);
3488 
3489             if (q > p) {
3490                 p = q;
3491                 if (at(p, n, "::")) {
3492                     compressedZeros = true;
3493                     p = scanHexPost(p + 2, n);
3494                 } else if (at(p, n, ':')) {
3495                     p = takeIPv4Address(p + 1,  n, "IPv4 address");
3496                     ipv6byteCount += 4;
3497                 }
3498             } else if (at(p, n, "::")) {
3499                 compressedZeros = true;
3500                 p = scanHexPost(p + 2, n);
3501             }
3502             if (p < n)
3503                 fail("Malformed IPv6 address", start);
3504             if (ipv6byteCount > 16)
3505                 fail("IPv6 address too long", start);
3506             if (!compressedZeros && ipv6byteCount < 16)
3507                 fail("IPv6 address too short", start);
3508             if (compressedZeros && ipv6byteCount == 16)
3509                 fail("Malformed IPv6 address", start);
3510 
3511             return p;
3512         }
3513 
scanHexPost(int start, int n)3514         private int scanHexPost(int start, int n)
3515             throws URISyntaxException
3516         {
3517             int p = start;
3518             int q;
3519 
3520             if (p == n)
3521                 return p;
3522 
3523             q = scanHexSeq(p, n);
3524             if (q > p) {
3525                 p = q;
3526                 if (at(p, n, ':')) {
3527                     p++;
3528                     p = takeIPv4Address(p, n, "hex digits or IPv4 address");
3529                     ipv6byteCount += 4;
3530                 }
3531             } else {
3532                 p = takeIPv4Address(p, n, "hex digits or IPv4 address");
3533                 ipv6byteCount += 4;
3534             }
3535             return p;
3536         }
3537 
3538         // Scan a hex sequence; return -1 if one could not be scanned
3539         //
scanHexSeq(int start, int n)3540         private int scanHexSeq(int start, int n)
3541             throws URISyntaxException
3542         {
3543             int p = start;
3544             int q;
3545 
3546             q = scan(p, n, L_HEX, H_HEX);
3547             if (q <= p)
3548                 return -1;
3549             if (at(q, n, '.'))          // Beginning of IPv4 address
3550                 return -1;
3551             if (q > p + 4)
3552                 fail("IPv6 hexadecimal digit sequence too long", p);
3553             ipv6byteCount += 2;
3554             p = q;
3555             while (p < n) {
3556                 if (!at(p, n, ':'))
3557                     break;
3558                 if (at(p + 1, n, ':'))
3559                     break;              // "::"
3560                 p++;
3561                 q = scan(p, n, L_HEX, H_HEX);
3562                 if (q <= p)
3563                     failExpecting("digits for an IPv6 address", p);
3564                 if (at(q, n, '.')) {    // Beginning of IPv4 address
3565                     p--;
3566                     break;
3567                 }
3568                 if (q > p + 4)
3569                     fail("IPv6 hexadecimal digit sequence too long", p);
3570                 ipv6byteCount += 2;
3571                 p = q;
3572             }
3573 
3574             return p;
3575         }
3576 
3577     }
3578 
3579 }
3580