KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > net > URI


1 /*
2  * @(#)URI.java 1.40 05/11/28
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.net;
9
10 import java.io.IOException JavaDoc;
11 import java.io.InvalidObjectException JavaDoc;
12 import java.io.ObjectInputStream JavaDoc;
13 import java.io.ObjectOutputStream JavaDoc;
14 import java.io.Serializable JavaDoc;
15 import java.nio.ByteBuffer JavaDoc;
16 import java.nio.CharBuffer JavaDoc;
17 import java.nio.charset.CharsetDecoder JavaDoc;
18 import java.nio.charset.CharsetEncoder JavaDoc;
19 import java.nio.charset.CoderResult JavaDoc;
20 import java.nio.charset.CodingErrorAction JavaDoc;
21 import java.nio.charset.CharacterCodingException JavaDoc;
22 import sun.nio.cs.ThreadLocalCoders;
23 import sun.text.Normalizer;
24
25 import java.lang.Character JavaDoc; // for javadoc
26
import java.lang.NullPointerException JavaDoc; // for javadoc
27

28
29 /**
30  * Represents a Uniform Resource Identifier (URI) reference.
31  *
32  * <p> Aside from some minor deviations noted below, an instance of this
33  * class represents a URI reference as defined by
34  * <a HREF="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC&nbsp;2396: Uniform
35  * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
36  * HREF="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
37  * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
38  * also supports scope_ids. The syntax and usage of scope_ids is described
39  * <a HREF="Inet6Address.html#scoped">here</a>.
40  * This class provides constructors for creating URI instances from
41  * their components or by parsing their string forms, methods for accessing the
42  * various components of an instance, and methods for normalizing, resolving,
43  * and relativizing URI instances. Instances of this class are immutable.
44  *
45  *
46  * <h4> URI syntax and components </h4>
47  *
48  * At the highest level a URI reference (hereinafter simply "URI") in string
49  * form has the syntax
50  *
51  * <blockquote>
52  * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
53  * </blockquote>
54  *
55  * where square brackets [...] delineate optional components and the characters
56  * <tt><b>:</b></tt> and <tt><b>#</b></tt> stand for themselves.
57  *
58  * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is
59  * said to be <i>relative</i>. URIs are also classified according to whether
60  * they are <i>opaque</i> or <i>hierarchical</i>.
61  *
62  * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does
63  * not begin with a slash character (<tt>'/'</tt>). Opaque URIs are not
64  * subject to further parsing. Some examples of opaque URIs are:
65  *
66  * <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
67  * <tr><td><tt>mailto:java-net@java.sun.com</tt><td></tr>
68  * <tr><td><tt>news:comp.lang.java</tt><td></tr>
69  * <tr><td><tt>urn:isbn:096139210x</tt></td></tr>
70  * </table></blockquote>
71  *
72  * <p> A <i>hierarchical</i> URI is either an absolute URI whose
73  * scheme-specific part begins with a slash character, or a relative URI, that
74  * is, a URI that does not specify a scheme. Some examples of hierarchical
75  * URIs are:
76  *
77  * <blockquote>
78  * <tt>http://java.sun.com/j2se/1.3/</tt><br>
79  * <tt>docs/guide/collections/designfaq.html#28</tt><br>
80  * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java</tt><br>
81  * <tt>file:///~/calendar</tt>
82  * </blockquote>
83  *
84  * <p> A hierarchical URI is subject to further parsing according to the syntax
85  *
86  * <blockquote>
87  * [<i>scheme</i><tt><b>:</b></tt>][<tt><b>//</b></tt><i>authority</i>][<i>path</i>][<tt><b>?</b></tt><i>query</i>][<tt><b>#</b></tt><i>fragment</i>]
88  * </blockquote>
89  *
90  * where the characters <tt><b>:</b></tt>, <tt><b>/</b></tt>,
91  * <tt><b>?</b></tt>, and <tt><b>#</b></tt> stand for themselves. The
92  * scheme-specific part of a hierarchical URI consists of the characters
93  * between the scheme and fragment components.
94  *
95  * <p> The authority component of a hierarchical URI is, if specified, either
96  * <i>server-based</i> or <i>registry-based</i>. A server-based authority
97  * parses according to the familiar syntax
98  *
99  * <blockquote>
100  * [<i>user-info</i><tt><b>@</b></tt>]<i>host</i>[<tt><b>:</b></tt><i>port</i>]
101  * </blockquote>
102  *
103  * where the characters <tt><b>@</b></tt> and <tt><b>:</b></tt> stand for
104  * themselves. Nearly all URI schemes currently in use are server-based. An
105  * authority component that does not parse in this way is considered to be
106  * registry-based.
107  *
108  * <p> The path component of a hierarchical URI is itself said to be absolute
109  * if it begins with a slash character (<tt>'/'</tt>); otherwise it is
110  * relative. The path of a hierarchical URI that is either absolute or
111  * specifies an authority is always absolute.
112  *
113  * <p> All told, then, a URI instance has the following nine components:
114  *
115  * <blockquote><table summary="Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment">
116  * <tr><th><i>Component</i></th><th><i>Type</i></th></tr>
117  * <tr><td>scheme</td><td><tt>String</tt></td></tr>
118  * <tr><td>scheme-specific-part&nbsp;&nbsp;&nbsp;&nbsp;</td><td><tt>String</tt></td></tr>
119  * <tr><td>authority</td><td><tt>String</tt></td></tr>
120  * <tr><td>user-info</td><td><tt>String</tt></td></tr>
121  * <tr><td>host</td><td><tt>String</tt></td></tr>
122  * <tr><td>port</td><td><tt>int</tt></td></tr>
123  * <tr><td>path</td><td><tt>String</tt></td></tr>
124  * <tr><td>query</td><td><tt>String</tt></td></tr>
125  * <tr><td>fragment</td><td><tt>String</tt></td></tr>
126  * </table></blockquote>
127  *
128  * In a given instance any particular component is either <i>undefined</i> or
129  * <i>defined</i> with a distinct value. Undefined string components are
130  * represented by <tt>null</tt>, while undefined integer components are
131  * represented by <tt>-1</tt>. A string component may be defined to have the
132  * empty string as its value; this is not equivalent to that component being
133  * undefined.
134  *
135  * <p> Whether a particular component is or is not defined in an instance
136  * depends upon the type of the URI being represented. An absolute URI has a
137  * scheme component. An opaque URI has a scheme, a scheme-specific part, and
138  * possibly a fragment, but has no other components. A hierarchical URI always
139  * has a path (though it may be empty) and a scheme-specific-part (which at
140  * least contains the path), and may have any of the other components. If the
141  * authority component is present and is server-based then the host component
142  * will be defined and the user-information and port components may be defined.
143  *
144  *
145  * <h4> Operations on URI instances </h4>
146  *
147  * The key operations supported by this class are those of
148  * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>.
149  *
150  * <p> <i>Normalization</i> is the process of removing unnecessary <tt>"."</tt>
151  * and <tt>".."</tt> segments from the path component of a hierarchical URI.
152  * Each <tt>"."</tt> segment is simply removed. A <tt>".."</tt> segment is
153  * removed only if it is preceded by a non-<tt>".."</tt> segment.
154  * Normalization has no effect upon opaque URIs.
155  *
156  * <p> <i>Resolution</i> is the process of resolving one URI against another,
157  * <i>base</i> URI. The resulting URI is constructed from components of both
158  * URIs in the manner specified by RFC&nbsp;2396, taking components from the
159  * base URI for those not specified in the original. For hierarchical URIs,
160  * the path of the original is resolved against the path of the base and then
161  * normalized. The result, for example, of resolving
162  *
163  * <blockquote>
164  * <tt>docs/guide/collections/designfaq.html#28&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt>(1)
165  * </blockquote>
166  *
167  * against the base URI <tt>http://java.sun.com/j2se/1.3/</tt> is the result
168  * URI
169  *
170  * <blockquote>
171  * <tt>http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28</tt>
172  * </blockquote>
173  *
174  * Resolving the relative URI
175  *
176  * <blockquote>
177  * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java&nbsp;&nbsp;&nbsp;&nbsp;</tt>(2)
178  * </blockquote>
179  *
180  * against this result yields, in turn,
181  *
182  * <blockquote>
183  * <tt>http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java</tt>
184  * </blockquote>
185  *
186  * Resolution of both absolute and relative URIs, and of both absolute and
187  * relative paths in the case of hierarchical URIs, is supported. Resolving
188  * the URI <tt>file:///~calendar</tt> against any other URI simply yields the
189  * original URI, since it is absolute. Resolving the relative URI (2) above
190  * against the relative base URI (1) yields the normalized, but still relative,
191  * URI
192  *
193  * <blockquote>
194  * <tt>demo/jfc/SwingSet2/src/SwingSet2.java</tt>
195  * </blockquote>
196  *
197  * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any
198  * two normalized URIs <i>u</i> and&nbsp;<i>v</i>,
199  *
200  * <blockquote>
201  * <i>u</i><tt>.relativize(</tt><i>u</i><tt>.resolve(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;and<br>
202  * <i>u</i><tt>.resolve(</tt><i>u</i><tt>.relativize(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;.<br>
203  * </blockquote>
204  *
205  * This operation is often useful when constructing a document containing URIs
206  * that must be made relative to the base URI of the document wherever
207  * possible. For example, relativizing the URI
208  *
209  * <blockquote>
210  * <tt>http://java.sun.com/j2se/1.3/docs/guide/index.html</tt>
211  * </blockquote>
212  *
213  * against the base URI
214  *
215  * <blockquote>
216  * <tt>http://java.sun.com/j2se/1.3</tt>
217  * </blockquote>
218  *
219  * yields the relative URI <tt>docs/guide/index.html</tt>.
220  *
221  *
222  * <h4> Character categories </h4>
223  *
224  * RFC&nbsp;2396 specifies precisely which characters are permitted in the
225  * various components of a URI reference. The following categories, most of
226  * which are taken from that specification, are used below to describe these
227  * constraints:
228  *
229  * <blockquote><table cellspacing=2 summary="Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other">
230  * <tr><th valign=top><i>alpha</i></th>
231  * <td>The US-ASCII alphabetic characters,
232  * <tt>'A'</tt>&nbsp;through&nbsp;<tt>'Z'</tt>
233  * and <tt>'a'</tt>&nbsp;through&nbsp;<tt>'z'</tt></td></tr>
234  * <tr><th valign=top><i>digit</i></th>
235  * <td>The US-ASCII decimal digit characters,
236  * <tt>'0'</tt>&nbsp;through&nbsp;<tt>'9'</tt></td></tr>
237  * <tr><th valign=top><i>alphanum</i></th>
238  * <td>All <i>alpha</i> and <i>digit</i> characters</td></tr>
239  * <tr><th valign=top><i>unreserved</i>&nbsp;&nbsp;&nbsp;&nbsp;</th>
240  * <td>All <i>alphanum</i> characters together with those in the string
241  * <tt>"_-!.~'()*"</tt></td></tr>
242  * <tr><th valign=top><i>punct</i></th>
243  * <td>The characters in the string <tt>",;:$&+="</tt></td></tr>
244  * <tr><th valign=top><i>reserved</i></th>
245  * <td>All <i>punct</i> characters together with those in the string
246  * <tt>"?/[]@"</tt></td></tr>
247  * <tr><th valign=top><i>escaped</i></th>
248  * <td>Escaped octets, that is, triplets consisting of the percent
249  * character (<tt>'%'</tt>) followed by two hexadecimal digits
250  * (<tt>'0'</tt>-<tt>'9'</tt>, <tt>'A'</tt>-<tt>'F'</tt>, and
251  * <tt>'a'</tt>-<tt>'f'</tt>)</td></tr>
252  * <tr><th valign=top><i>other</i></th>
253  * <td>The Unicode characters that are not in the US-ASCII character set,
254  * are not control characters (according to the {@link
255  * java.lang.Character#isISOControl(char) Character.isISOControl}
256  * method), and are not space characters (according to the {@link
257  * java.lang.Character#isSpaceChar(char) Character.isSpaceChar}
258  * method)&nbsp;&nbsp;<i>(<b>Deviation from RFC 2396</b>, which is
259  * limited to US-ASCII)</i></td></tr>
260  * </table></blockquote>
261  *
262  * <p><a name="legal-chars"></a> The set of all legal URI characters consists of
263  * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i>
264  * characters.
265  *
266  *
267  * <h4> Escaped octets, quotation, encoding, and decoding </h4>
268  *
269  * RFC 2396 allows escaped octets to appear in the user-info, path, query, and
270  * fragment components. Escaping serves two purposes in URIs:
271  *
272  * <ul>
273  *
274  * <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to
275  * conform strictly to RFC&nbsp;2396 by not containing any <i>other</i>
276  * characters. </p></li>
277  *
278  * <li><p> To <i>quote</i> characters that are otherwise illegal in a
279  * component. The user-info, path, query, and fragment components differ
280  * slightly in terms of which characters are considered legal and illegal.
281  * </p></li>
282  *
283  * </ul>
284  *
285  * These purposes are served in this class by three related operations:
286  *
287  * <ul>
288  *
289  * <li><p><a name="encode"></a> A character is <i>encoded</i> by replacing it
290  * with the sequence of escaped octets that represent that character in the
291  * UTF-8 character set. The Euro currency symbol (<tt>'&#92;u20AC'</tt>),
292  * for example, is encoded as <tt>"%E2%82%AC"</tt>. <i>(<b>Deviation from
293  * RFC&nbsp;2396</b>, which does not specify any particular character
294  * set.)</i> </p></li>
295  *
296  * <li><p><a name="quote"></a> An illegal character is <i>quoted</i> simply by
297  * encoding it. The space character, for example, is quoted by replacing it
298  * with <tt>"%20"</tt>. UTF-8 contains US-ASCII, hence for US-ASCII
299  * characters this transformation has exactly the effect required by
300  * RFC&nbsp;2396. </p></li>
301  *
302  * <li><p><a name="decode"></a>
303  * A sequence of escaped octets is <i>decoded</i> by
304  * replacing it with the sequence of characters that it represents in the
305  * UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the
306  * effect of de-quoting any quoted US-ASCII characters as well as that of
307  * decoding any encoded non-US-ASCII characters. If a <a
308  * HREF="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs
309  * when decoding the escaped octets then the erroneous octets are replaced by
310  * <tt>'&#92;uFFFD'</tt>, the Unicode replacement character. </p></li>
311  *
312  * </ul>
313  *
314  * These operations are exposed in the constructors and methods of this class
315  * as follows:
316  *
317  * <ul>
318  *
319  * <li><p> The {@link #URI(java.lang.String) <code>single-argument
320  * constructor</code>} requires any illegal characters in its argument to be
321  * quoted and preserves any escaped octets and <i>other</i> characters that
322  * are present. </p></li>
323  *
324  * <li><p> The {@link
325  * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
326  * <code>multi-argument constructors</code>} quote illegal characters as
327  * required by the components in which they appear. The percent character
328  * (<tt>'%'</tt>) is always quoted by these constructors. Any <i>other</i>
329  * characters are preserved. </p></li>
330  *
331  * <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath()
332  * getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment()
333  * getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link
334  * #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the
335  * values of their corresponding components in raw form, without interpreting
336  * any escaped octets. The strings returned by these methods may contain
337  * both escaped octets and <i>other</i> characters, and will not contain any
338  * illegal characters. </p></li>
339  *
340  * <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath()
341  * getPath}, {@link #getQuery() getQuery}, {@link #getFragment()
342  * getFragment}, {@link #getAuthority() getAuthority}, and {@link
343  * #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped
344  * octets in their corresponding components. The strings returned by these
345  * methods may contain both <i>other</i> characters and illegal characters,
346  * and will not contain any escaped octets. </p></li>
347  *
348  * <li><p> The {@link #toString() toString} method returns a URI string with
349  * all necessary quotation but which may contain <i>other</i> characters.
350  * </p></li>
351  *
352  * <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully
353  * quoted and encoded URI string that does not contain any <i>other</i>
354  * characters. </p></li>
355  *
356  * </ul>
357  *
358  *
359  * <h4> Identities </h4>
360  *
361  * For any URI <i>u</i>, it is always the case that
362  *
363  * <blockquote>
364  * <tt>new URI(</tt><i>u</i><tt>.toString()).equals(</tt><i>u</i><tt>)</tt>&nbsp;.
365  * </blockquote>
366  *
367  * For any URI <i>u</i> that does not contain redundant syntax such as two
368  * slashes before an empty authority (as in <tt>file:///tmp/</tt>&nbsp;) or a
369  * colon following a host name but no port (as in
370  * <tt>http://java.sun.com:</tt>&nbsp;), and that does not encode characters
371  * except those that must be quoted, the following identities also hold:
372  *
373  * <blockquote>
374  * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
375  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getSchemeSpecificPart(),<br>
376  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
377  * .equals(</tt><i>u</i><tt>)</tt>
378  * </blockquote>
379  *
380  * in all cases,
381  *
382  * <blockquote>
383  * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
384  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getAuthority(),<br>
385  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
386  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
387  * .equals(</tt><i>u</i><tt>)</tt>
388  * </blockquote>
389  *
390  * if <i>u</i> is hierarchical, and
391  *
392  * <blockquote>
393  * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
394  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getHost(),&nbsp;</tt><i>u</i><tt>.getPort(),<br>
395  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
396  * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
397  * .equals(</tt><i>u</i><tt>)</tt>
398  * </blockquote>
399  *
400  * if <i>u</i> is hierarchical and has either no authority or a server-based
401  * authority.
402  *
403  *
404  * <h4> URIs, URLs, and URNs </h4>
405  *
406  * A URI is a uniform resource <i>identifier</i> while a URL is a uniform
407  * resource <i>locator</i>. Hence every URL is a URI, abstractly speaking, but
408  * not every URI is a URL. This is because there is another subcategory of
409  * URIs, uniform resource <i>names</i> (URNs), which name resources but do not
410  * specify how to locate them. The <tt>mailto</tt>, <tt>news</tt>, and
411  * <tt>isbn</tt> URIs shown above are examples of URNs.
412  *
413  * <p> The conceptual distinction between URIs and URLs is reflected in the
414  * differences between this class and the {@link URL} class.
415  *
416  * <p> An instance of this class represents a URI reference in the syntactic
417  * sense defined by RFC&nbsp;2396. A URI may be either absolute or relative.
418  * A URI string is parsed according to the generic syntax without regard to the
419  * scheme, if any, that it specifies. No lookup of the host, if any, is
420  * performed, and no scheme-dependent stream handler is constructed. Equality,
421  * hashing, and comparison are defined strictly in terms of the character
422  * content of the instance. In other words, a URI instance is little more than
423  * a structured string that supports the syntactic, scheme-independent
424  * operations of comparison, normalization, resolution, and relativization.
425  *
426  * <p> An instance of the {@link URL} class, by contrast, represents the
427  * syntactic components of a URL together with some of the information required
428  * to access the resource that it describes. A URL must be absolute, that is,
429  * it must always specify a scheme. A URL string is parsed according to its
430  * scheme. A stream handler is always established for a URL, and in fact it is
431  * impossible to create a URL instance for a scheme for which no handler is
432  * available. Equality and hashing depend upon both the scheme and the
433  * Internet address of the host, if any; comparison is not defined. In other
434  * words, a URL is a structured string that supports the syntactic operation of
435  * resolution as well as the network I/O operations of looking up the host and
436  * opening a connection to the specified resource.
437  *
438  *
439  * @version 1.40, 05/11/28
440  * @author Mark Reinhold
441  * @since 1.4
442  *
443  * @see <a HREF="http://ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279: UTF-8, a
444  * transformation format of ISO 10646</i></a>, <br><a
445  * HREF="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6 Addressing
446  * Architecture</i></a>, <br><a
447  * HREF="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC&nbsp;2396: Uniform
448  * Resource Identifiers (URI): Generic Syntax</i></a>, <br><a
449  * HREF="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
450  * Literal IPv6 Addresses in URLs</i></a>, <br><a
451  * HREF="URISyntaxException.html">URISyntaxException</a>
452  */

453
454 public final class URI
455     implements Comparable JavaDoc<URI JavaDoc>, Serializable JavaDoc
456 {
457
458     // Note: Comments containing the word "ASSERT" indicate places where a
459
// throw of an InternalError should be replaced by an appropriate assertion
460
// statement once asserts are enabled in the build.
461

462     static final long serialVersionUID = -6052424284110960213L;
463
464
465     // -- Properties and components of this instance --
466

467     // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
468
private transient String JavaDoc scheme; // null ==> relative URI
469
private transient String JavaDoc fragment;
470
471     // Hierarchical URI components: [//<authority>]<path>[?<query>]
472
private transient String JavaDoc authority; // Registry or server
473

474     // Server-based authority: [<userInfo>@]<host>[:<port>]
475
private transient String JavaDoc userInfo;
476     private transient String JavaDoc host; // null ==> registry-based
477
private transient int port = -1; // -1 ==> undefined
478

479     // Remaining components of hierarchical URIs
480
private transient String JavaDoc path; // null ==> opaque
481
private transient String JavaDoc query;
482
483     // The remaining fields may be computed on demand
484

485     private volatile transient String JavaDoc schemeSpecificPart;
486     private volatile transient int hash; // Zero ==> undefined
487

488     private volatile transient String JavaDoc decodedUserInfo = null;
489     private volatile transient String JavaDoc decodedAuthority = null;
490     private volatile transient String JavaDoc decodedPath = null;
491     private volatile transient String JavaDoc decodedQuery = null;
492     private volatile transient String JavaDoc decodedFragment = null;
493     private volatile transient String JavaDoc decodedSchemeSpecificPart = null;
494
495     /**
496      * The string form of this URI.
497      *
498      * @serial
499      */

500     private volatile String JavaDoc string; // The only serializable field
501

502
503
504     // -- Constructors and factories --
505

506     private URI() { } // Used internally
507

508     /**
509      * Constructs a URI by parsing the given string.
510      *
511      * <p> This constructor parses the given string exactly as specified by the
512      * grammar in <a
513      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
514      * Appendix&nbsp;A, <b><i>except for the following deviations:</i></b> </p>
515      *
516      * <ul type=disc>
517      *
518      * <li><p> An empty authority component is permitted as long as it is
519      * followed by a non-empty path, a query component, or a fragment
520      * component. This allows the parsing of URIs such as
521      * <tt>"file:///foo/bar"</tt>, which seems to be the intent of
522      * RFC&nbsp;2396 although the grammar does not permit it. If the
523      * authority component is empty then the user-information, host, and port
524      * components are undefined. </p></li>
525      *
526      * <li><p> Empty relative paths are permitted; this seems to be the
527      * intent of RFC&nbsp;2396 although the grammar does not permit it. The
528      * primary consequence of this deviation is that a standalone fragment
529      * such as <tt>"#foo"</tt> parses as a relative URI with an empty path
530      * and the given fragment, and can be usefully <a
531      * HREF="#resolve-frag">resolved</a> against a base URI.
532      *
533      * <li><p> IPv4 addresses in host components are parsed rigorously, as
534      * specified by <a
535      * HREF="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>: Each
536      * element of a dotted-quad address must contain no more than three
537      * decimal digits. Each element is further constrained to have a value
538      * no greater than 255. </p></li>
539      *
540      * <li> <p> Hostnames in host components that comprise only a single
541      * domain label are permitted to start with an <i>alphanum</i>
542      * character. This seems to be the intent of <a
543      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
544      * section&nbsp;3.2.2 although the grammar does not permit it. The
545      * consequence of this deviation is that the authority component of a
546      * hierarchical URI such as <tt>s://123</tt>, will parse as a server-based
547      * authority. </p></li>
548      *
549      * <li><p> IPv6 addresses are permitted for the host component. An IPv6
550      * address must be enclosed in square brackets (<tt>'['</tt> and
551      * <tt>']'</tt>) as specified by <a
552      * HREF="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>. The
553      * IPv6 address itself must parse according to <a
554      * HREF="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>. IPv6
555      * addresses are further constrained to describe no more than sixteen
556      * bytes of address information, a constraint implicit in RFC&nbsp;2373
557      * but not expressible in the grammar. </p></li>
558      *
559      * <li><p> Characters in the <i>other</i> category are permitted wherever
560      * RFC&nbsp;2396 permits <i>escaped</i> octets, that is, in the
561      * user-information, path, query, and fragment components, as well as in
562      * the authority component if the authority is registry-based. This
563      * allows URIs to contain Unicode characters beyond those in the US-ASCII
564      * character set. </p></li>
565      *
566      * </ul>
567      *
568      * @param str The string to be parsed into a URI
569      *
570      * @throws NullPointerException
571      * If <tt>str</tt> is <tt>null</tt>
572      *
573      * @throws URISyntaxException
574      * If the given string violates RFC&nbsp;2396, as augmented
575      * by the above deviations
576      */

577     public URI(String JavaDoc str) throws URISyntaxException JavaDoc {
578     new Parser(str).parse(false);
579     }
580
581     /**
582      * Constructs a hierarchical URI from the given components.
583      *
584      * <p> If a scheme is given then the path, if also given, must either be
585      * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
586      * component of the new URI may be left undefined by passing <tt>null</tt>
587      * for the corresponding parameter or, in the case of the <tt>port</tt>
588      * parameter, by passing <tt>-1</tt>.
589      *
590      * <p> This constructor first builds a URI string from the given components
591      * according to the rules specified in <a
592      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
593      * section&nbsp;5.2, step&nbsp;7: </p>
594      *
595      * <ol>
596      *
597      * <li><p> Initially, the result string is empty. </p></li>
598      *
599      * <li><p> If a scheme is given then it is appended to the result,
600      * followed by a colon character (<tt>':'</tt>). </p></li>
601      *
602      * <li><p> If user information, a host, or a port are given then the
603      * string <tt>"//"</tt> is appended. </p></li>
604      *
605      * <li><p> If user information is given then it is appended, followed by
606      * a commercial-at character (<tt>'@'</tt>). Any character not in the
607      * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
608      * categories is <a HREF="#quote">quoted</a>. </p></li>
609      *
610      * <li><p> If a host is given then it is appended. If the host is a
611      * literal IPv6 address but is not enclosed in square brackets
612      * (<tt>'['</tt> and <tt>']'</tt>) then the square brackets are added.
613      * </p></li>
614      *
615      * <li><p> If a port number is given then a colon character
616      * (<tt>':'</tt>) is appended, followed by the port number in decimal.
617      * </p></li>
618      *
619      * <li><p> If a path is given then it is appended. Any character not in
620      * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
621      * categories, and not equal to the slash character (<tt>'/'</tt>) or the
622      * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
623      *
624      * <li><p> If a query is given then a question-mark character
625      * (<tt>'?'</tt>) is appended, followed by the query. Any character that
626      * is not a <a HREF="#legal-chars">legal URI character</a> is quoted.
627      * </p></li>
628      *
629      * <li><p> Finally, if a fragment is given then a hash character
630      * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
631      * that is not a legal URI character is quoted. </p></li>
632      *
633      * </ol>
634      *
635      * <p> The resulting URI string is then parsed as if by invoking the {@link
636      * #URI(String)} constructor and then invoking the {@link
637      * #parseServerAuthority()} method upon the result; this may cause a {@link
638      * URISyntaxException} to be thrown. </p>
639      *
640      * @param scheme Scheme name
641      * @param userInfo User name and authorization information
642      * @param host Host name
643      * @param port Port number
644      * @param path Path
645      * @param query Query
646      * @param fragment Fragment
647      *
648      * @throws URISyntaxException
649      * If both a scheme and a path are given but the path is relative,
650      * if the URI string constructed from the given components violates
651      * RFC&nbsp;2396, or if the authority component of the string is
652      * present but cannot be parsed as a server-based authority
653      */

654     public URI(String JavaDoc scheme,
655                String JavaDoc userInfo, String JavaDoc host, int port,
656                String JavaDoc path, String JavaDoc query, String JavaDoc fragment)
657     throws URISyntaxException JavaDoc
658     {
659     String JavaDoc s = toString(scheme, null,
660                 null, userInfo, host, port,
661                 path, query, fragment);
662     checkPath(s, scheme, path);
663     new Parser(s).parse(true);
664     }
665
666     /**
667      * Constructs a hierarchical URI from the given components.
668      *
669      * <p> If a scheme is given then the path, if also given, must either be
670      * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
671      * component of the new URI may be left undefined by passing <tt>null</tt>
672      * for the corresponding parameter.
673      *
674      * <p> This constructor first builds a URI string from the given components
675      * according to the rules specified in <a
676      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
677      * section&nbsp;5.2, step&nbsp;7: </p>
678      *
679      * <ol>
680      *
681      * <li><p> Initially, the result string is empty. </p></li>
682      *
683      * <li><p> If a scheme is given then it is appended to the result,
684      * followed by a colon character (<tt>':'</tt>). </p></li>
685      *
686      * <li><p> If an authority is given then the string <tt>"//"</tt> is
687      * appended, followed by the authority. If the authority contains a
688      * literal IPv6 address then the address must be enclosed in square
689      * brackets (<tt>'['</tt> and <tt>']'</tt>). Any character not in the
690      * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
691      * categories, and not equal to the commercial-at character
692      * (<tt>'@'</tt>), is <a HREF="#quote">quoted</a>. </p></li>
693      *
694      * <li><p> If a path is given then it is appended. Any character not in
695      * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
696      * categories, and not equal to the slash character (<tt>'/'</tt>) or the
697      * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
698      *
699      * <li><p> If a query is given then a question-mark character
700      * (<tt>'?'</tt>) is appended, followed by the query. Any character that
701      * is not a <a HREF="#legal-chars">legal URI character</a> is quoted.
702      * </p></li>
703      *
704      * <li><p> Finally, if a fragment is given then a hash character
705      * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
706      * that is not a legal URI character is quoted. </p></li>
707      *
708      * </ol>
709      *
710      * <p> The resulting URI string is then parsed as if by invoking the {@link
711      * #URI(String)} constructor and then invoking the {@link
712      * #parseServerAuthority()} method upon the result; this may cause a {@link
713      * URISyntaxException} to be thrown. </p>
714      *
715      * @param scheme Scheme name
716      * @param authority Authority
717      * @param path Path
718      * @param query Query
719      * @param fragment Fragment
720      *
721      * @throws URISyntaxException
722      * If both a scheme and a path are given but the path is relative,
723      * if the URI string constructed from the given components violates
724      * RFC&nbsp;2396, or if the authority component of the string is
725      * present but cannot be parsed as a server-based authority
726      */

727     public URI(String JavaDoc scheme,
728            String JavaDoc authority,
729            String JavaDoc path, String JavaDoc query, String JavaDoc fragment)
730     throws URISyntaxException JavaDoc
731     {
732     String JavaDoc s = toString(scheme, null,
733                 authority, null, null, -1,
734                 path, query, fragment);
735     checkPath(s, scheme, path);
736     new Parser(s).parse(false);
737     }
738
739     /**
740      * Constructs a hierarchical URI from the given components.
741      *
742      * <p> A component may be left undefined by passing <tt>null</tt>.
743      *
744      * <p> This convenience constructor works as if by invoking the
745      * seven-argument constructor as follows:
746      *
747      * <blockquote><tt>
748      * new&nbsp;{@link #URI(String, String, String, int, String, String, String)
749      * URI}(scheme,&nbsp;null,&nbsp;host,&nbsp;-1,&nbsp;path,&nbsp;null,&nbsp;fragment);
750      * </tt></blockquote>
751      *
752      * @param scheme Scheme name
753      * @param host Host name
754      * @param path Path
755      * @param fragment Fragment
756      *
757      * @throws URISyntaxException
758      * If the URI string constructed from the given components
759      * violates RFC&nbsp;2396
760      */

761     public URI(String JavaDoc scheme, String JavaDoc host, String JavaDoc path, String JavaDoc fragment)
762     throws URISyntaxException JavaDoc
763     {
764     this(scheme, null, host, -1, path, null, fragment);
765     }
766
767     /**
768      * Constructs a URI from the given components.
769      *
770      * <p> A component may be left undefined by passing <tt>null</tt>.
771      *
772      * <p> This constructor first builds a URI in string form using the given
773      * components as follows: </p>
774      *
775      * <ol>
776      *
777      * <li><p> Initially, the result string is empty. </p></li>
778      *
779      * <li><p> If a scheme is given then it is appended to the result,
780      * followed by a colon character (<tt>':'</tt>). </p></li>
781      *
782      * <li><p> If a scheme-specific part is given then it is appended. Any
783      * character that is not a <a HREF="#legal-chars">legal URI character</a>
784      * is <a HREF="#quote">quoted</a>. </p></li>
785      *
786      * <li><p> Finally, if a fragment is given then a hash character
787      * (<tt>'#'</tt>) is appended to the string, followed by the fragment.
788      * Any character that is not a legal URI character is quoted. </p></li>
789      *
790      * </ol>
791      *
792      * <p> The resulting URI string is then parsed in order to create the new
793      * URI instance as if by invoking the {@link #URI(String)} constructor;
794      * this may cause a {@link URISyntaxException} to be thrown. </p>
795      *
796      * @param scheme Scheme name
797      * @param ssp Scheme-specific part
798      * @param fragment Fragment
799      *
800      * @throws URISyntaxException
801      * If the URI string constructed from the given components
802      * violates RFC&nbsp;2396
803      */

804     public URI(String JavaDoc scheme, String JavaDoc ssp, String JavaDoc fragment)
805     throws URISyntaxException JavaDoc
806     {
807     new Parser(toString(scheme, ssp,
808                 null, null, null, -1,
809                 null, null, fragment))
810         .parse(false);
811     }
812
813     /**
814      * Creates a URI by parsing the given string.
815      *
816      * <p> This convenience factory method works as if by invoking the {@link
817      * #URI(String)} constructor; any {@link URISyntaxException} thrown by the
818      * constructor is caught and wrapped in a new {@link
819      * IllegalArgumentException} object, which is then thrown.
820      *
821      * <p> This method is provided for use in situations where it is known that
822      * the given string is a legal URI, for example for URI constants declared
823      * within in a program, and so it would be considered a programming error
824      * for the string not to parse as such. The constructors, which throw
825      * {@link URISyntaxException} directly, should be used situations where a
826      * URI is being constructed from user input or from some other source that
827      * may be prone to errors. </p>
828      *
829      * @param str The string to be parsed into a URI
830      * @return The new URI
831      *
832      * @throws NullPointerException
833      * If <tt>str</tt> is <tt>null</tt>
834      *
835      * @throws IllegalArgumentException
836      * If the given string violates RFC&nbsp;2396
837      */

838     public static URI JavaDoc create(String JavaDoc str) {
839     try {
840         return new URI JavaDoc(str);
841     } catch (URISyntaxException JavaDoc x) {
842         IllegalArgumentException JavaDoc y = new IllegalArgumentException JavaDoc();
843         y.initCause(x);
844         throw y;
845     }
846     }
847
848
849     // -- Operations --
850

851     /**
852      * Attempts to parse this URI's authority component, if defined, into
853      * user-information, host, and port components.
854      *
855      * <p> If this URI's authority component has already been recognized as
856      * being server-based then it will already have been parsed into
857      * user-information, host, and port components. In this case, or if this
858      * URI has no authority component, this method simply returns this URI.
859      *
860      * <p> Otherwise this method attempts once more to parse the authority
861      * component into user-information, host, and port components, and throws
862      * an exception describing why the authority component could not be parsed
863      * in that way.
864      *
865      * <p> This method is provided because the generic URI syntax specified in
866      * <a HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
867      * cannot always distinguish a malformed server-based authority from a
868      * legitimate registry-based authority. It must therefore treat some
869      * instances of the former as instances of the latter. The authority
870      * component in the URI string <tt>"//foo:bar"</tt>, for example, is not a
871      * legal server-based authority but it is legal as a registry-based
872      * authority.
873      *
874      * <p> In many common situations, for example when working URIs that are
875      * known to be either URNs or URLs, the hierarchical URIs being used will
876      * always be server-based. They therefore must either be parsed as such or
877      * treated as an error. In these cases a statement such as
878      *
879      * <blockquote>
880      * <tt>URI </tt><i>u</i><tt> = new URI(str).parseServerAuthority();</tt>
881      * </blockquote>
882      *
883      * <p> can be used to ensure that <i>u</i> always refers to a URI that, if
884      * it has an authority component, has a server-based authority with proper
885      * user-information, host, and port components. Invoking this method also
886      * ensures that if the authority could not be parsed in that way then an
887      * appropriate diagnostic message can be issued based upon the exception
888      * that is thrown. </p>
889      *
890      * @return A URI whose authority field has been parsed
891      * as a server-based authority
892      *
893      * @throws URISyntaxException
894      * If the authority component of this URI is defined
895      * but cannot be parsed as a server-based authority
896      * according to RFC&nbsp;2396
897      */

898     public URI JavaDoc parseServerAuthority()
899     throws URISyntaxException JavaDoc
900     {
901     // We could be clever and cache the error message and index from the
902
// exception thrown during the original parse, but that would require
903
// either more fields or a more-obscure representation.
904
if ((host != null) || (authority == null))
905         return this;
906     defineString();
907     new Parser(string).parse(true);
908     return this;
909     }
910
911     /**
912      * Normalizes this URI's path.
913      *
914      * <p> If this URI is opaque, or if its path is already in normal form,
915      * then this URI is returned. Otherwise a new URI is constructed that is
916      * identical to this URI except that its path is computed by normalizing
917      * this URI's path in a manner consistent with <a
918      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
919      * section&nbsp;5.2, step&nbsp;6, sub-steps&nbsp;c through&nbsp;f; that is:
920      * </p>
921      *
922      * <ol>
923      *
924      * <li><p> All <tt>"."</tt> segments are removed. </p></li>
925      *
926      * <li><p> If a <tt>".."</tt> segment is preceded by a non-<tt>".."</tt>
927      * segment then both of these segments are removed. This step is
928      * repeated until it is no longer applicable. </p></li>
929      *
930      * <li><p> If the path is relative, and if its first segment contains a
931      * colon character (<tt>':'</tt>), then a <tt>"."</tt> segment is
932      * prepended. This prevents a relative URI with a path such as
933      * <tt>"a:b/c/d"</tt> from later being re-parsed as an opaque URI with a
934      * scheme of <tt>"a"</tt> and a scheme-specific part of <tt>"b/c/d"</tt>.
935      * <b><i>(Deviation from RFC&nbsp;2396)</i></b> </p></li>
936      *
937      * </ol>
938      *
939      * <p> A normalized path will begin with one or more <tt>".."</tt> segments
940      * if there were insufficient non-<tt>".."</tt> segments preceding them to
941      * allow their removal. A normalized path will begin with a <tt>"."</tt>
942      * segment if one was inserted by step 3 above. Otherwise, a normalized
943      * path will not contain any <tt>"."</tt> or <tt>".."</tt> segments. </p>
944      *
945      * @return A URI equivalent to this URI,
946      * but whose path is in normal form
947      */

948     public URI JavaDoc normalize() {
949     return normalize(this);
950     }
951
952     /**
953      * Resolves the given URI against this URI.
954      *
955      * <p> If the given URI is already absolute, or if this URI is opaque, then
956      * the given URI is returned.
957      *
958      * <p><a name="resolve-frag"></a> If the given URI's fragment component is
959      * defined, its path component is empty, and its scheme, authority, and
960      * query components are undefined, then a URI with the given fragment but
961      * with all other components equal to those of this URI is returned. This
962      * allows a URI representing a standalone fragment reference, such as
963      * <tt>"#foo"</tt>, to be usefully resolved against a base URI.
964      *
965      * <p> Otherwise this method constructs a new hierarchical URI in a manner
966      * consistent with <a
967      * HREF="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
968      * section&nbsp;5.2; that is: </p>
969      *
970      * <ol>
971      *
972      * <li><p> A new URI is constructed with this URI's scheme and the given
973      * URI's query and fragment components. </p></li>
974      *
975      * <li><p> If the given URI has an authority component then the new URI's
976      * authority and path are taken from the given URI. </p></li>
977      *
978      * <li><p> Otherwise the new URI's authority component is copied from
979      * this URI, and its path is computed as follows: </p></li>
980      *
981      * <ol type=a>
982      *
983      * <li><p> If the given URI's path is absolute then the new URI's path
984      * is taken from the given URI. </p></li>
985      *
986      * <li><p> Otherwise the given URI's path is relative, and so the new
987      * URI's path is computed by resolving the path of the given URI
988      * against the path of this URI. This is done by concatenating all but
989      * the last segment of this URI's path, if any, with the given URI's
990      * path and then normalizing the result as if by invoking the {@link
991      * #normalize() normalize} method. </p></li>
992      *
993      * </ol>
994      *
995      * </ol>
996      *
997      * <p> The res