Source Home >> Java Source 1.6.0 >> java.net.URI V 0.09
  • 0001/*
  • 0002 * @(#)URI.java 1.48 06/06/12
  • 0003 *
  • 0004 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
  • 0005 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  • 0006 */
  • 0007
  • 0008package java.net;
  • 0009
  • 0010import java.io.IOException;
  • 0011import java.io.InvalidObjectException;
  • 0012import java.io.ObjectInputStream;
  • 0013import java.io.ObjectOutputStream;
  • 0014import java.io.Serializable;
  • 0015import java.nio.ByteBuffer;
  • 0016import java.nio.CharBuffer;
  • 0017import java.nio.charset.CharsetDecoder;
  • 0018import java.nio.charset.CharsetEncoder;
  • 0019import java.nio.charset.CoderResult;
  • 0020import java.nio.charset.CodingErrorAction;
  • 0021import java.nio.charset.CharacterCodingException;
  • 0022import java.text.Normalizer;
  • 0023import sun.nio.cs.ThreadLocalCoders;
  • 0024
  • 0025import java.lang.Character; // for javadoc
  • 0026import java.lang.NullPointerException; // for javadoc
  • 0027
  • 0028
  • 0029/**
  • 0030 * Represents a Uniform Resource Identifier (URI) reference.
  • 0031 *
  • 0032 * <p> Aside from some minor deviations noted below, an instance of this
  • 0033 * class represents a URI reference as defined by
  • 0034 * <a href="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC 2396: Uniform
  • 0035 * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
  • 0036 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC 2732: Format for
  • 0037 * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
  • 0038 * also supports scope_ids. The syntax and usage of scope_ids is described
  • 0039 * <a href="Inet6Address.html#scoped">here</a>.
  • 0040 * This class provides constructors for creating URI instances from
  • 0041 * their components or by parsing their string forms, methods for accessing the
  • 0042 * various components of an instance, and methods for normalizing, resolving,
  • 0043 * and relativizing URI instances. Instances of this class are immutable.
  • 0044 *
  • 0045 *
  • 0046 * <h4> URI syntax and components </h4>
  • 0047 *
  • 0048 * At the highest level a URI reference (hereinafter simply "URI") in string
  • 0049 * form has the syntax
  • 0050 *
  • 0051 * <blockquote>
  • 0052 * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
  • 0053 * </blockquote>
  • 0054 *
  • 0055 * where square brackets [...] delineate optional components and the characters
  • 0056 * <tt><b>:</b></tt> and <tt><b>#</b></tt> stand for themselves.
  • 0057 *
  • 0058 * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is
  • 0059 * said to be <i>relative</i>. URIs are also classified according to whether
  • 0060 * they are <i>opaque</i> or <i>hierarchical</i>.
  • 0061 *
  • 0062 * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does
  • 0063 * not begin with a slash character (<tt>'/'</tt>). Opaque URIs are not
  • 0064 * subject to further parsing. Some examples of opaque URIs are:
  • 0065 *
  • 0066 * <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
  • 0067 * <tr><td><tt>mailto:java-net@java.sun.com</tt><td></tr>
  • 0068 * <tr><td><tt>news:comp.lang.java</tt><td></tr>
  • 0069 * <tr><td><tt>urn:isbn:096139210x</tt></td></tr>
  • 0070 * </table></blockquote>
  • 0071 *
  • 0072 * <p> A <i>hierarchical</i> URI is either an absolute URI whose
  • 0073 * scheme-specific part begins with a slash character, or a relative URI, that
  • 0074 * is, a URI that does not specify a scheme. Some examples of hierarchical
  • 0075 * URIs are:
  • 0076 *
  • 0077 * <blockquote>
  • 0078 * <tt>http://java.sun.com/j2se/1.3/</tt><br>
  • 0079 * <tt>docs/guide/collections/designfaq.html#28</tt><br>
  • 0080 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java</tt><br>
  • 0081 * <tt>file:///~/calendar</tt>
  • 0082 * </blockquote>
  • 0083 *
  • 0084 * <p> A hierarchical URI is subject to further parsing according to the syntax
  • 0085 *
  • 0086 * <blockquote>
  • 0087 * [<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>]
  • 0088 * </blockquote>
  • 0089 *
  • 0090 * where the characters <tt><b>:</b></tt>, <tt><b>/</b></tt>,
  • 0091 * <tt><b>?</b></tt>, and <tt><b>#</b></tt> stand for themselves. The
  • 0092 * scheme-specific part of a hierarchical URI consists of the characters
  • 0093 * between the scheme and fragment components.
  • 0094 *
  • 0095 * <p> The authority component of a hierarchical URI is, if specified, either
  • 0096 * <i>server-based</i> or <i>registry-based</i>. A server-based authority
  • 0097 * parses according to the familiar syntax
  • 0098 *
  • 0099 * <blockquote>
  • 0100 * [<i>user-info</i><tt><b>@</b></tt>]<i>host</i>[<tt><b>:</b></tt><i>port</i>]
  • 0101 * </blockquote>
  • 0102 *
  • 0103 * where the characters <tt><b>@</b></tt> and <tt><b>:</b></tt> stand for
  • 0104 * themselves. Nearly all URI schemes currently in use are server-based. An
  • 0105 * authority component that does not parse in this way is considered to be
  • 0106 * registry-based.
  • 0107 *
  • 0108 * <p> The path component of a hierarchical URI is itself said to be absolute
  • 0109 * if it begins with a slash character (<tt>'/'</tt>); otherwise it is
  • 0110 * relative. The path of a hierarchical URI that is either absolute or
  • 0111 * specifies an authority is always absolute.
  • 0112 *
  • 0113 * <p> All told, then, a URI instance has the following nine components:
  • 0114 *
  • 0115 * <blockquote><table summary="Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment">
  • 0116 * <tr><th><i>Component</i></th><th><i>Type</i></th></tr>
  • 0117 * <tr><td>scheme</td><td><tt>String</tt></td></tr>
  • 0118 * <tr><td>scheme-specific-part    </td><td><tt>String</tt></td></tr>
  • 0119 * <tr><td>authority</td><td><tt>String</tt></td></tr>
  • 0120 * <tr><td>user-info</td><td><tt>String</tt></td></tr>
  • 0121 * <tr><td>host</td><td><tt>String</tt></td></tr>
  • 0122 * <tr><td>port</td><td><tt>int</tt></td></tr>
  • 0123 * <tr><td>path</td><td><tt>String</tt></td></tr>
  • 0124 * <tr><td>query</td><td><tt>String</tt></td></tr>
  • 0125 * <tr><td>fragment</td><td><tt>String</tt></td></tr>
  • 0126 * </table></blockquote>
  • 0127 *
  • 0128 * In a given instance any particular component is either <i>undefined</i> or
  • 0129 * <i>defined</i> with a distinct value. Undefined string components are
  • 0130 * represented by <tt>null</tt>, while undefined integer components are
  • 0131 * represented by <tt>-1</tt>. A string component may be defined to have the
  • 0132 * empty string as its value; this is not equivalent to that component being
  • 0133 * undefined.
  • 0134 *
  • 0135 * <p> Whether a particular component is or is not defined in an instance
  • 0136 * depends upon the type of the URI being represented. An absolute URI has a
  • 0137 * scheme component. An opaque URI has a scheme, a scheme-specific part, and
  • 0138 * possibly a fragment, but has no other components. A hierarchical URI always
  • 0139 * has a path (though it may be empty) and a scheme-specific-part (which at
  • 0140 * least contains the path), and may have any of the other components. If the
  • 0141 * authority component is present and is server-based then the host component
  • 0142 * will be defined and the user-information and port components may be defined.
  • 0143 *
  • 0144 *
  • 0145 * <h4> Operations on URI instances </h4>
  • 0146 *
  • 0147 * The key operations supported by this class are those of
  • 0148 * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>.
  • 0149 *
  • 0150 * <p> <i>Normalization</i> is the process of removing unnecessary <tt>"."</tt>
  • 0151 * and <tt>".."</tt> segments from the path component of a hierarchical URI.
  • 0152 * Each <tt>"."</tt> segment is simply removed. A <tt>".."</tt> segment is
  • 0153 * removed only if it is preceded by a non-<tt>".."</tt> segment.
  • 0154 * Normalization has no effect upon opaque URIs.
  • 0155 *
  • 0156 * <p> <i>Resolution</i> is the process of resolving one URI against another,
  • 0157 * <i>base</i> URI. The resulting URI is constructed from components of both
  • 0158 * URIs in the manner specified by RFC 2396, taking components from the
  • 0159 * base URI for those not specified in the original. For hierarchical URIs,
  • 0160 * the path of the original is resolved against the path of the base and then
  • 0161 * normalized. The result, for example, of resolving
  • 0162 *
  • 0163 * <blockquote>
  • 0164 * <tt>docs/guide/collections/designfaq.html#28          </tt>(1)
  • 0165 * </blockquote>
  • 0166 *
  • 0167 * against the base URI <tt>http://java.sun.com/j2se/1.3/</tt> is the result
  • 0168 * URI
  • 0169 *
  • 0170 * <blockquote>
  • 0171 * <tt>http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28</tt>
  • 0172 * </blockquote>
  • 0173 *
  • 0174 * Resolving the relative URI
  • 0175 *
  • 0176 * <blockquote>
  • 0177 * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java    </tt>(2)
  • 0178 * </blockquote>
  • 0179 *
  • 0180 * against this result yields, in turn,
  • 0181 *
  • 0182 * <blockquote>
  • 0183 * <tt>http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java</tt>
  • 0184 * </blockquote>
  • 0185 *
  • 0186 * Resolution of both absolute and relative URIs, and of both absolute and
  • 0187 * relative paths in the case of hierarchical URIs, is supported. Resolving
  • 0188 * the URI <tt>file:///~calendar</tt> against any other URI simply yields the
  • 0189 * original URI, since it is absolute. Resolving the relative URI (2) above
  • 0190 * against the relative base URI (1) yields the normalized, but still relative,
  • 0191 * URI
  • 0192 *
  • 0193 * <blockquote>
  • 0194 * <tt>demo/jfc/SwingSet2/src/SwingSet2.java</tt>
  • 0195 * </blockquote>
  • 0196 *
  • 0197 * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any
  • 0198 * two normalized URIs <i>u</i> and <i>v</i>,
  • 0199 *
  • 0200 * <blockquote>
  • 0201 * <i>u</i><tt>.relativize(</tt><i>u</i><tt>.resolve(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>  and<br>
  • 0202 * <i>u</i><tt>.resolve(</tt><i>u</i><tt>.relativize(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>  .<br>
  • 0203 * </blockquote>
  • 0204 *
  • 0205 * This operation is often useful when constructing a document containing URIs
  • 0206 * that must be made relative to the base URI of the document wherever
  • 0207 * possible. For example, relativizing the URI
  • 0208 *
  • 0209 * <blockquote>
  • 0210 * <tt>http://java.sun.com/j2se/1.3/docs/guide/index.html</tt>
  • 0211 * </blockquote>
  • 0212 *
  • 0213 * against the base URI
  • 0214 *
  • 0215 * <blockquote>
  • 0216 * <tt>http://java.sun.com/j2se/1.3</tt>
  • 0217 * </blockquote>
  • 0218 *
  • 0219 * yields the relative URI <tt>docs/guide/index.html</tt>.
  • 0220 *
  • 0221 *
  • 0222 * <h4> Character categories </h4>
  • 0223 *
  • 0224 * RFC 2396 specifies precisely which characters are permitted in the
  • 0225 * various components of a URI reference. The following categories, most of
  • 0226 * which are taken from that specification, are used below to describe these
  • 0227 * constraints:
  • 0228 *
  • 0229 * <blockquote><table cellspacing=2 summary="Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other">
  • 0230 * <tr><th valign=top><i>alpha</i></th>
  • 0231 * <td>The US-ASCII alphabetic characters,
  • 0232 * <tt>'A'</tt> through <tt>'Z'</tt>
  • 0233 * and <tt>'a'</tt> through <tt>'z'</tt></td></tr>
  • 0234 * <tr><th valign=top><i>digit</i></th>
  • 0235 * <td>The US-ASCII decimal digit characters,
  • 0236 * <tt>'0'</tt> through <tt>'9'</tt></td></tr>
  • 0237 * <tr><th valign=top><i>alphanum</i></th>
  • 0238 * <td>All <i>alpha</i> and <i>digit</i> characters</td></tr>
  • 0239 * <tr><th valign=top><i>unreserved</i>    </th>
  • 0240 * <td>All <i>alphanum</i> characters together with those in the string
  • 0241 * <tt>"_-!.~'()*"</tt></td></tr>
  • 0242 * <tr><th valign=top><i>punct</i></th>
  • 0243 * <td>The characters in the string <tt>",;:$&+="</tt></td></tr>
  • 0244 * <tr><th valign=top><i>reserved</i></th>
  • 0245 * <td>All <i>punct</i> characters together with those in the string
  • 0246 * <tt>"?/[]@"</tt></td></tr>
  • 0247 * <tr><th valign=top><i>escaped</i></th>
  • 0248 * <td>Escaped octets, that is, triplets consisting of the percent
  • 0249 * character (<tt>'%'</tt>) followed by two hexadecimal digits
  • 0250 * (<tt>'0'</tt>-<tt>'9'</tt>, <tt>'A'</tt>-<tt>'F'</tt>, and
  • 0251 * <tt>'a'</tt>-<tt>'f'</tt>)</td></tr>
  • 0252 * <tr><th valign=top><i>other</i></th>
  • 0253 * <td>The Unicode characters that are not in the US-ASCII character set,
  • 0254 * are not control characters (according to the {@link
  • 0255 * java.lang.Character#isISOControl(char) Character.isISOControl}
  • 0256 * method), and are not space characters (according to the {@link
  • 0257 * java.lang.Character#isSpaceChar(char) Character.isSpaceChar}
  • 0258 * method)  <i>(<b>Deviation from RFC 2396</b>, which is
  • 0259 * limited to US-ASCII)</i></td></tr>
  • 0260 * </table></blockquote>
  • 0261 *
  • 0262 * <p><a name="legal-chars"></a> The set of all legal URI characters consists of
  • 0263 * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i>
  • 0264 * characters.
  • 0265 *
  • 0266 *
  • 0267 * <h4> Escaped octets, quotation, encoding, and decoding </h4>
  • 0268 *
  • 0269 * RFC 2396 allows escaped octets to appear in the user-info, path, query, and
  • 0270 * fragment components. Escaping serves two purposes in URIs:
  • 0271 *
  • 0272 * <ul>
  • 0273 *
  • 0274 * <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to
  • 0275 * conform strictly to RFC 2396 by not containing any <i>other</i>
  • 0276 * characters. </p></li>
  • 0277 *
  • 0278 * <li><p> To <i>quote</i> characters that are otherwise illegal in a
  • 0279 * component. The user-info, path, query, and fragment components differ
  • 0280 * slightly in terms of which characters are considered legal and illegal.
  • 0281 * </p></li>
  • 0282 *
  • 0283 * </ul>
  • 0284 *
  • 0285 * These purposes are served in this class by three related operations:
  • 0286 *
  • 0287 * <ul>
  • 0288 *
  • 0289 * <li><p><a name="encode"></a> A character is <i>encoded</i> by replacing it
  • 0290 * with the sequence of escaped octets that represent that character in the
  • 0291 * UTF-8 character set. The Euro currency symbol (<tt>'\u20AC'</tt>),
  • 0292 * for example, is encoded as <tt>"%E2%82%AC"</tt>. <i>(<b>Deviation from
  • 0293 * RFC 2396</b>, which does not specify any particular character
  • 0294 * set.)</i> </p></li>
  • 0295 *
  • 0296 * <li><p><a name="quote"></a> An illegal character is <i>quoted</i> simply by
  • 0297 * encoding it. The space character, for example, is quoted by replacing it
  • 0298 * with <tt>"%20"</tt>. UTF-8 contains US-ASCII, hence for US-ASCII
  • 0299 * characters this transformation has exactly the effect required by
  • 0300 * RFC 2396. </p></li>
  • 0301 *
  • 0302 * <li><p><a name="decode"></a>
  • 0303 * A sequence of escaped octets is <i>decoded</i> by
  • 0304 * replacing it with the sequence of characters that it represents in the
  • 0305 * UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the
  • 0306 * effect of de-quoting any quoted US-ASCII characters as well as that of
  • 0307 * decoding any encoded non-US-ASCII characters. If a <a
  • 0308 * href="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs
  • 0309 * when decoding the escaped octets then the erroneous octets are replaced by
  • 0310 * <tt>'\uFFFD'</tt>, the Unicode replacement character. </p></li>
  • 0311 *
  • 0312 * </ul>
  • 0313 *
  • 0314 * These operations are exposed in the constructors and methods of this class
  • 0315 * as follows:
  • 0316 *
  • 0317 * <ul>
  • 0318 *
  • 0319 * <li><p> The {@link #URI(java.lang.String) <code>single-argument
  • 0320 * constructor</code>} requires any illegal characters in its argument to be
  • 0321 * quoted and preserves any escaped octets and <i>other</i> characters that
  • 0322 * are present. </p></li>
  • 0323 *
  • 0324 * <li><p> The {@link
  • 0325 * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
  • 0326 * <code>multi-argument constructors</code>} quote illegal characters as
  • 0327 * required by the components in which they appear. The percent character
  • 0328 * (<tt>'%'</tt>) is always quoted by these constructors. Any <i>other</i>
  • 0329 * characters are preserved. </p></li>
  • 0330 *
  • 0331 * <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath()
  • 0332 * getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment()
  • 0333 * getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link
  • 0334 * #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the
  • 0335 * values of their corresponding components in raw form, without interpreting
  • 0336 * any escaped octets. The strings returned by these methods may contain
  • 0337 * both escaped octets and <i>other</i> characters, and will not contain any
  • 0338 * illegal characters. </p></li>
  • 0339 *
  • 0340 * <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath()
  • 0341 * getPath}, {@link #getQuery() getQuery}, {@link #getFragment()
  • 0342 * getFragment}, {@link #getAuthority() getAuthority}, and {@link
  • 0343 * #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped
  • 0344 * octets in their corresponding components. The strings returned by these
  • 0345 * methods may contain both <i>other</i> characters and illegal characters,
  • 0346 * and will not contain any escaped octets. </p></li>
  • 0347 *
  • 0348 * <li><p> The {@link #toString() toString} method returns a URI string with
  • 0349 * all necessary quotation but which may contain <i>other</i> characters.
  • 0350 * </p></li>
  • 0351 *
  • 0352 * <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully
  • 0353 * quoted and encoded URI string that does not contain any <i>other</i>
  • 0354 * characters. </p></li>
  • 0355 *
  • 0356 * </ul>
  • 0357 *
  • 0358 *
  • 0359 * <h4> Identities </h4>
  • 0360 *
  • 0361 * For any URI <i>u</i>, it is always the case that
  • 0362 *
  • 0363 * <blockquote>
  • 0364 * <tt>new URI(</tt><i>u</i><tt>.toString()).equals(</tt><i>u</i><tt>)</tt> .
  • 0365 * </blockquote>
  • 0366 *
  • 0367 * For any URI <i>u</i> that does not contain redundant syntax such as two
  • 0368 * slashes before an empty authority (as in <tt>file:///tmp/</tt> ) or a
  • 0369 * colon following a host name but no port (as in
  • 0370 * <tt>http://java.sun.com:</tt> ), and that does not encode characters
  • 0371 * except those that must be quoted, the following identities also hold:
  • 0372 *
  • 0373 * <blockquote>
  • 0374 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  • 0375 *         </tt><i>u</i><tt>.getSchemeSpecificPart(),<br>
  • 0376 *         </tt><i>u</i><tt>.getFragment())<br>
  • 0377 * .equals(</tt><i>u</i><tt>)</tt>
  • 0378 * </blockquote>
  • 0379 *
  • 0380 * in all cases,
  • 0381 *
  • 0382 * <blockquote>
  • 0383 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  • 0384 *         </tt><i>u</i><tt>.getUserInfo(), </tt><i>u</i><tt>.getAuthority(),<br>
  • 0385 *         </tt><i>u</i><tt>.getPath(), </tt><i>u</i><tt>.getQuery(),<br>
  • 0386 *         </tt><i>u</i><tt>.getFragment())<br>
  • 0387 * .equals(</tt><i>u</i><tt>)</tt>
  • 0388 * </blockquote>
  • 0389 *
  • 0390 * if <i>u</i> is hierarchical, and
  • 0391 *
  • 0392 * <blockquote>
  • 0393 * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  • 0394 *         </tt><i>u</i><tt>.getUserInfo(), </tt><i>u</i><tt>.getHost(), </tt><i>u</i><tt>.getPort(),<br>
  • 0395 *         </tt><i>u</i><tt>.getPath(), </tt><i>u</i><tt>.getQuery(),<br>
  • 0396 *         </tt><i>u</i><tt>.getFragment())<br>
  • 0397 * .equals(</tt><i>u</i><tt>)</tt>
  • 0398 * </blockquote>
  • 0399 *
  • 0400 * if <i>u</i> is hierarchical and has either no authority or a server-based
  • 0401 * authority.
  • 0402 *
  • 0403 *
  • 0404 * <h4> URIs, URLs, and URNs </h4>
  • 0405 *
  • 0406 * A URI is a uniform resource <i>identifier</i> while a URL is a uniform
  • 0407 * resource <i>locator</i>. Hence every URL is a URI, abstractly speaking, but
  • 0408 * not every URI is a URL. This is because there is another subcategory of
  • 0409 * URIs, uniform resource <i>names</i> (URNs), which name resources but do not
  • 0410 * specify how to locate them. The <tt>mailto</tt>, <tt>news</tt>, and
  • 0411 * <tt>isbn</tt> URIs shown above are examples of URNs.
  • 0412 *
  • 0413 * <p> The conceptual distinction between URIs and URLs is reflected in the
  • 0414 * differences between this class and the {@link URL} class.
  • 0415 *
  • 0416 * <p> An instance of this class represents a URI reference in the syntactic
  • 0417 * sense defined by RFC 2396. A URI may be either absolute or relative.
  • 0418 * A URI string is parsed according to the generic syntax without regard to the
  • 0419 * scheme, if any, that it specifies. No lookup of the host, if any, is
  • 0420 * performed, and no scheme-dependent stream handler is constructed. Equality,
  • 0421 * hashing, and comparison are defined strictly in terms of the character
  • 0422 * content of the instance. In other words, a URI instance is little more than
  • 0423 * a structured string that supports the syntactic, scheme-independent
  • 0424 * operations of comparison, normalization, resolution, and relativization.
  • 0425 *
  • 0426 * <p> An instance of the {@link URL} class, by contrast, represents the
  • 0427 * syntactic components of a URL together with some of the information required
  • 0428 * to access the resource that it describes. A URL must be absolute, that is,
  • 0429 * it must always specify a scheme. A URL string is parsed according to its
  • 0430 * scheme. A stream handler is always established for a URL, and in fact it is
  • 0431 * impossible to create a URL instance for a scheme for which no handler is
  • 0432 * available. Equality and hashing depend upon both the scheme and the
  • 0433 * Internet address of the host, if any; comparison is not defined. In other
  • 0434 * words, a URL is a structured string that supports the syntactic operation of
  • 0435 * resolution as well as the network I/O operations of looking up the host and
  • 0436 * opening a connection to the specified resource.
  • 0437 *
  • 0438 *
  • 0439 * @version 1.48, 06/06/12
  • 0440 * @author Mark Reinhold
  • 0441 * @since 1.4
  • 0442 *
  • 0443 * @see <a href="http://ietf.org/rfc/rfc2279.txt"><i>RFC 2279: UTF-8, a
  • 0444 * transformation format of ISO 10646</i></a>, <br><a
  • 0445 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IPv6 Addressing
  • 0446 * Architecture</i></a>, <br><a
  • 0447 * href="http://www.ietf.org/rfc/rfc2396.txt""><i>RFC 2396: Uniform
  • 0448 * Resource Identifiers (URI): Generic Syntax</i></a>, <br><a
  • 0449 * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC 2732: Format for
  • 0450 * Literal IPv6 Addresses in URLs</i></a>, <br><a
  • 0451 * href="URISyntaxException.html">URISyntaxException</a>
  • 0452 */
  • 0453
  • 0454public final class URI
  • 0455 implements Comparable<URI>, Serializable
  • 0456{
  • 0457
  • 0458 // Note: Comments containing the word "ASSERT" indicate places where a
  • 0459 // throw of an InternalError should be replaced by an appropriate assertion
  • 0460 // statement once asserts are enabled in the build.
  • 0461
  • 0462 static final long serialVersionUID = -6052424284110960213L;
  • 0463
  • 0464
  • 0465 // -- Properties and components of this instance --
  • 0466
  • 0467 // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
  • 0468 private transient String scheme; // null ==> relative URI
  • 0469 private transient String fragment;
  • 0470
  • 0471 // Hierarchical URI components: [//<authority>]<path>[?<query>]
  • 0472 private transient String authority; // Registry or server
  • 0473
  • 0474 // Server-based authority: [<userInfo>@]<host>[:<port>]
  • 0475 private transient String userInfo;
  • 0476 private transient String host; // null ==> registry-based
  • 0477 private transient int port = -1; // -1 ==> undefined
  • 0478
  • 0479 // Remaining components of hierarchical URIs
  • 0480 private transient String path; // null ==> opaque
  • 0481 private transient String query;
  • 0482
  • 0483 // The remaining fields may be computed on demand
  • 0484
  • 0485 private volatile transient String schemeSpecificPart;
  • 0486 private volatile transient int hash; // Zero ==> undefined
  • 0487
  • 0488 private volatile transient String decodedUserInfo = null;
  • 0489 private volatile transient String decodedAuthority = null;
  • 0490 private volatile transient String decodedPath = null;
  • 0491 private volatile transient String decodedQuery = null;
  • 0492 private volatile transient String decodedFragment = null;
  • 0493 private volatile transient String decodedSchemeSpecificPart = null;
  • 0494
  • 0495 /**
  • 0496 * The string form of this URI.
  • 0497 *
  • 0498 * @serial
  • 0499 */
  • 0500 private volatile String string; // The only serializable field
  • 0501
  • 0502
  • 0503
  • 0504 // -- Constructors and factories --
  • 0505
  • 0506 private URI() { } // Used internally
  • 0507
  • 0508 /**
  • 0509 * Constructs a URI by parsing the given string.
  • 0510 *
  • 0511 * <p> This constructor parses the given string exactly as specified by the
  • 0512 * grammar in <a
  • 0513 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 0514 * Appendix A, <b><i>except for the following deviations:</i></b> </p>
  • 0515 *
  • 0516 * <ul type=disc>
  • 0517 *
  • 0518 * <li><p> An empty authority component is permitted as long as it is
  • 0519 * followed by a non-empty path, a query component, or a fragment
  • 0520 * component. This allows the parsing of URIs such as
  • 0521 * <tt>"file:///foo/bar"</tt>, which seems to be the intent of
  • 0522 * RFC 2396 although the grammar does not permit it. If the
  • 0523 * authority component is empty then the user-information, host, and port
  • 0524 * components are undefined. </p></li>
  • 0525 *
  • 0526 * <li><p> Empty relative paths are permitted; this seems to be the
  • 0527 * intent of RFC 2396 although the grammar does not permit it. The
  • 0528 * primary consequence of this deviation is that a standalone fragment
  • 0529 * such as <tt>"#foo"</tt> parses as a relative URI with an empty path
  • 0530 * and the given fragment, and can be usefully <a
  • 0531 * href="#resolve-frag">resolved</a> against a base URI.
  • 0532 *
  • 0533 * <li><p> IPv4 addresses in host components are parsed rigorously, as
  • 0534 * specified by <a
  • 0535 * href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>: Each
  • 0536 * element of a dotted-quad address must contain no more than three
  • 0537 * decimal digits. Each element is further constrained to have a value
  • 0538 * no greater than 255. </p></li>
  • 0539 *
  • 0540 * <li> <p> Hostnames in host components that comprise only a single
  • 0541 * domain label are permitted to start with an <i>alphanum</i>
  • 0542 * character. This seems to be the intent of <a
  • 0543 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>
  • 0544 * section 3.2.2 although the grammar does not permit it. The
  • 0545 * consequence of this deviation is that the authority component of a
  • 0546 * hierarchical URI such as <tt>s://123</tt>, will parse as a server-based
  • 0547 * authority. </p></li>
  • 0548 *
  • 0549 * <li><p> IPv6 addresses are permitted for the host component. An IPv6
  • 0550 * address must be enclosed in square brackets (<tt>'['</tt> and
  • 0551 * <tt>']'</tt>) as specified by <a
  • 0552 * href="http://www.ietf.org/rfc/rfc2732.txt">RFC 2732</a>. The
  • 0553 * IPv6 address itself must parse according to <a
  • 0554 * href="http://www.ietf.org/rfc/rfc2373.txt">RFC 2373</a>. IPv6
  • 0555 * addresses are further constrained to describe no more than sixteen
  • 0556 * bytes of address information, a constraint implicit in RFC 2373
  • 0557 * but not expressible in the grammar. </p></li>
  • 0558 *
  • 0559 * <li><p> Characters in the <i>other</i> category are permitted wherever
  • 0560 * RFC 2396 permits <i>escaped</i> octets, that is, in the
  • 0561 * user-information, path, query, and fragment components, as well as in
  • 0562 * the authority component if the authority is registry-based. This
  • 0563 * allows URIs to contain Unicode characters beyond those in the US-ASCII
  • 0564 * character set. </p></li>
  • 0565 *
  • 0566 * </ul>
  • 0567 *
  • 0568 * @param str The string to be parsed into a URI
  • 0569 *
  • 0570 * @throws NullPointerException
  • 0571 * If <tt>str</tt> is <tt>null</tt>
  • 0572 *
  • 0573 * @throws URISyntaxException
  • 0574 * If the given string violates RFC 2396, as augmented
  • 0575 * by the above deviations
  • 0576 */
  • 0577 public URI(String str) throws URISyntaxException {
  • 0578 new Parser(str).parse(false);
  • 0579 }
  • 0580
  • 0581 /**
  • 0582 * Constructs a hierarchical URI from the given components.
  • 0583 *
  • 0584 * <p> If a scheme is given then the path, if also given, must either be
  • 0585 * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
  • 0586 * component of the new URI may be left undefined by passing <tt>null</tt>
  • 0587 * for the corresponding parameter or, in the case of the <tt>port</tt>
  • 0588 * parameter, by passing <tt>-1</tt>.
  • 0589 *
  • 0590 * <p> This constructor first builds a URI string from the given components
  • 0591 * according to the rules specified in <a
  • 0592 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 0593 * section 5.2, step 7: </p>
  • 0594 *
  • 0595 * <ol>
  • 0596 *
  • 0597 * <li><p> Initially, the result string is empty. </p></li>
  • 0598 *
  • 0599 * <li><p> If a scheme is given then it is appended to the result,
  • 0600 * followed by a colon character (<tt>':'</tt>). </p></li>
  • 0601 *
  • 0602 * <li><p> If user information, a host, or a port are given then the
  • 0603 * string <tt>"//"</tt> is appended. </p></li>
  • 0604 *
  • 0605 * <li><p> If user information is given then it is appended, followed by
  • 0606 * a commercial-at character (<tt>'@'</tt>). Any character not in the
  • 0607 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  • 0608 * categories is <a href="#quote">quoted</a>. </p></li>
  • 0609 *
  • 0610 * <li><p> If a host is given then it is appended. If the host is a
  • 0611 * literal IPv6 address but is not enclosed in square brackets
  • 0612 * (<tt>'['</tt> and <tt>']'</tt>) then the square brackets are added.
  • 0613 * </p></li>
  • 0614 *
  • 0615 * <li><p> If a port number is given then a colon character
  • 0616 * (<tt>':'</tt>) is appended, followed by the port number in decimal.
  • 0617 * </p></li>
  • 0618 *
  • 0619 * <li><p> If a path is given then it is appended. Any character not in
  • 0620 * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  • 0621 * categories, and not equal to the slash character (<tt>'/'</tt>) or the
  • 0622 * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
  • 0623 *
  • 0624 * <li><p> If a query is given then a question-mark character
  • 0625 * (<tt>'?'</tt>) is appended, followed by the query. Any character that
  • 0626 * is not a <a href="#legal-chars">legal URI character</a> is quoted.
  • 0627 * </p></li>
  • 0628 *
  • 0629 * <li><p> Finally, if a fragment is given then a hash character
  • 0630 * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
  • 0631 * that is not a legal URI character is quoted. </p></li>
  • 0632 *
  • 0633 * </ol>
  • 0634 *
  • 0635 * <p> The resulting URI string is then parsed as if by invoking the {@link
  • 0636 * #URI(String)} constructor and then invoking the {@link
  • 0637 * #parseServerAuthority()} method upon the result; this may cause a {@link
  • 0638 * URISyntaxException} to be thrown. </p>
  • 0639 *
  • 0640 * @param scheme Scheme name
  • 0641 * @param userInfo User name and authorization information
  • 0642 * @param host Host name
  • 0643 * @param port Port number
  • 0644 * @param path Path
  • 0645 * @param query Query
  • 0646 * @param fragment Fragment
  • 0647 *
  • 0648 * @throws URISyntaxException
  • 0649 * If both a scheme and a path are given but the path is relative,
  • 0650 * if the URI string constructed from the given components violates
  • 0651 * RFC 2396, or if the authority component of the string is
  • 0652 * present but cannot be parsed as a server-based authority
  • 0653 */
  • 0654 public URI(String scheme,
  • 0655 String userInfo, String host, int port,
  • 0656 String path, String query, String fragment)
  • 0657 throws URISyntaxException
  • 0658 {
  • 0659 String s = toString(scheme, null,
  • 0660 null, userInfo, host, port,
  • 0661 path, query, fragment);
  • 0662 checkPath(s, scheme, path);
  • 0663 new Parser(s).parse(true);
  • 0664 }
  • 0665
  • 0666 /**
  • 0667 * Constructs a hierarchical URI from the given components.
  • 0668 *
  • 0669 * <p> If a scheme is given then the path, if also given, must either be
  • 0670 * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
  • 0671 * component of the new URI may be left undefined by passing <tt>null</tt>
  • 0672 * for the corresponding parameter.
  • 0673 *
  • 0674 * <p> This constructor first builds a URI string from the given components
  • 0675 * according to the rules specified in <a
  • 0676 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 0677 * section 5.2, step 7: </p>
  • 0678 *
  • 0679 * <ol>
  • 0680 *
  • 0681 * <li><p> Initially, the result string is empty. </p></li>
  • 0682 *
  • 0683 * <li><p> If a scheme is given then it is appended to the result,
  • 0684 * followed by a colon character (<tt>':'</tt>). </p></li>
  • 0685 *
  • 0686 * <li><p> If an authority is given then the string <tt>"//"</tt> is
  • 0687 * appended, followed by the authority. If the authority contains a
  • 0688 * literal IPv6 address then the address must be enclosed in square
  • 0689 * brackets (<tt>'['</tt> and <tt>']'</tt>). Any character not in the
  • 0690 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  • 0691 * categories, and not equal to the commercial-at character
  • 0692 * (<tt>'@'</tt>), is <a href="#quote">quoted</a>. </p></li>
  • 0693 *
  • 0694 * <li><p> If a path is given then it is appended. Any character not in
  • 0695 * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  • 0696 * categories, and not equal to the slash character (<tt>'/'</tt>) or the
  • 0697 * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
  • 0698 *
  • 0699 * <li><p> If a query is given then a question-mark character
  • 0700 * (<tt>'?'</tt>) is appended, followed by the query. Any character that
  • 0701 * is not a <a href="#legal-chars">legal URI character</a> is quoted.
  • 0702 * </p></li>
  • 0703 *
  • 0704 * <li><p> Finally, if a fragment is given then a hash character
  • 0705 * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
  • 0706 * that is not a legal URI character is quoted. </p></li>
  • 0707 *
  • 0708 * </ol>
  • 0709 *
  • 0710 * <p> The resulting URI string is then parsed as if by invoking the {@link
  • 0711 * #URI(String)} constructor and then invoking the {@link
  • 0712 * #parseServerAuthority()} method upon the result; this may cause a {@link
  • 0713 * URISyntaxException} to be thrown. </p>
  • 0714 *
  • 0715 * @param scheme Scheme name
  • 0716 * @param authority Authority
  • 0717 * @param path Path
  • 0718 * @param query Query
  • 0719 * @param fragment Fragment
  • 0720 *
  • 0721 * @throws URISyntaxException
  • 0722 * If both a scheme and a path are given but the path is relative,
  • 0723 * if the URI string constructed from the given components violates
  • 0724 * RFC 2396, or if the authority component of the string is
  • 0725 * present but cannot be parsed as a server-based authority
  • 0726 */
  • 0727 public URI(String scheme,
  • 0728 String authority,
  • 0729 String path, String query, String fragment)
  • 0730 throws URISyntaxException
  • 0731 {
  • 0732 String s = toString(scheme, null,
  • 0733 authority, null, null, -1,
  • 0734 path, query, fragment);
  • 0735 checkPath(s, scheme, path);
  • 0736 new Parser(s).parse(false);
  • 0737 }
  • 0738
  • 0739 /**
  • 0740 * Constructs a hierarchical URI from the given components.
  • 0741 *
  • 0742 * <p> A component may be left undefined by passing <tt>null</tt>.
  • 0743 *
  • 0744 * <p> This convenience constructor works as if by invoking the
  • 0745 * seven-argument constructor as follows:
  • 0746 *
  • 0747 * <blockquote><tt>
  • 0748 * new {@link #URI(String, String, String, int, String, String, String)
  • 0749 * URI}(scheme, null, host, -1, path, null, fragment);
  • 0750 * </tt></blockquote>
  • 0751 *
  • 0752 * @param scheme Scheme name
  • 0753 * @param host Host name
  • 0754 * @param path Path
  • 0755 * @param fragment Fragment
  • 0756 *
  • 0757 * @throws URISyntaxException
  • 0758 * If the URI string constructed from the given components
  • 0759 * violates RFC 2396
  • 0760 */
  • 0761 public URI(String scheme, String host, String path, String fragment)
  • 0762 throws URISyntaxException
  • 0763 {
  • 0764 this(scheme, null, host, -1, path, null, fragment);
  • 0765 }
  • 0766
  • 0767 /**
  • 0768 * Constructs a URI from the given components.
  • 0769 *
  • 0770 * <p> A component may be left undefined by passing <tt>null</tt>.
  • 0771 *
  • 0772 * <p> This constructor first builds a URI in string form using the given
  • 0773 * components as follows: </p>
  • 0774 *
  • 0775 * <ol>
  • 0776 *
  • 0777 * <li><p> Initially, the result string is empty. </p></li>
  • 0778 *
  • 0779 * <li><p> If a scheme is given then it is appended to the result,
  • 0780 * followed by a colon character (<tt>':'</tt>). </p></li>
  • 0781 *
  • 0782 * <li><p> If a scheme-specific part is given then it is appended. Any
  • 0783 * character that is not a <a href="#legal-chars">legal URI character</a>
  • 0784 * is <a href="#quote">quoted</a>. </p></li>
  • 0785 *
  • 0786 * <li><p> Finally, if a fragment is given then a hash character
  • 0787 * (<tt>'#'</tt>) is appended to the string, followed by the fragment.
  • 0788 * Any character that is not a legal URI character is quoted. </p></li>
  • 0789 *
  • 0790 * </ol>
  • 0791 *
  • 0792 * <p> The resulting URI string is then parsed in order to create the new
  • 0793 * URI instance as if by invoking the {@link #URI(String)} constructor;
  • 0794 * this may cause a {@link URISyntaxException} to be thrown. </p>
  • 0795 *
  • 0796 * @param scheme Scheme name
  • 0797 * @param ssp Scheme-specific part
  • 0798 * @param fragment Fragment
  • 0799 *
  • 0800 * @throws URISyntaxException
  • 0801 * If the URI string constructed from the given components
  • 0802 * violates RFC 2396
  • 0803 */
  • 0804 public URI(String scheme, String ssp, String fragment)
  • 0805 throws URISyntaxException
  • 0806 {
  • 0807 new Parser(toString(scheme, ssp,
  • 0808 null, null, null, -1,
  • 0809 null, null, fragment))
  • 0810 .parse(false);
  • 0811 }
  • 0812
  • 0813 /**
  • 0814 * Creates a URI by parsing the given string.
  • 0815 *
  • 0816 * <p> This convenience factory method works as if by invoking the {@link
  • 0817 * #URI(String)} constructor; any {@link URISyntaxException} thrown by the
  • 0818 * constructor is caught and wrapped in a new {@link
  • 0819 * IllegalArgumentException} object, which is then thrown.
  • 0820 *
  • 0821 * <p> This method is provided for use in situations where it is known that
  • 0822 * the given string is a legal URI, for example for URI constants declared
  • 0823 * within in a program, and so it would be considered a programming error
  • 0824 * for the string not to parse as such. The constructors, which throw
  • 0825 * {@link URISyntaxException} directly, should be used situations where a
  • 0826 * URI is being constructed from user input or from some other source that
  • 0827 * may be prone to errors. </p>
  • 0828 *
  • 0829 * @param str The string to be parsed into a URI
  • 0830 * @return The new URI
  • 0831 *
  • 0832 * @throws NullPointerException
  • 0833 * If <tt>str</tt> is <tt>null</tt>
  • 0834 *
  • 0835 * @throws IllegalArgumentException
  • 0836 * If the given string violates RFC 2396
  • 0837 */
  • 0838 public static URI create(String str) {
  • 0839 try {
  • 0840 return new URI(str);
  • 0841 } catch (URISyntaxException x) {
  • 0842 IllegalArgumentException y = new IllegalArgumentException();
  • 0843 y.initCause(x);
  • 0844 throw y;
  • 0845 }
  • 0846 }
  • 0847
  • 0848
  • 0849 // -- Operations --
  • 0850
  • 0851 /**
  • 0852 * Attempts to parse this URI's authority component, if defined, into
  • 0853 * user-information, host, and port components.
  • 0854 *
  • 0855 * <p> If this URI's authority component has already been recognized as
  • 0856 * being server-based then it will already have been parsed into
  • 0857 * user-information, host, and port components. In this case, or if this
  • 0858 * URI has no authority component, this method simply returns this URI.
  • 0859 *
  • 0860 * <p> Otherwise this method attempts once more to parse the authority
  • 0861 * component into user-information, host, and port components, and throws
  • 0862 * an exception describing why the authority component could not be parsed
  • 0863 * in that way.
  • 0864 *
  • 0865 * <p> This method is provided because the generic URI syntax specified in
  • 0866 * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>
  • 0867 * cannot always distinguish a malformed server-based authority from a
  • 0868 * legitimate registry-based authority. It must therefore treat some
  • 0869 * instances of the former as instances of the latter. The authority
  • 0870 * component in the URI string <tt>"//foo:bar"</tt>, for example, is not a
  • 0871 * legal server-based authority but it is legal as a registry-based
  • 0872 * authority.
  • 0873 *
  • 0874 * <p> In many common situations, for example when working URIs that are
  • 0875 * known to be either URNs or URLs, the hierarchical URIs being used will
  • 0876 * always be server-based. They therefore must either be parsed as such or
  • 0877 * treated as an error. In these cases a statement such as
  • 0878 *
  • 0879 * <blockquote>
  • 0880 * <tt>URI </tt><i>u</i><tt> = new URI(str).parseServerAuthority();</tt>
  • 0881 * </blockquote>
  • 0882 *
  • 0883 * <p> can be used to ensure that <i>u</i> always refers to a URI that, if
  • 0884 * it has an authority component, has a server-based authority with proper
  • 0885 * user-information, host, and port components. Invoking this method also
  • 0886 * ensures that if the authority could not be parsed in that way then an
  • 0887 * appropriate diagnostic message can be issued based upon the exception
  • 0888 * that is thrown. </p>
  • 0889 *
  • 0890 * @return A URI whose authority field has been parsed
  • 0891 * as a server-based authority
  • 0892 *
  • 0893 * @throws URISyntaxException
  • 0894 * If the authority component of this URI is defined
  • 0895 * but cannot be parsed as a server-based authority
  • 0896 * according to RFC 2396
  • 0897 */
  • 0898 public URI parseServerAuthority()
  • 0899 throws URISyntaxException
  • 0900 {
  • 0901 // We could be clever and cache the error message and index from the
  • 0902 // exception thrown during the original parse, but that would require
  • 0903 // either more fields or a more-obscure representation.
  • 0904 if ((host != null) || (authority == null))
  • 0905 return this;
  • 0906 defineString();
  • 0907 new Parser(string).parse(true);
  • 0908 return this;
  • 0909 }
  • 0910
  • 0911 /**
  • 0912 * Normalizes this URI's path.
  • 0913 *
  • 0914 * <p> If this URI is opaque, or if its path is already in normal form,
  • 0915 * then this URI is returned. Otherwise a new URI is constructed that is
  • 0916 * identical to this URI except that its path is computed by normalizing
  • 0917 * this URI's path in a manner consistent with <a
  • 0918 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 0919 * section 5.2, step 6, sub-steps c through f; that is:
  • 0920 * </p>
  • 0921 *
  • 0922 * <ol>
  • 0923 *
  • 0924 * <li><p> All <tt>"."</tt> segments are removed. </p></li>
  • 0925 *
  • 0926 * <li><p> If a <tt>".."</tt> segment is preceded by a non-<tt>".."</tt>
  • 0927 * segment then both of these segments are removed. This step is
  • 0928 * repeated until it is no longer applicable. </p></li>
  • 0929 *
  • 0930 * <li><p> If the path is relative, and if its first segment contains a
  • 0931 * colon character (<tt>':'</tt>), then a <tt>"."</tt> segment is
  • 0932 * prepended. This prevents a relative URI with a path such as
  • 0933 * <tt>"a:b/c/d"</tt> from later being re-parsed as an opaque URI with a
  • 0934 * scheme of <tt>"a"</tt> and a scheme-specific part of <tt>"b/c/d"</tt>.
  • 0935 * <b><i>(Deviation from RFC 2396)</i></b> </p></li>
  • 0936 *
  • 0937 * </ol>
  • 0938 *
  • 0939 * <p> A normalized path will begin with one or more <tt>".."</tt> segments
  • 0940 * if there were insufficient non-<tt>".."</tt> segments preceding them to
  • 0941 * allow their removal. A normalized path will begin with a <tt>"."</tt>
  • 0942 * segment if one was inserted by step 3 above. Otherwise, a normalized
  • 0943 * path will not contain any <tt>"."</tt> or <tt>".."</tt> segments. </p>
  • 0944 *
  • 0945 * @return A URI equivalent to this URI,
  • 0946 * but whose path is in normal form
  • 0947 */
  • 0948 public URI normalize() {
  • 0949 return normalize(this);
  • 0950 }
  • 0951
  • 0952 /**
  • 0953 * Resolves the given URI against this URI.
  • 0954 *
  • 0955 * <p> If the given URI is already absolute, or if this URI is opaque, then
  • 0956 * the given URI is returned.
  • 0957 *
  • 0958 * <p><a name="resolve-frag"></a> If the given URI's fragment component is
  • 0959 * defined, its path component is empty, and its scheme, authority, and
  • 0960 * query components are undefined, then a URI with the given fragment but
  • 0961 * with all other components equal to those of this URI is returned. This
  • 0962 * allows a URI representing a standalone fragment reference, such as
  • 0963 * <tt>"#foo"</tt>, to be usefully resolved against a base URI.
  • 0964 *
  • 0965 * <p> Otherwise this method constructs a new hierarchical URI in a manner
  • 0966 * consistent with <a
  • 0967 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 0968 * section 5.2; that is: </p>
  • 0969 *
  • 0970 * <ol>
  • 0971 *
  • 0972 * <li><p> A new URI is constructed with this URI's scheme and the given
  • 0973 * URI's query and fragment components. </p></li>
  • 0974 *
  • 0975 * <li><p> If the given URI has an authority component then the new URI's
  • 0976 * authority and path are taken from the given URI. </p></li>
  • 0977 *
  • 0978 * <li><p> Otherwise the new URI's authority component is copied from
  • 0979 * this URI, and its path is computed as follows: </p></li>
  • 0980 *
  • 0981 * <ol type=a>
  • 0982 *
  • 0983 * <li><p> If the given URI's path is absolute then the new URI's path
  • 0984 * is taken from the given URI. </p></li>
  • 0985 *
  • 0986 * <li><p> Otherwise the given URI's path is relative, and so the new
  • 0987 * URI's path is computed by resolving the path of the given URI
  • 0988 * against the path of this URI. This is done by concatenating all but
  • 0989 * the last segment of this URI's path, if any, with the given URI's
  • 0990 * path and then normalizing the result as if by invoking the {@link
  • 0991 * #normalize() normalize} method. </p></li>
  • 0992 *
  • 0993 * </ol>
  • 0994 *
  • 0995 * </ol>
  • 0996 *
  • 0997 * <p> The result of this method is absolute if, and only if, either this
  • 0998 * URI is absolute or the given URI is absolute. </p>
  • 0999 *
  • 1000 * @param uri The URI to be resolved against this URI
  • 1001 * @return The resulting URI
  • 1002 *
  • 1003 * @throws NullPointerException
  • 1004 * If <tt>uri</tt> is <tt>null</tt>
  • 1005 */
  • 1006 public URI resolve(URI uri) {
  • 1007 return resolve(this, uri);
  • 1008 }
  • 1009
  • 1010 /**
  • 1011 * Constructs a new URI by parsing the given string and then resolving it
  • 1012 * against this URI.
  • 1013 *
  • 1014 * <p> This convenience method works as if invoking it were equivalent to
  • 1015 * evaluating the expression <tt>{@link #resolve(java.net.URI)
  • 1016 * resolve}(URI.{@link #create(String) create}(str))</tt>. </p>
  • 1017 *
  • 1018 * @param str The string to be parsed into a URI
  • 1019 * @return The resulting URI
  • 1020 *
  • 1021 * @throws NullPointerException
  • 1022 * If <tt>str</tt> is <tt>null</tt>
  • 1023 *
  • 1024 * @throws IllegalArgumentException
  • 1025 * If the given string violates RFC 2396
  • 1026 */
  • 1027 public URI resolve(String str) {
  • 1028 return resolve(URI.create(str));
  • 1029 }
  • 1030
  • 1031 /**
  • 1032 * Relativizes the given URI against this URI.
  • 1033 *
  • 1034 * <p> The relativization of the given URI against this URI is computed as
  • 1035 * follows: </p>
  • 1036 *
  • 1037 * <ol>
  • 1038 *
  • 1039 * <li><p> If either this URI or the given URI are opaque, or if the
  • 1040 * scheme and authority components of the two URIs are not identical, or
  • 1041 * if the path of this URI is not a prefix of the path of the given URI,
  • 1042 * then the given URI is returned. </p></li>
  • 1043 *
  • 1044 * <li><p> Otherwise a new relative hierarchical URI is constructed with
  • 1045 * query and fragment components taken from the given URI and with a path
  • 1046 * component computed by removing this URI's path from the beginning of
  • 1047 * the given URI's path. </p></li>
  • 1048 *
  • 1049 * </ol>
  • 1050 *
  • 1051 * @param uri The URI to be relativized against this URI
  • 1052 * @return The resulting URI
  • 1053 *
  • 1054 * @throws NullPointerException
  • 1055 * If <tt>uri</tt> is <tt>null</tt>
  • 1056 */
  • 1057 public URI relativize(URI uri) {
  • 1058 return relativize(this, uri);
  • 1059 }
  • 1060
  • 1061 /**
  • 1062 * Constructs a URL from this URI.
  • 1063 *
  • 1064 * <p> This convenience method works as if invoking it were equivalent to
  • 1065 * evaluating the expression <tt>new URL(this.toString())</tt> after
  • 1066 * first checking that this URI is absolute. </p>
  • 1067 *
  • 1068 * @return A URL constructed from this URI
  • 1069 *
  • 1070 * @throws IllegalArgumentException
  • 1071 * If this URL is not absolute
  • 1072 *
  • 1073 * @throws MalformedURLException
  • 1074 * If a protocol handler for the URL could not be found,
  • 1075 * or if some other error occurred while constructing the URL
  • 1076 */
  • 1077 public URL toURL()
  • 1078 throws MalformedURLException {
  • 1079 if (!isAbsolute())
  • 1080 throw new IllegalArgumentException("URI is not absolute");
  • 1081 return new URL(toString());
  • 1082 }
  • 1083
  • 1084 // -- Component access methods --
  • 1085
  • 1086 /**
  • 1087 * Returns the scheme component of this URI.
  • 1088 *
  • 1089 * <p> The scheme component of a URI, if defined, only contains characters
  • 1090 * in the <i>alphanum</i> category and in the string <tt>"-.+"</tt>. A
  • 1091 * scheme always starts with an <i>alpha</i> character. <p>
  • 1092 *
  • 1093 * The scheme component of a URI cannot contain escaped octets, hence this
  • 1094 * method does not perform any decoding.
  • 1095 *
  • 1096 * @return The scheme component of this URI,
  • 1097 * or <tt>null</tt> if the scheme is undefined
  • 1098 */
  • 1099 public String getScheme() {
  • 1100 return scheme;
  • 1101 }
  • 1102
  • 1103 /**
  • 1104 * Tells whether or not this URI is absolute.
  • 1105 *
  • 1106 * <p> A URI is absolute if, and only if, it has a scheme component. </p>
  • 1107 *
  • 1108 * @return <tt>true</tt> if, and only if, this URI is absolute
  • 1109 */
  • 1110 public boolean isAbsolute() {
  • 1111 return scheme != null;
  • 1112 }
  • 1113
  • 1114 /**
  • 1115 * Tells whether or not this URI is opaque.
  • 1116 *
  • 1117 * <p> A URI is opaque if, and only if, it is absolute and its
  • 1118 * scheme-specific part does not begin with a slash character ('/').
  • 1119 * An opaque URI has a scheme, a scheme-specific part, and possibly
  • 1120 * a fragment; all other components are undefined. </p>
  • 1121 *
  • 1122 * @return <tt>true</tt> if, and only if, this URI is opaque
  • 1123 */
  • 1124 public boolean isOpaque() {
  • 1125 return path == null;
  • 1126 }
  • 1127
  • 1128 /**
  • 1129 * Returns the raw scheme-specific part of this URI. The scheme-specific
  • 1130 * part is never undefined, though it may be empty.
  • 1131 *
  • 1132 * <p> The scheme-specific part of a URI only contains legal URI
  • 1133 * characters. </p>
  • 1134 *
  • 1135 * @return The raw scheme-specific part of this URI
  • 1136 * (never <tt>null</tt>)
  • 1137 */
  • 1138 public String getRawSchemeSpecificPart() {
  • 1139 defineSchemeSpecificPart();
  • 1140 return schemeSpecificPart;
  • 1141 }
  • 1142
  • 1143 /**
  • 1144 * Returns the decoded scheme-specific part of this URI.
  • 1145 *
  • 1146 * <p> The string returned by this method is equal to that returned by the
  • 1147 * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method
  • 1148 * except that all sequences of escaped octets are <a
  • 1149 * href="#decode">decoded</a>. </p>
  • 1150 *
  • 1151 * @return The decoded scheme-specific part of this URI
  • 1152 * (never <tt>null</tt>)
  • 1153 */
  • 1154 public String getSchemeSpecificPart() {
  • 1155 if (decodedSchemeSpecificPart == null)
  • 1156 decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart());
  • 1157 return decodedSchemeSpecificPart;
  • 1158 }
  • 1159
  • 1160 /**
  • 1161 * Returns the raw authority component of this URI.
  • 1162 *
  • 1163 * <p> The authority component of a URI, if defined, only contains the
  • 1164 * commercial-at character (<tt>'@'</tt>) and characters in the
  • 1165 * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and <i>other</i>
  • 1166 * categories. If the authority is server-based then it is further
  • 1167 * constrained to have valid user-information, host, and port
  • 1168 * components. </p>
  • 1169 *
  • 1170 * @return The raw authority component of this URI,
  • 1171 * or <tt>null</tt> if the authority is undefined
  • 1172 */
  • 1173 public String getRawAuthority() {
  • 1174 return authority;
  • 1175 }
  • 1176
  • 1177 /**
  • 1178 * Returns the decoded authority component of this URI.
  • 1179 *
  • 1180 * <p> The string returned by this method is equal to that returned by the
  • 1181 * {@link #getRawAuthority() getRawAuthority} method except that all
  • 1182 * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  • 1183 *
  • 1184 * @return The decoded authority component of this URI,
  • 1185 * or <tt>null</tt> if the authority is undefined
  • 1186 */
  • 1187 public String getAuthority() {
  • 1188 if (decodedAuthority == null)
  • 1189 decodedAuthority = decode(authority);
  • 1190 return decodedAuthority;
  • 1191 }
  • 1192
  • 1193 /**
  • 1194 * Returns the raw user-information component of this URI.
  • 1195 *
  • 1196 * <p> The user-information component of a URI, if defined, only contains
  • 1197 * characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and
  • 1198 * <i>other</i> categories. </p>
  • 1199 *
  • 1200 * @return The raw user-information component of this URI,
  • 1201 * or <tt>null</tt> if the user information is undefined
  • 1202 */
  • 1203 public String getRawUserInfo() {
  • 1204 return userInfo;
  • 1205 }
  • 1206
  • 1207 /**
  • 1208 * Returns the decoded user-information component of this URI.
  • 1209 *
  • 1210 * <p> The string returned by this method is equal to that returned by the
  • 1211 * {@link #getRawUserInfo() getRawUserInfo} method except that all
  • 1212 * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  • 1213 *
  • 1214 * @return The decoded user-information component of this URI,
  • 1215 * or <tt>null</tt> if the user information is undefined
  • 1216 */
  • 1217 public String getUserInfo() {
  • 1218 if ((decodedUserInfo == null) && (userInfo != null))
  • 1219 decodedUserInfo = decode(userInfo);
  • 1220 return decodedUserInfo;
  • 1221 }
  • 1222
  • 1223 /**
  • 1224 * Returns the host component of this URI.
  • 1225 *
  • 1226 * <p> The host component of a URI, if defined, will have one of the
  • 1227 * following forms: </p>
  • 1228 *
  • 1229 * <ul type=disc>
  • 1230 *
  • 1231 * <li><p> A domain name consisting of one or more <i>labels</i>
  • 1232 * separated by period characters (<tt>'.'</tt>), optionally followed by
  • 1233 * a period character. Each label consists of <i>alphanum</i> characters
  • 1234 * as well as hyphen characters (<tt>'-'</tt>), though hyphens never
  • 1235 * occur as the first or last characters in a label. The rightmost
  • 1236 * label of a domain name consisting of two or more labels, begins
  • 1237 * with an <i>alpha</i> character. </li>
  • 1238 *
  • 1239 * <li><p> A dotted-quad IPv4 address of the form
  • 1240 * <i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+</tt>,
  • 1241 * where no <i>digit</i> sequence is longer than three characters and no
  • 1242 * sequence has a value larger than 255. </p></li>
  • 1243 *
  • 1244 * <li><p> An IPv6 address enclosed in square brackets (<tt>'['</tt> and
  • 1245 * <tt>']'</tt>) and consisting of hexadecimal digits, colon characters
  • 1246 * (<tt>':'</tt>), and possibly an embedded IPv4 address. The full
  • 1247 * syntax of IPv6 addresses is specified in <a
  • 1248 * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC 2373: IPv6
  • 1249 * Addressing Architecture</i></a>. </p></li>
  • 1250 *
  • 1251 * </ul>
  • 1252 *
  • 1253 * The host component of a URI cannot contain escaped octets, hence this
  • 1254 * method does not perform any decoding.
  • 1255 *
  • 1256 * @return The host component of this URI,
  • 1257 * or <tt>null</tt> if the host is undefined
  • 1258 */
  • 1259 public String getHost() {
  • 1260 return host;
  • 1261 }
  • 1262
  • 1263 /**
  • 1264 * Returns the port number of this URI.
  • 1265 *
  • 1266 * <p> The port component of a URI, if defined, is a non-negative
  • 1267 * integer. </p>
  • 1268 *
  • 1269 * @return The port component of this URI,
  • 1270 * or <tt>-1</tt> if the port is undefined
  • 1271 */
  • 1272 public int getPort() {
  • 1273 return port;
  • 1274 }
  • 1275
  • 1276 /**
  • 1277 * Returns the raw path component of this URI.
  • 1278 *
  • 1279 * <p> The path component of a URI, if defined, only contains the slash
  • 1280 * character (<tt>'/'</tt>), the commercial-at character (<tt>'@'</tt>),
  • 1281 * and characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>,
  • 1282 * and <i>other</i> categories. </p>
  • 1283 *
  • 1284 * @return The path component of this URI,
  • 1285 * or <tt>null</tt> if the path is undefined
  • 1286 */
  • 1287 public String getRawPath() {
  • 1288 return path;
  • 1289 }
  • 1290
  • 1291 /**
  • 1292 * Returns the decoded path component of this URI.
  • 1293 *
  • 1294 * <p> The string returned by this method is equal to that returned by the
  • 1295 * {@link #getRawPath() getRawPath} method except that all sequences of
  • 1296 * escaped octets are <a href="#decode">decoded</a>. </p>
  • 1297 *
  • 1298 * @return The decoded path component of this URI,
  • 1299 * or <tt>null</tt> if the path is undefined
  • 1300 */
  • 1301 public String getPath() {
  • 1302 if ((decodedPath == null) && (path != null))
  • 1303 decodedPath = decode(path);
  • 1304 return decodedPath;
  • 1305 }
  • 1306
  • 1307 /**
  • 1308 * Returns the raw query component of this URI.
  • 1309 *
  • 1310 * <p> The query component of a URI, if defined, only contains legal URI
  • 1311 * characters. </p>
  • 1312 *
  • 1313 * @return The raw query component of this URI,
  • 1314 * or <tt>null</tt> if the query is undefined
  • 1315 */
  • 1316 public String getRawQuery() {
  • 1317 return query;
  • 1318 }
  • 1319
  • 1320 /**
  • 1321 * Returns the decoded query component of this URI.
  • 1322 *
  • 1323 * <p> The string returned by this method is equal to that returned by the
  • 1324 * {@link #getRawQuery() getRawQuery} method except that all sequences of
  • 1325 * escaped octets are <a href="#decode">decoded</a>. </p>
  • 1326 *
  • 1327 * @return The decoded query component of this URI,
  • 1328 * or <tt>null</tt> if the query is undefined
  • 1329 */
  • 1330 public String getQuery() {
  • 1331 if ((decodedQuery == null) && (query != null))
  • 1332 decodedQuery = decode(query);
  • 1333 return decodedQuery;
  • 1334 }
  • 1335
  • 1336 /**
  • 1337 * Returns the raw fragment component of this URI.
  • 1338 *
  • 1339 * <p> The fragment component of a URI, if defined, only contains legal URI
  • 1340 * characters. </p>
  • 1341 *
  • 1342 * @return The raw fragment component of this URI,
  • 1343 * or <tt>null</tt> if the fragment is undefined
  • 1344 */
  • 1345 public String getRawFragment() {
  • 1346 return fragment;
  • 1347 }
  • 1348
  • 1349 /**
  • 1350 * Returns the decoded fragment component of this URI.
  • 1351 *
  • 1352 * <p> The string returned by this method is equal to that returned by the
  • 1353 * {@link #getRawFragment() getRawFragment} method except that all
  • 1354 * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  • 1355 *
  • 1356 * @return The decoded fragment component of this URI,
  • 1357 * or <tt>null</tt> if the fragment is undefined
  • 1358 */
  • 1359 public String getFragment() {
  • 1360 if ((decodedFragment == null) && (fragment != null))
  • 1361 decodedFragment = decode(fragment);
  • 1362 return decodedFragment;
  • 1363 }
  • 1364
  • 1365
  • 1366 // -- Equality, comparison, hash code, toString, and serialization --
  • 1367
  • 1368 /**
  • 1369 * Tests this URI for equality with another object.
  • 1370 *
  • 1371 * <p> If the given object is not a URI then this method immediately
  • 1372 * returns <tt>false</tt>.
  • 1373 *
  • 1374 * <p> For two URIs to be considered equal requires that either both are
  • 1375 * opaque or both are hierarchical. Their schemes must either both be
  • 1376 * undefined or else be equal without regard to case. Their fragments
  • 1377 * must either both be undefined or else be equal.
  • 1378 *
  • 1379 * <p> For two opaque URIs to be considered equal, their scheme-specific
  • 1380 * parts must be equal.
  • 1381 *
  • 1382 * <p> For two hierarchical URIs to be considered equal, their paths must
  • 1383 * be equal and their queries must either both be undefined or else be
  • 1384 * equal. Their authorities must either both be undefined, or both be
  • 1385 * registry-based, or both be server-based. If their authorities are
  • 1386 * defined and are registry-based, then they must be equal. If their
  • 1387 * authorities are defined and are server-based, then their hosts must be
  • 1388 * equal without regard to case, their port numbers must be equal, and
  • 1389 * their user-information components must be equal.
  • 1390 *
  • 1391 * <p> When testing the user-information, path, query, fragment, authority,
  • 1392 * or scheme-specific parts of two URIs for equality, the raw forms rather
  • 1393 * than the encoded forms of these components are compared and the
  • 1394 * hexadecimal digits of escaped octets are compared without regard to
  • 1395 * case.
  • 1396 *
  • 1397 * <p> This method satisfies the general contract of the {@link
  • 1398 * java.lang.Object#equals(Object) Object.equals} method. </p>
  • 1399 *
  • 1400 * @param ob The object to which this object is to be compared
  • 1401 *
  • 1402 * @return <tt>true</tt> if, and only if, the given object is a URI that
  • 1403 * is identical to this URI
  • 1404 */
  • 1405 public boolean equals(Object ob) {
  • 1406 if (ob == this)
  • 1407 return true;
  • 1408 if (!(ob instanceof URI))
  • 1409 return false;
  • 1410 URI that = (URI)ob;
  • 1411 if (this.isOpaque() != that.isOpaque()) return false;
  • 1412 if (!equalIgnoringCase(this.scheme, that.scheme)) return false;
  • 1413 if (!equal(this.fragment, that.fragment)) return false;
  • 1414
  • 1415 // Opaque
  • 1416 if (this.isOpaque())
  • 1417 return equal(this.schemeSpecificPart, that.schemeSpecificPart);
  • 1418
  • 1419 // Hierarchical
  • 1420 if (!equal(this.path, that.path)) return false;
  • 1421 if (!equal(this.query, that.query)) return false;
  • 1422
  • 1423 // Authorities
  • 1424 if (this.authority == that.authority) return true;
  • 1425 if (this.host != null) {
  • 1426 // Server-based
  • 1427 if (!equal(this.userInfo, that.userInfo)) return false;
  • 1428 if (!equalIgnoringCase(this.host, that.host)) return false;
  • 1429 if (this.port != that.port) return false;
  • 1430 } else if (this.authority != null) {
  • 1431 // Registry-based
  • 1432 if (!equal(this.authority, that.authority)) return false;
  • 1433 } else if (this.authority != that.authority) {
  • 1434 return false;
  • 1435 }
  • 1436
  • 1437 return true;
  • 1438 }
  • 1439
  • 1440 /**
  • 1441 * Returns a hash-code value for this URI. The hash code is based upon all
  • 1442 * of the URI's components, and satisfies the general contract of the
  • 1443 * {@link java.lang.Object#hashCode() Object.hashCode} method.
  • 1444 *
  • 1445 * @return A hash-code value for this URI
  • 1446 */
  • 1447 public int hashCode() {
  • 1448 if (hash != 0)
  • 1449 return hash;
  • 1450 int h = hashIgnoringCase(0, scheme);
  • 1451 h = hash(h, fragment);
  • 1452 if (isOpaque()) {
  • 1453 h = hash(h, schemeSpecificPart);
  • 1454 } else {
  • 1455 h = hash(h, path);
  • 1456 h = hash(h, query);
  • 1457 if (host != null) {
  • 1458 h = hash(h, userInfo);
  • 1459 h = hashIgnoringCase(h, host);
  • 1460 h += 1949 * port;
  • 1461 } else {
  • 1462 h = hash(h, authority);
  • 1463 }
  • 1464 }
  • 1465 hash = h;
  • 1466 return h;
  • 1467 }
  • 1468
  • 1469 /**
  • 1470 * Compares this URI to another object, which must be a URI.
  • 1471 *
  • 1472 * <p> When comparing corresponding components of two URIs, if one
  • 1473 * component is undefined but the other is defined then the first is
  • 1474 * considered to be less than the second. Unless otherwise noted, string
  • 1475 * components are ordered according to their natural, case-sensitive
  • 1476 * ordering as defined by the {@link java.lang.String#compareTo(Object)
  • 1477 * String.compareTo} method. String components that are subject to
  • 1478 * encoding are compared by comparing their raw forms rather than their
  • 1479 * encoded forms.
  • 1480 *
  • 1481 * <p> The ordering of URIs is defined as follows: </p>
  • 1482 *
  • 1483 * <ul type=disc>
  • 1484 *
  • 1485 * <li><p> Two URIs with different schemes are ordered according the
  • 1486 * ordering of their schemes, without regard to case. </p></li>
  • 1487 *
  • 1488 * <li><p> A hierarchical URI is considered to be less than an opaque URI
  • 1489 * with an identical scheme. </p></li>
  • 1490 *
  • 1491 * <li><p> Two opaque URIs with identical schemes are ordered according
  • 1492 * to the ordering of their scheme-specific parts. </p></li>
  • 1493 *
  • 1494 * <li><p> Two opaque URIs with identical schemes and scheme-specific
  • 1495 * parts are ordered according to the ordering of their
  • 1496 * fragments. </p></li>
  • 1497 *
  • 1498 * <li><p> Two hierarchical URIs with identical schemes are ordered
  • 1499 * according to the ordering of their authority components: </p></li>
  • 1500 *
  • 1501 * <ul type=disc>
  • 1502 *
  • 1503 * <li><p> If both authority components are server-based then the URIs
  • 1504 * are ordered according to their user-information components; if these
  • 1505 * components are identical then the URIs are ordered according to the
  • 1506 * ordering of their hosts, without regard to case; if the hosts are
  • 1507 * identical then the URIs are ordered according to the ordering of
  • 1508 * their ports. </p></li>
  • 1509 *
  • 1510 * <li><p> If one or both authority components are registry-based then
  • 1511 * the URIs are ordered according to the ordering of their authority
  • 1512 * components. </p></li>
  • 1513 *
  • 1514 * </ul>
  • 1515 *
  • 1516 * <li><p> Finally, two hierarchical URIs with identical schemes and
  • 1517 * authority components are ordered according to the ordering of their
  • 1518 * paths; if their paths are identical then they are ordered according to
  • 1519 * the ordering of their queries; if the queries are identical then they
  • 1520 * are ordered according to the order of their fragments. </p></li>
  • 1521 *
  • 1522 * </ul>
  • 1523 *
  • 1524 * <p> This method satisfies the general contract of the {@link
  • 1525 * java.lang.Comparable#compareTo(Object) Comparable.compareTo}
  • 1526 * method. </p>
  • 1527 *
  • 1528 * @param that
  • 1529 * The object to which this URI is to be compared
  • 1530 *
  • 1531 * @return A negative integer, zero, or a positive integer as this URI is
  • 1532 * less than, equal to, or greater than the given URI
  • 1533 *
  • 1534 * @throws ClassCastException
  • 1535 * If the given object is not a URI
  • 1536 */
  • 1537 public int compareTo(URI that) {
  • 1538 int c;
  • 1539
  • 1540 if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0)
  • 1541 return c;
  • 1542
  • 1543 if (this.isOpaque()) {
  • 1544 if (that.isOpaque()) {
  • 1545 // Both opaque
  • 1546 if ((c = compare(this.schemeSpecificPart,
  • 1547 that.schemeSpecificPart)) != 0)
  • 1548 return c;
  • 1549 return compare(this.fragment, that.fragment);
  • 1550 }
  • 1551 return +1; // Opaque > hierarchical
  • 1552 } else if (that.isOpaque()) {
  • 1553 return -1; // Hierarchical < opaque
  • 1554 }
  • 1555
  • 1556 // Hierarchical
  • 1557 if ((this.host != null) && (that.host != null)) {
  • 1558 // Both server-based
  • 1559 if ((c = compare(this.userInfo, that.userInfo)) != 0)
  • 1560 return c;
  • 1561 if ((c = compareIgnoringCase(this.host, that.host)) != 0)
  • 1562 return c;
  • 1563 if ((c = this.port - that.port) != 0)
  • 1564 return c;
  • 1565 } else {
  • 1566 // If one or both authorities are registry-based then we simply
  • 1567 // compare them in the usual, case-sensitive way. If one is
  • 1568 // registry-based and one is server-based then the strings are
  • 1569 // guaranteed to be unequal, hence the comparison will never return
  • 1570 // zero and the compareTo and equals methods will remain
  • 1571 // consistent.
  • 1572 if ((c = compare(this.authority, that.authority)) != 0) return c;
  • 1573 }
  • 1574
  • 1575 if ((c = compare(this.path, that.path)) != 0) return c;
  • 1576 if ((c = compare(this.query, that.query)) != 0) return c;
  • 1577 return compare(this.fragment, that.fragment);
  • 1578 }
  • 1579
  • 1580 /**
  • 1581 * Returns the content of this URI as a string.
  • 1582 *
  • 1583 * <p> If this URI was created by invoking one of the constructors in this
  • 1584 * class then a string equivalent to the original input string, or to the
  • 1585 * string computed from the originally-given components, as appropriate, is
  • 1586 * returned. Otherwise this URI was created by normalization, resolution,
  • 1587 * or relativization, and so a string is constructed from this URI's
  • 1588 * components according to the rules specified in <a
  • 1589 * href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a>,
  • 1590 * section 5.2, step 7. </p>
  • 1591 *
  • 1592 * @return The string form of this URI
  • 1593 */
  • 1594 public String toString() {
  • 1595 defineString();
  • 1596 return string;
  • 1597 }
  • 1598
  • 1599 /**
  • 1600 * Returns the content of this URI as a US-ASCII string.
  • 1601 *
  • 1602 * <p> If this URI does not contain any characters in the <i>other</i>
  • 1603 * category then an invocation of this method will return the same value as
  • 1604 * an invocation of the {@link #toString() toString} method. Otherwise
  • 1605 * this method works as if by invoking that method and then <a
  • 1606 * href="#encode">encoding</a> the result. </p>
  • 1607 *
  • 1608 * @return The string form of this URI, encoded as needed
  • 1609 * so that it only contains characters in the US-ASCII
  • 1610 * charset
  • 1611 */
  • 1612 public String toASCIIString() {
  • 1613 defineString();
  • 1614 return encode(string);
  • 1615 }
  • 1616
  • 1617
  • 1618 // -- Serialization support --
  • 1619
  • 1620 /**
  • 1621 * Saves the content of this URI to the given serial stream.
  • 1622 *
  • 1623 * <p> The only serializable field of a URI instance is its <tt>string</tt>
  • 1624 * field. That field is given a value, if it does not have one already,
  • 1625 * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()}
  • 1626 * method of the given object-output stream is invoked. </p>
  • 1627 *
  • 1628 * @param os The object-output stream to which this object
  • 1629 * is to be written
  • 1630 */
  • 1631 private void writeObject(ObjectOutputStream os)
  • 1632 throws IOException
  • 1633 {
  • 1634 defineString();
  • 1635 os.defaultWriteObject(); // Writes the string field only
  • 1636 }
  • 1637
  • 1638 /**
  • 1639 * Reconstitutes a URI from the given serial stream.
  • 1640 *
  • 1641 * <p> The {@link java.io.ObjectInputStream#defaultReadObject()} method is
  • 1642 * invoked to read the value of the <tt>string</tt> field. The result is
  • 1643 * then parsed in the usual way.
  • 1644 *
  • 1645 * @param is The object-input stream from which this object
  • 1646 * is being read
  • 1647 */
  • 1648 private void readObject(ObjectInputStream is)
  • 1649 throws ClassNotFoundException, IOException
  • 1650 {
  • 1651 port = -1; // Argh
  • 1652 is.defaultReadObject();
  • 1653 try {
  • 1654 new Parser(string).parse(false);
  • 1655 } catch (URISyntaxException x) {
  • 1656 IOException y = new InvalidObjectException("Invalid URI");
  • 1657 y.initCause(x);
  • 1658 throw y;
  • 1659 }
  • 1660 }
  • 1661
  • 1662
  • 1663 // -- End of public methods --
  • 1664
  • 1665
  • 1666 // -- Utility methods for string-field comparison and hashing --
  • 1667
  • 1668 // These methods return appropriate values for null string arguments,
  • 1669 // thereby simplifying the equals, hashCode, and compareTo methods.
  • 1670 //
  • 1671 // The case-ignoring methods should only be applied to strings whose
  • 1672 // characters are all known to be US-ASCII. Because of this restriction,
  • 1673 // these methods are faster than the similar methods in the String class.
  • 1674
  • 1675 // US-ASCII only
  • 1676 private static int toLower(char c) {
  • 1677 if ((c >= 'A') && (c <= 'Z'))
  • 1678 return c + ('a' - 'A');
  • 1679 return c;
  • 1680 }
  • 1681
  • 1682 private static boolean equal(String s, String t) {
  • 1683 if (s == t) return true;
  • 1684 if ((s != null) && (t != null)) {
  • 1685 if (s.length() != t.length())
  • 1686 return false;
  • 1687 if (s.indexOf('%') < 0)
  • 1688 return s.equals(t);
  • 1689 int n = s.length();
  • 1690 for (int i = 0; i < n;) {
  • 1691 char c = s.charAt(i);
  • 1692 char d = t.charAt(i);
  • 1693 if (c != '%') {
  • 1694 if (c != d)
  • 1695 return false;
  • 1696 i++;
  • 1697 continue;
  • 1698 }
  • 1699 i++;
  • 1700 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  • 1701 return false;
  • 1702 i++;
  • 1703 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  • 1704 return false;
  • 1705 i++;
  • 1706 }
  • 1707 return true;
  • 1708 }
  • 1709 return false;
  • 1710 }
  • 1711
  • 1712 // US-ASCII only
  • 1713 private static boolean equalIgnoringCase(String s, String t) {
  • 1714 if (s == t) return true;
  • 1715 if ((s != null) && (t != null)) {
  • 1716 int n = s.length();
  • 1717 if (t.length() != n)
  • 1718 return false;
  • 1719 for (int i = 0; i < n; i++) {
  • 1720 if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  • 1721 return false;
  • 1722 }
  • 1723 return true;
  • 1724 }
  • 1725 return false;
  • 1726 }
  • 1727
  • 1728 private static int hash(int hash, String s) {
  • 1729 if (s == null) return hash;
  • 1730 return hash * 127 + s.hashCode();
  • 1731 }
  • 1732
  • 1733 // US-ASCII only
  • 1734 private static int hashIgnoringCase(int hash, String s) {
  • 1735 if (s == null) return hash;
  • 1736 int h = hash;
  • 1737 int n = s.length();
  • 1738 for (int i = 0; i < n; i++)
  • 1739 h = 31 * h + toLower(s.charAt(i));
  • 1740 return h;
  • 1741 }
  • 1742
  • 1743 private static int compare(String s, String t) {
  • 1744 if (s == t) return 0;
  • 1745 if (s != null) {
  • 1746 if (t != null)
  • 1747 return s.compareTo(t);
  • 1748 else
  • 1749 return +1;
  • 1750 } else {
  • 1751 return -1;
  • 1752 }
  • 1753 }
  • 1754
  • 1755 // US-ASCII only
  • 1756 private static int compareIgnoringCase(String s, String t) {
  • 1757 if (s == t) return 0;
  • 1758 if (s != null) {
  • 1759 if (t != null) {
  • 1760 int sn = s.length();
  • 1761 int tn = t.length();
  • 1762 int n = sn < tn ? sn : tn;
  • 1763 for (int i = 0; i < n; i++) {
  • 1764 int c = toLower(s.charAt(i)) - toLower(t.charAt(i));
  • 1765 if (c != 0)
  • 1766 return c;
  • 1767 }
  • 1768 return sn - tn;
  • 1769 }
  • 1770 return +1;
  • 1771 } else {
  • 1772 return -1;
  • 1773 }
  • 1774 }
  • 1775
  • 1776
  • 1777 // -- String construction --
  • 1778
  • 1779 // If a scheme is given then the path, if given, must be absolute
  • 1780 //
  • 1781 private static void checkPath(String s, String scheme, String path)
  • 1782 throws URISyntaxException
  • 1783 {
  • 1784 if (scheme != null) {
  • 1785 if ((path != null)
  • 1786 && ((path.length() > 0) && (path.charAt(0) != '/')))
  • 1787 throw new URISyntaxException(s,
  • 1788 "Relative path in absolute URI");
  • 1789 }
  • 1790 }
  • 1791
  • 1792 private void appendAuthority(StringBuffer sb,
  • 1793 String authority,
  • 1794 String userInfo,
  • 1795 String host,
  • 1796 int port)
  • 1797 {
  • 1798 if (host != null) {
  • 1799 sb.append("//");
  • 1800 if (userInfo != null) {
  • 1801 sb.append(quote(userInfo, L_USERINFO, H_USERINFO));
  • 1802 sb.append('@');
  • 1803 }
  • 1804 boolean needBrackets = ((host.indexOf(':') >= 0)
  • 1805 && !host.startsWith("[")
  • 1806 && !host.endsWith("]"));
  • 1807 if (needBrackets) sb.append('[');
  • 1808 sb.append(host);
  • 1809 if (needBrackets) sb.append(']');
  • 1810 if (port != -1) {
  • 1811 sb.append(':');
  • 1812 sb.append(port);
  • 1813 }
  • 1814 } else if (authority != null) {
  • 1815 sb.append("//");
  • 1816 if (authority.startsWith("[")) {
  • 1817 int end = authority.indexOf("]");
  • 1818 if (end != -1 && authority.indexOf(":")!=-1) {
  • 1819 String doquote, dontquote;
  • 1820 if (end == authority.length()) {
  • 1821 dontquote = authority;
  • 1822 doquote = "";
  • 1823 } else {
  • 1824 dontquote = authority.substring(0,end+1);
  • 1825 doquote = authority.substring(end+1);
  • 1826 }
  • 1827 sb.append (dontquote);
  • 1828 sb.append(quote(doquote,
  • 1829 L_REG_NAME | L_SERVER,
  • 1830 H_REG_NAME | H_SERVER));
  • 1831 }
  • 1832 } else {
  • 1833 sb.append(quote(authority,
  • 1834 L_REG_NAME | L_SERVER,
  • 1835 H_REG_NAME | H_SERVER));
  • 1836 }
  • 1837 }
  • 1838 }
  • 1839
  • 1840 private void appendSchemeSpecificPart(StringBuffer sb,
  • 1841 String opaquePart,
  • 1842 String authority,
  • 1843 String userInfo,
  • 1844 String host,
  • 1845 int port,
  • 1846 String path,
  • 1847 String query)
  • 1848 {
  • 1849 if (opaquePart != null) {
  • 1850 /* check if SSP begins with an IPv6 address
  • 1851 * because we must not quote a literal IPv6 address
  • 1852 */
  • 1853 if (opaquePart.startsWith("//[")) {
  • 1854 int end = opaquePart.indexOf("]");
  • 1855 if (end != -1 && opaquePart.indexOf(":")!=-1) {
  • 1856 String doquote, dontquote;
  • 1857 if (end == opaquePart.length()) {
  • 1858 dontquote = opaquePart;
  • 1859 doquote = "";
  • 1860 } else {
  • 1861 dontquote = opaquePart.substring(0,end+1);
  • 1862 doquote = opaquePart.substring(end+1);
  • 1863 }
  • 1864 sb.append (dontquote);
  • 1865 sb.append(quote(doquote, L_URIC, H_URIC));
  • 1866 }
  • 1867 } else {
  • 1868 sb.append(quote(opaquePart, L_URIC, H_URIC));
  • 1869 }
  • 1870 } else {
  • 1871 appendAuthority(sb, authority, userInfo, host, port);
  • 1872 if (path != null)
  • 1873 sb.append(quote(path, L_PATH, H_PATH));
  • 1874 if (query != null) {
  • 1875 sb.append('?');
  • 1876 sb.append(quote(query, L_URIC, H_URIC));
  • 1877 }
  • 1878 }
  • 1879 }
  • 1880
  • 1881 private void appendFragment(StringBuffer sb, String fragment) {
  • 1882 if (fragment != null) {
  • 1883 sb.append('#');
  • 1884 sb.append(quote(fragment, L_URIC, H_URIC));
  • 1885 }
  • 1886 }
  • 1887
  • 1888 private String toString(String scheme,
  • 1889 String opaquePart,
  • 1890 String authority,
  • 1891 String userInfo,
  • 1892 String host,
  • 1893 int port,
  • 1894 String path,
  • 1895 String query,
  • 1896 String fragment)
  • 1897 {
  • 1898 StringBuffer sb = new StringBuffer();
  • 1899 if (scheme != null) {
  • 1900 sb.append(scheme);
  • 1901 sb.append(':');
  • 1902 }
  • 1903 appendSchemeSpecificPart(sb, opaquePart,
  • 1904 authority, userInfo, host, port,
  • 1905 path, query);
  • 1906 appendFragment(sb, fragment);
  • 1907 return sb.toString();
  • 1908 }
  • 1909
  • 1910 private void defineSchemeSpecificPart() {
  • 1911 if (schemeSpecificPart != null) return;
  • 1912 StringBuffer sb = new StringBuffer();
  • 1913 appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
  • 1914 host, port, getPath(), getQuery());
  • 1915 if (sb.length() == 0) return;
  • 1916 schemeSpecificPart = sb.toString();
  • 1917 }
  • 1918
  • 1919 private void defineString() {
  • 1920 if (string != null) return;
  • 1921
  • 1922 StringBuffer sb = new StringBuffer();
  • 1923 if (scheme != null) {
  • 1924 sb.append(scheme);
  • 1925 sb.append(':');
  • 1926 }
  • 1927 if (isOpaque()) {
  • 1928 sb.append(schemeSpecificPart);
  • 1929 } else {
  • 1930 if (host != null) {
  • 1931 sb.append("//");
  • 1932 if (userInfo != null) {
  • 1933 sb.append(userInfo);
  • 1934 sb.append('@');
  • 1935 }
  • 1936 boolean needBrackets = ((host.indexOf(':') >= 0)
  • 1937 && !host.startsWith("[")
  • 1938 && !host.endsWith("]"));
  • 1939 if (needBrackets) sb.append('[');
  • 1940 sb.append(host);
  • 1941 if (needBrackets) sb.append(']');
  • 1942 if (port != -1) {
  • 1943 sb.append(':');
  • 1944 sb.append(port);
  • 1945 }
  • 1946 } else if (authority != null) {
  • 1947 sb.append("//");
  • 1948 sb.append(authority);
  • 1949 }
  • 1950 if (path != null)
  • 1951 sb.append(path);
  • 1952 if (query != null) {
  • 1953 sb.append('?');
  • 1954 sb.append(query);
  • 1955 }
  • 1956 }
  • 1957 if (fragment != null) {
  • 1958 sb.append('#');
  • 1959 sb.append(fragment);
  • 1960 }
  • 1961 string = sb.toString();
  • 1962 }
  • 1963
  • 1964
  • 1965 // -- Normalization, resolution, and relativization --
  • 1966
  • 1967 // RFC2396 5.2 (6)
  • 1968 private static String resolvePath(String base, String child,
  • 1969 boolean absolute)
  • 1970 {
  • 1971 int i = base.lastIndexOf('/');
  • 1972 int cn = child.length();
  • 1973 String path = "";
  • 1974
  • 1975 if (cn == 0) {
  • 1976 // 5.2 (6a)
  • 1977 if (i >= 0)
  • 1978 path = base.substring(0, i + 1);
  • 1979 } else {
  • 1980 StringBuffer sb = new StringBuffer(base.length() + cn);
  • 1981 // 5.2 (6a)
  • 1982 if (i >= 0)
  • 1983 sb.append(base.substring(0, i + 1));
  • 1984 // 5.2 (6b)
  • 1985 sb.append(child);
  • 1986 path = sb.toString();
  • 1987 }
  • 1988
  • 1989 // 5.2 (6c-f)
  • 1990 String np = normalize(path);
  • 1991
  • 1992 // 5.2 (6g): If the result is absolute but the path begins with "../",
  • 1993 // then we simply leave the path as-is
  • 1994
  • 1995 return np;
  • 1996 }
  • 1997
  • 1998 // RFC2396 5.2
  • 1999 private static URI resolve(URI base, URI child) {
  • 2000 // check if child if opaque first so that NPE is thrown
  • 2001 // if child is null.
  • 2002 if (child.isOpaque() || base.isOpaque())
  • 2003 return child;
  • 2004
  • 2005 // 5.2 (2): Reference to current document (lone fragment)
  • 2006 if ((child.scheme == null) && (child.authority == null)
  • 2007 && child.path.equals("") && (child.fragment != null)
  • 2008 && (child.query == null)) {
  • 2009 if ((base.fragment != null)
  • 2010 && child.fragment.equals(base.fragment)) {
  • 2011 return base;
  • 2012 }
  • 2013 URI ru = new URI();
  • 2014 ru.scheme = base.scheme;
  • 2015 ru.authority = base.authority;
  • 2016 ru.userInfo = base.userInfo;
  • 2017 ru.host = base.host;
  • 2018 ru.port = base.port;
  • 2019 ru.path = base.path;
  • 2020 ru.fragment = child.fragment;
  • 2021 ru.query = base.query;
  • 2022 return ru;
  • 2023 }
  • 2024
  • 2025 // 5.2 (3): Child is absolute
  • 2026 if (child.scheme != null)
  • 2027 return child;
  • 2028
  • 2029 URI ru = new URI(); // Resolved URI
  • 2030 ru.scheme = base.scheme;
  • 2031 ru.query = child.query;
  • 2032 ru.fragment = child.fragment;
  • 2033
  • 2034 // 5.2 (4): Authority
  • 2035 if (child.authority == null) {
  • 2036 ru.authority = base.authority;
  • 2037 ru.host = base.host;
  • 2038 ru.userInfo = base.userInfo;
  • 2039 ru.port = base.port;
  • 2040
  • 2041 String cp = (child.path == null) ? "" : child.path;
  • 2042 if ((cp.length() > 0) && (cp.charAt(0) == '/')) {
  • 2043 // 5.2 (5): Child path is absolute
  • 2044 ru.path = child.path;
  • 2045 } else {
  • 2046 // 5.2 (6): Resolve relative path
  • 2047 ru.path = resolvePath(base.path, cp, base.isAbsolute());
  • 2048 }
  • 2049 } else {
  • 2050 ru.authority = child.authority;
  • 2051 ru.host = child.host;
  • 2052 ru.userInfo = child.userInfo;
  • 2053 ru.host = child.host;
  • 2054 ru.port = child.port;
  • 2055 ru.path = child.path;
  • 2056 }
  • 2057
  • 2058 // 5.2 (7): Recombine (nothing to do here)
  • 2059 return ru;
  • 2060 }
  • 2061
  • 2062 // If the given URI's path is normal then return the URI;
  • 2063 // o.w., return a new URI containing the normalized path.
  • 2064 //
  • 2065 private static URI normalize(URI u) {
  • 2066 if (u.isOpaque() || (u.path == null) || (u.path.length() == 0))
  • 2067 return u;
  • 2068
  • 2069 String np = normalize(u.path);
  • 2070 if (np == u.path)
  • 2071 return u;
  • 2072
  • 2073 URI v = new URI();
  • 2074 v.scheme = u.scheme;
  • 2075 v.fragment = u.fragment;
  • 2076 v.authority = u.authority;
  • 2077 v.userInfo = u.userInfo;
  • 2078 v.host = u.host;
  • 2079 v.port = u.port;
  • 2080 v.path = np;
  • 2081 v.query = u.query;
  • 2082 return v;
  • 2083 }
  • 2084
  • 2085 // If both URIs are hierarchical, their scheme and authority components are
  • 2086 // identical, and the base path is a prefix of the child's path, then
  • 2087 // return a relative URI that, when resolved against the base, yields the
  • 2088 // child; otherwise, return the child.
  • 2089 //
  • 2090 private static URI relativize(URI base, URI child) {
  • 2091 // check if child if opaque first so that NPE is thrown
  • 2092 // if child is null.
  • 2093 if (child.isOpaque() || base.isOpaque())
  • 2094 return child;
  • 2095 if (!equalIgnoringCase(base.scheme, child.scheme)
  • 2096 || !equal(base.authority, child.authority))
  • 2097 return child;
  • 2098
  • 2099 String bp = normalize(base.path);
  • 2100 String cp = normalize(child.path);
  • 2101 if (!bp.equals(cp)) {
  • 2102 if (!bp.endsWith("/"))
  • 2103 bp = bp + "/";
  • 2104 if (!cp.startsWith(bp))
  • 2105 return child;
  • 2106 }
  • 2107
  • 2108 URI v = new URI();
  • 2109 v.path = cp.substring(bp.length());
  • 2110 v.query = child.query;
  • 2111 v.fragment = child.fragment;
  • 2112 return v;
  • 2113 }
  • 2114
  • 2115
  • 2116
  • 2117 // -- Path normalization --
  • 2118
  • 2119 // The following algorithm for path normalization avoids the creation of a
  • 2120 // string object for each segment, as well as the use of a string buffer to
  • 2121 // compute the final result, by using a single char array and editing it in
  • 2122 // place. The array is first split into segments, replacing each slash
  • 2123 // with '\0' and creating a segment-index array, each element of which is
  • 2124 // the index of the first char in the corresponding segment. We then walk
  • 2125 // through both arrays, removing ".", "..", and other segments as necessary
  • 2126 // by setting their entries in the index array to -1. Finally, the two
  • 2127 // arrays are used to rejoin the segments and compute the final result.
  • 2128 //
  • 2129 // This code is based upon src/solaris/native/java/io/canonicalize_md.c
  • 2130
  • 2131
  • 2132 // Check the given path to see if it might need normalization. A path
  • 2133 // might need normalization if it contains duplicate slashes, a "."
  • 2134 // segment, or a ".." segment. Return -1 if no further normalization is
  • 2135 // possible, otherwise return the number of segments found.
  • 2136 //
  • 2137 // This method takes a string argument rather than a char array so that
  • 2138 // this test can be performed without invoking path.toCharArray().
  • 2139 //
  • 2140 static private int needsNormalization(String path) {
  • 2141 boolean normal = true;
  • 2142 int ns = 0; // Number of segments
  • 2143 int end = path.length() - 1; // Index of last char in path
  • 2144 int p = 0; // Index of next char in path
  • 2145
  • 2146 // Skip initial slashes
  • 2147 while (p <= end) {
  • 2148 if (path.charAt(p) != '/') break;
  • 2149 p++;
  • 2150 }
  • 2151 if (p > 1) normal = false;
  • 2152
  • 2153 // Scan segments
  • 2154 while (p <= end) {
  • 2155
  • 2156 // Looking at "." or ".." ?
  • 2157 if ((path.charAt(p) == '.')
  • 2158 && ((p == end)
  • 2159 || ((path.charAt(p + 1) == '/')
  • 2160 || ((path.charAt(p + 1) == '.')
  • 2161 && ((p + 1 == end)
  • 2162 || (path.charAt(p + 2) == '/')))))) {
  • 2163 normal = false;
  • 2164 }
  • 2165 ns++;
  • 2166
  • 2167 // Find beginning of next segment
  • 2168 while (p <= end) {
  • 2169 if (path.charAt(p++) != '/')
  • 2170 continue;
  • 2171
  • 2172 // Skip redundant slashes
  • 2173 while (p <= end) {
  • 2174 if (path.charAt(p) != '/') break;
  • 2175 normal = false;
  • 2176 p++;
  • 2177 }
  • 2178
  • 2179 break;
  • 2180 }
  • 2181 }
  • 2182
  • 2183 return normal ? -1 : ns;
  • 2184 }
  • 2185
  • 2186
  • 2187 // Split the given path into segments, replacing slashes with nulls and
  • 2188 // filling in the given segment-index array.
  • 2189 //
  • 2190 // Preconditions:
  • 2191 // segs.length == Number of segments in path
  • 2192 //
  • 2193 // Postconditions:
  • 2194 // All slashes in path replaced by '\0'
  • 2195 // segs[i] == Index of first char in segment i (0 <= i < segs.length)
  • 2196 //
  • 2197 static private void split(char[] path, int[] segs) {
  • 2198 int end = path.length - 1; // Index of last char in path
  • 2199 int p = 0; // Index of next char in path
  • 2200 int i = 0; // Index of current segment
  • 2201
  • 2202 // Skip initial slashes
  • 2203 while (p <= end) {
  • 2204 if (path[p] != '/') break;
  • 2205 path[p] = '\0';
  • 2206 p++;
  • 2207 }
  • 2208
  • 2209 while (p <= end) {
  • 2210
  • 2211 // Note start of segment
  • 2212 segs[i++] = p++;
  • 2213
  • 2214 // Find beginning of next segment
  • 2215 while (p <= end) {
  • 2216 if (path[p++] != '/')
  • 2217 continue;
  • 2218 path[p - 1] = '\0';
  • 2219
  • 2220 // Skip redundant slashes
  • 2221 while (p <= end) {
  • 2222 if (path[p] != '/') break;
  • 2223 path[p++] = '\0';
  • 2224 }
  • 2225 break;
  • 2226 }
  • 2227 }
  • 2228
  • 2229 if (i != segs.length)
  • 2230 throw new InternalError(); // ASSERT
  • 2231 }
  • 2232
  • 2233
  • 2234 // Join the segments in the given path according to the given segment-index
  • 2235 // array, ignoring those segments whose index entries have been set to -1,
  • 2236 // and inserting slashes as needed. Return the length of the resulting
  • 2237 // path.
  • 2238 //
  • 2239 // Preconditions:
  • 2240 // segs[i] == -1 implies segment i is to be ignored
  • 2241 // path computed by split, as above, with '\0' having replaced '/'
  • 2242 //
  • 2243 // Postconditions:
  • 2244 // path[0] .. path[return value] == Resulting path
  • 2245 //
  • 2246 static private int join(char[] path, int[] segs) {
  • 2247 int ns = segs.length; // Number of segments
  • 2248 int end = path.length - 1; // Index of last char in path
  • 2249 int p = 0; // Index of next path char to write
  • 2250
  • 2251 if (path[p] == '\0') {
  • 2252 // Restore initial slash for absolute paths
  • 2253 path[p++] = '/';
  • 2254 }
  • 2255
  • 2256 for (int i = 0; i < ns; i++) {
  • 2257 int q = segs[i]; // Current segment
  • 2258 if (q == -1)
  • 2259 // Ignore this segment
  • 2260 continue;
  • 2261
  • 2262 if (p == q) {
  • 2263 // We're already at this segment, so just skip to its end
  • 2264 while ((p <= end) && (path[p] != '\0'))
  • 2265 p++;
  • 2266 if (p <= end) {
  • 2267 // Preserve trailing slash
  • 2268 path[p++] = '/';
  • 2269 }
  • 2270 } else if (p < q) {
  • 2271 // Copy q down to p
  • 2272 while ((q <= end) && (path[q] != '\0'))
  • 2273 path[p++] = path[q++];
  • 2274 if (q <= end) {
  • 2275 // Preserve trailing slash
  • 2276 path[p++] = '/';
  • 2277 }
  • 2278 } else
  • 2279 throw new InternalError(); // ASSERT false
  • 2280 }
  • 2281
  • 2282 return p;
  • 2283 }
  • 2284
  • 2285
  • 2286 // Remove "." segments from the given path, and remove segment pairs
  • 2287 // consisting of a non-".." segment followed by a ".." segment.
  • 2288 //
  • 2289 private static void removeDots(char[] path, int[] segs) {
  • 2290 int ns = segs.length;
  • 2291 int end = path.length - 1;
  • 2292
  • 2293 for (int i = 0; i < ns; i++) {
  • 2294 int dots = 0; // Number of dots found (0, 1, or 2)
  • 2295
  • 2296 // Find next occurrence of "." or ".."
  • 2297 do {
  • 2298 int p = segs[i];
  • 2299 if (path[p] == '.') {
  • 2300 if (p == end) {
  • 2301 dots = 1;
  • 2302 break;
  • 2303 } else if (path[p + 1] == '\0') {
  • 2304 dots = 1;
  • 2305 break;
  • 2306 } else if ((path[p + 1] == '.')
  • 2307 && ((p + 1 == end)
  • 2308 || (path[p + 2] == '\0'))) {
  • 2309 dots = 2;
  • 2310 break;
  • 2311 }
  • 2312 }
  • 2313 i++;
  • 2314 } while (i < ns);
  • 2315 if ((i > ns) || (dots == 0))
  • 2316 break;
  • 2317
  • 2318 if (dots == 1) {
  • 2319 // Remove this occurrence of "."
  • 2320 segs[i] = -1;
  • 2321 } else {
  • 2322 // If there is a preceding non-".." segment, remove both that
  • 2323 // segment and this occurrence of ".."; otherwise, leave this
  • 2324 // ".." segment as-is.
  • 2325 int j;
  • 2326 for (j = i - 1; j >= 0; j--) {
  • 2327 if (segs[j] != -1) break;
  • 2328 }
  • 2329 if (j >= 0) {
  • 2330 int q = segs[j];
  • 2331 if (!((path[q] == '.')
  • 2332 && (path[q + 1] == '.')
  • 2333 && (path[q + 2] == '\0'))) {
  • 2334 segs[i] = -1;
  • 2335 segs[j] = -1;
  • 2336 }
  • 2337 }
  • 2338 }
  • 2339 }
  • 2340 }
  • 2341
  • 2342
  • 2343 // DEVIATION: If the normalized path is relative, and if the first
  • 2344 // segment could be parsed as a scheme name, then prepend a "." segment
  • 2345 //
  • 2346 private static void maybeAddLeadingDot(char[] path, int[] segs) {
  • 2347
  • 2348 if (path[0] == '\0')
  • 2349 // The path is absolute
  • 2350 return;
  • 2351
  • 2352 int ns = segs.length;
  • 2353 int f = 0; // Index of first segment
  • 2354 while (f < ns) {
  • 2355 if (segs[f] >= 0)
  • 2356 break;
  • 2357 f++;
  • 2358 }
  • 2359 if ((f >= ns) || (f == 0))
  • 2360 // The path is empty, or else the original first segment survived,
  • 2361 // in which case we already know that no leading "." is needed
  • 2362 return;
  • 2363
  • 2364 int p = segs[f];
  • 2365 while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++;
  • 2366 if (p >= path.length || path[p] == '\0')
  • 2367 // No colon in first segment, so no "." needed
  • 2368 return;
  • 2369
  • 2370 // At this point we know that the first segment is unused,
  • 2371 // hence we can insert a "." segment at that position
  • 2372 path[0] = '.';
  • 2373 path[1] = '\0';
  • 2374 segs[0] = 0;
  • 2375 }
  • 2376
  • 2377
  • 2378 // Normalize the given path string. A normal path string has no empty
  • 2379 // segments (i.e., occurrences of "//"), no segments equal to ".", and no
  • 2380 // segments equal to ".." that are preceded by a segment not equal to "..".
  • 2381 // In contrast to Unix-style pathname normalization, for URI paths we
  • 2382 // always retain trailing slashes.
  • 2383 //
  • 2384 private static String normalize(String ps) {
  • 2385
  • 2386 // Does this path need normalization?
  • 2387 int ns = needsNormalization(ps); // Number of segments
  • 2388 if (ns < 0)
  • 2389 // Nope -- just return it
  • 2390 return ps;
  • 2391
  • 2392 char[] path = ps.toCharArray(); // Path in char-array form
  • 2393
  • 2394 // Split path into segments
  • 2395 int[] segs = new int[ns]; // Segment-index array
  • 2396 split(path, segs);
  • 2397
  • 2398 // Remove dots
  • 2399 removeDots(path, segs);
  • 2400
  • 2401 // Prevent scheme-name confusion
  • 2402 maybeAddLeadingDot(path, segs);
  • 2403
  • 2404 // Join the remaining segments and return the result
  • 2405 String s = new String(path, 0, join(path, segs));
  • 2406 if (s.equals(ps)) {
  • 2407 // string was already normalized
  • 2408 return ps;
  • 2409 }
  • 2410 return s;
  • 2411 }
  • 2412
  • 2413
  • 2414
  • 2415 // -- Character classes for parsing --
  • 2416
  • 2417 // RFC2396 precisely specifies which characters in the US-ASCII charset are
  • 2418 // permissible in the various components of a URI reference. We here
  • 2419 // define a set of mask pairs to aid in enforcing these restrictions. Each
  • 2420 // mask pair consists of two longs, a low mask and a high mask. Taken
  • 2421 // together they represent a 128-bit mask, where bit i is set iff the
  • 2422 // character with value i is permitted.
  • 2423 //
  • 2424 // This approach is more efficient than sequentially searching arrays of
  • 2425 // permitted characters. It could be made still more efficient by
  • 2426 // precompiling the mask information so that a character's presence in a
  • 2427 // given mask could be determined by a single table lookup.
  • 2428
  • 2429 // Compute the low-order mask for the characters in the given string
  • 2430 private static long lowMask(String chars) {
  • 2431 int n = chars.length();
  • 2432 long m = 0;
  • 2433 for (int i = 0; i < n; i++) {
  • 2434 char c = chars.charAt(i);
  • 2435 if (c < 64)
  • 2436 m |= (1L << c);
  • 2437 }
  • 2438 return m;
  • 2439 }
  • 2440
  • 2441 // Compute the high-order mask for the characters in the given string
  • 2442 private static long highMask(String chars) {
  • 2443 int n = chars.length();
  • 2444 long m = 0;
  • 2445 for (int i = 0; i < n; i++) {
  • 2446 char c = chars.charAt(i);
  • 2447 if ((c >= 64) && (c < 128))
  • 2448 m |= (1L << (c - 64));
  • 2449 }
  • 2450 return m;
  • 2451 }
  • 2452
  • 2453 // Compute a low-order mask for the characters
  • 2454 // between first and last, inclusive
  • 2455 private static long lowMask(char first, char last) {
  • 2456 long m = 0;
  • 2457 int f = Math.max(Math.min(first, 63), 0);
  • 2458 int l = Math.max(Math.min(last, 63), 0);
  • 2459 for (int i = f; i <= l; i++)
  • 2460 m |= 1L << i;
  • 2461 return m;
  • 2462 }
  • 2463
  • 2464 // Compute a high-order mask for the characters
  • 2465 // between first and last, inclusive
  • 2466 private static long highMask(char first, char last) {
  • 2467 long m = 0;
  • 2468 int f = Math.max(Math.min(first, 127), 64) - 64;
  • 2469 int l = Math.max(Math.min(last, 127), 64) - 64;
  • 2470 for (int i = f; i <= l; i++)
  • 2471 m |= 1L << i;
  • 2472 return m;
  • 2473 }
  • 2474
  • 2475 // Tell whether the given character is permitted by the given mask pair
  • 2476 private static boolean match(char c, long lowMask, long highMask) {
  • 2477 if (c < 64)
  • 2478 return ((1L << c) & lowMask) != 0;
  • 2479 if (c < 128)
  • 2480 return ((1L << (c - 64)) & highMask) != 0;
  • 2481 return false;
  • 2482 }
  • 2483
  • 2484 // Character-class masks, in reverse order from RFC2396 because
  • 2485 // initializers for static fields cannot make forward references.
  • 2486
  • 2487 // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
  • 2488 // "8" | "9"
  • 2489 private static final long L_DIGIT = lowMask('0', '9');
  • 2490 private static final long H_DIGIT = 0L;
  • 2491
  • 2492 // upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
  • 2493 // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
  • 2494 // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
  • 2495 private static final long L_UPALPHA = 0L;
  • 2496 private static final long H_UPALPHA = highMask('A', 'Z');
  • 2497
  • 2498 // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
  • 2499 // "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
  • 2500 // "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
  • 2501 private static final long L_LOWALPHA = 0L;
  • 2502 private static final long H_LOWALPHA = highMask('a', 'z');
  • 2503
  • 2504 // alpha = lowalpha | upalpha
  • 2505 private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
  • 2506 private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
  • 2507
  • 2508 // alphanum = alpha | digit
  • 2509 private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
  • 2510 private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
  • 2511
  • 2512 // hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
  • 2513 // "a" | "b" | "c" | "d" | "e" | "f"
  • 2514 private static final long L_HEX = L_DIGIT;
  • 2515 private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f');
  • 2516
  • 2517 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
  • 2518 // "(" | ")"
  • 2519 private static final long L_MARK = lowMask("-_.!~*'()");
  • 2520 private static final long H_MARK = highMask("-_.!~*'()");
  • 2521
  • 2522 // unreserved = alphanum | mark
  • 2523 private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
  • 2524 private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
  • 2525
  • 2526 // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  • 2527 // "$" | "," | "[" | "]"
  • 2528 // Added per RFC2732: "[", "]"
  • 2529 private static final long L_RESERVED = lowMask(";/?:@&=+$,[]");
  • 2530 private static final long H_RESERVED = highMask(";/?:@&=+$,[]");
  • 2531
  • 2532 // The zero'th bit is used to indicate that escape pairs and non-US-ASCII
  • 2533 // characters are allowed; this is handled by the scanEscape method below.
  • 2534 private static final long L_ESCAPED = 1L;
  • 2535 private static final long H_ESCAPED = 0L;
  • 2536
  • 2537 // uric = reserved | unreserved | escaped
  • 2538 private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED;
  • 2539 private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED;
  • 2540
  • 2541 // pchar = unreserved | escaped |
  • 2542 // ":" | "@" | "&" | "=" | "+" | "$" | ","
  • 2543 private static final long L_PCHAR
  • 2544 = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,");
  • 2545 private static final long H_PCHAR
  • 2546 = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,");
  • 2547
  • 2548 // All valid path characters
  • 2549 private static final long L_PATH = L_PCHAR | lowMask(";/");
  • 2550 private static final long H_PATH = H_PCHAR | highMask(";/");
  • 2551
  • 2552 // Dash, for use in domainlabel and toplabel
  • 2553 private static final long L_DASH = lowMask("-");
  • 2554 private static final long H_DASH = highMask("-");
  • 2555
  • 2556 // Dot, for use in hostnames
  • 2557 private static final long L_DOT = lowMask(".");
  • 2558 private static final long H_DOT = highMask(".");
  • 2559
  • 2560 // userinfo = *( unreserved | escaped |
  • 2561 // ";" | ":" | "&" | "=" | "+" | "$" | "," )
  • 2562 private static final long L_USERINFO
  • 2563 = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,");
  • 2564 private static final long H_USERINFO
  • 2565 = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,");
  • 2566
  • 2567 // reg_name = 1*( unreserved | escaped | "$" | "," |
  • 2568 // ";" | ":" | "@" | "&" | "=" | "+" )
  • 2569 private static final long L_REG_NAME
  • 2570 = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+");
  • 2571 private static final long H_REG_NAME
  • 2572 = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+");
  • 2573
  • 2574 // All valid characters for server-based authorities
  • 2575 private static final long L_SERVER
  • 2576 = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]");
  • 2577 private static final long H_SERVER
  • 2578 = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]");
  • 2579
  • 2580 // Special case of server authority that represents an IPv6 address
  • 2581 // In this case, a % does not signify an escape sequence
  • 2582 private static final long L_SERVER_PERCENT
  • 2583 = L_SERVER | lowMask("%");
  • 2584 private static final long H_SERVER_PERCENT
  • 2585 = H_SERVER | highMask("%");
  • 2586 private static final long L_LEFT_BRACKET = lowMask("[");
  • 2587 private static final long H_LEFT_BRACKET = highMask("[");
  • 2588
  • 2589 // scheme = alpha *( alpha | digit | "+" | "-" | "." )
  • 2590 private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-.");
  • 2591 private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-.");
  • 2592
  • 2593 // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
  • 2594 // "&" | "=" | "+" | "$" | ","
  • 2595 private static final long L_URIC_NO_SLASH
  • 2596 = L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,");
  • 2597 private static final long H_URIC_NO_SLASH
  • 2598 = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,");
  • 2599
  • 2600
  • 2601 // -- Escaping and encoding --
  • 2602
  • 2603 private final static char[] hexDigits = {
  • 2604 '0', '1', '2', '3', '4', '5', '6', '7',
  • 2605 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  • 2606 };
  • 2607
  • 2608 private static void appendEscape(StringBuffer sb, byte b) {
  • 2609 sb.append('%');
  • 2610 sb.append(hexDigits[(b >> 4) & 0x0f]);
  • 2611 sb.append(hexDigits[(b >> 0) & 0x0f]);
  • 2612 }
  • 2613
  • 2614 private static void appendEncoded(StringBuffer sb, char c) {
  • 2615 ByteBuffer bb = null;
  • 2616 try {
  • 2617 bb = ThreadLocalCoders.encoderFor("UTF-8")
  • 2618 .encode(CharBuffer.wrap("" + c));
  • 2619 } catch (CharacterCodingException x) {
  • 2620 assert false;
  • 2621 }
  • 2622 while (bb.hasRemaining()) {
  • 2623 int b = bb.get() & 0xff;
  • 2624 if (b >= 0x80)
  • 2625 appendEscape(sb, (byte)b);
  • 2626 else
  • 2627 sb.append((char)b);
  • 2628 }
  • 2629 }
  • 2630
  • 2631 // Quote any characters in s that are not permitted
  • 2632 // by the given mask pair
  • 2633 //
  • 2634 private static String quote(String s, long lowMask, long highMask) {
  • 2635 int n = s.length();
  • 2636 StringBuffer sb = null;
  • 2637 boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
  • 2638 for (int i = 0; i < s.length(); i++) {
  • 2639 char c = s.charAt(i);
  • 2640 if (c < '\u0080') {
  • 2641 if (!match(c, lowMask, highMask)) {
  • 2642 if (sb == null) {
  • 2643 sb = new StringBuffer();
  • 2644 sb.append(s.substring(0, i));
  • 2645 }
  • 2646 appendEscape(sb, (byte)c);
  • 2647 } else {
  • 2648 if (sb != null)
  • 2649 sb.append(c);
  • 2650 }
  • 2651 } else if (allowNonASCII
  • 2652 && (Character.isSpaceChar(c)
  • 2653 || Character.isISOControl(c))) {
  • 2654 if (sb == null) {
  • 2655 sb = new StringBuffer();
  • 2656 sb.append(s.substring(0, i));
  • 2657 }
  • 2658 appendEncoded(sb, c);
  • 2659 } else {
  • 2660 if (sb != null)
  • 2661 sb.append(c);
  • 2662 }
  • 2663 }
  • 2664 return (sb == null) ? s : sb.toString();
  • 2665 }
  • 2666
  • 2667 // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets,
  • 2668 // assuming that s is otherwise legal
  • 2669 //
  • 2670 private static String encode(String s) {
  • 2671 int n = s.length();
  • 2672 if (n == 0)
  • 2673 return s;
  • 2674
  • 2675 // First check whether we actually need to encode
  • 2676 for (int i = 0;;) {
  • 2677 if (s.charAt(i) >= '\u0080')
  • 2678 break;
  • 2679 if (++i >= n)
  • 2680 return s;
  • 2681 }
  • 2682
  • 2683 String ns = Normalizer.normalize(s, Normalizer.Form.NFC);
  • 2684 ByteBuffer bb = null;
  • 2685 try {
  • 2686 bb = ThreadLocalCoders.encoderFor("UTF-8")
  • 2687 .encode(CharBuffer.wrap(ns));
  • 2688 } catch (CharacterCodingException x) {
  • 2689 assert false;
  • 2690 }
  • 2691
  • 2692 StringBuffer sb = new StringBuffer();
  • 2693 while (bb.hasRemaining()) {
  • 2694 int b = bb.get() & 0xff;
  • 2695 if (b >= 0x80)
  • 2696 appendEscape(sb, (byte)b);
  • 2697 else
  • 2698 sb.append((char)b);
  • 2699 }
  • 2700 return sb.toString();
  • 2701 }
  • 2702
  • 2703 private static int decode(char c) {
  • 2704 if ((c >= '0') && (c <= '9'))
  • 2705 return c - '0';
  • 2706 if ((c >= 'a') && (c <= 'f'))
  • 2707 return c - 'a' + 10;
  • 2708 if ((c >= 'A') && (c <= 'F'))
  • 2709 return c - 'A' + 10;
  • 2710 assert false;
  • 2711 return -1;
  • 2712 }
  • 2713
  • 2714 private static byte decode(char c1, char c2) {
  • 2715 return (byte)( ((decode(c1) & 0xf) << 4)
  • 2716 | ((decode(c2) & 0xf) << 0));
  • 2717 }
  • 2718
  • 2719 // Evaluates all escapes in s, applying UTF-8 decoding if needed. Assumes
  • 2720 // that escapes are well-formed syntactically, i.e., of the form %XX. If a
  • 2721 // sequence of escaped octets is not valid UTF-8 then the erroneous octets
  • 2722 // are replaced with '\uFFFD'.
  • 2723 // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal
  • 2724 // with a scope_id
  • 2725 //
  • 2726 private static String decode(String s) {
  • 2727 if (s == null)
  • 2728 return s;
  • 2729 int n = s.length();
  • 2730 if (n == 0)
  • 2731 return s;
  • 2732 if (s.indexOf('%') < 0)
  • 2733 return s;
  • 2734
  • 2735 byte[] ba = new byte[n];
  • 2736 StringBuffer sb = new StringBuffer(n);
  • 2737 ByteBuffer bb = ByteBuffer.allocate(n);
  • 2738 CharBuffer cb = CharBuffer.allocate(n);
  • 2739 CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8")
  • 2740 .onMalformedInput(CodingErrorAction.REPLACE)
  • 2741 .onUnmappableCharacter(CodingErrorAction.REPLACE);
  • 2742
  • 2743 // This is not horribly efficient, but it will do for now
  • 2744 char c = s.charAt(0);
  • 2745 boolean betweenBrackets = false;
  • 2746
  • 2747 for (int i = 0; i < n;) {
  • 2748 assert c == s.charAt(i); // Loop invariant
  • 2749 if (c == '[') {
  • 2750 betweenBrackets = true;
  • 2751 } else if (betweenBrackets && c == ']') {
  • 2752 betweenBrackets = false;
  • 2753 }
  • 2754 if (c != '%' || betweenBrackets) {
  • 2755 sb.append(c);
  • 2756 if (++i >= n)
  • 2757 break;
  • 2758 c = s.charAt(i);
  • 2759 continue;
  • 2760 }
  • 2761 bb.clear();
  • 2762 int ui = i;
  • 2763 for (;;) {
  • 2764 assert (n - i >= 2);
  • 2765 bb.put(decode(s.charAt(++i), s.charAt(++i)));
  • 2766 if (++i >= n)
  • 2767 break;
  • 2768 c = s.charAt(i);
  • 2769 if (c != '%')
  • 2770 break;
  • 2771 }
  • 2772 bb.flip();
  • 2773 cb.clear();
  • 2774 dec.reset();
  • 2775 CoderResult cr = dec.decode(bb, cb, true);
  • 2776 assert cr.isUnderflow();
  • 2777 cr = dec.flush(cb);
  • 2778 assert cr.isUnderflow();
  • 2779 sb.append(cb.flip().toString());
  • 2780 }
  • 2781
  • 2782 return sb.toString();
  • 2783 }
  • 2784
  • 2785
  • 2786 // -- Parsing --
  • 2787
  • 2788 // For convenience we wrap the input URI string in a new instance of the
  • 2789 // following internal class. This saves always having to pass the input
  • 2790 // string as an argument to each internal scan/parse method.
  • 2791
  • 2792 private class Parser {
  • 2793
  • 2794 private String input; // URI input string
  • 2795 private boolean requireServerAuthority = false;
  • 2796
  • 2797 Parser(String s) {
  • 2798 input = s;
  • 2799 string = s;
  • 2800 }
  • 2801
  • 2802 // -- Methods for throwing URISyntaxException in various ways --
  • 2803
  • 2804 private void fail(String reason) throws URISyntaxException {
  • 2805 throw new URISyntaxException(input, reason);
  • 2806 }
  • 2807
  • 2808 private void fail(String reason, int p) throws URISyntaxException {
  • 2809 throw new URISyntaxException(input, reason, p);
  • 2810 }
  • 2811
  • 2812 private void failExpecting(String expected, int p)
  • 2813 throws URISyntaxException
  • 2814 {
  • 2815 fail("Expected " + expected, p);
  • 2816 }
  • 2817
  • 2818 private void failExpecting(String expected, String prior, int p)
  • 2819 throws URISyntaxException
  • 2820 {
  • 2821 fail("Expected " + expected + " following " + prior, p);
  • 2822 }
  • 2823
  • 2824
  • 2825 // -- Simple access to the input string --
  • 2826
  • 2827 // Return a substring of the input string
  • 2828 //
  • 2829 private String substring(int start, int end) {
  • 2830 return input.substring(start, end);
  • 2831 }
  • 2832
  • 2833 // Return the char at position p,
  • 2834 // assuming that p < input.length()
  • 2835 //
  • 2836 private char charAt(int p) {
  • 2837 return input.charAt(p);
  • 2838 }
  • 2839
  • 2840 // Tells whether start < end and, if so, whether charAt(start) == c
  • 2841 //
  • 2842 private boolean at(int start, int end, char c) {
  • 2843 return (start < end) && (charAt(start) == c);
  • 2844 }
  • 2845
  • 2846 // Tells whether start + s.length() < end and, if so,
  • 2847 // whether the chars at the start position match s exactly
  • 2848 //
  • 2849 private boolean at(int start, int end, String s) {
  • 2850 int p = start;
  • 2851 int sn = s.length();
  • 2852 if (sn > end - p)
  • 2853 return false;
  • 2854 int i = 0;
  • 2855 while (i < sn) {
  • 2856 if (charAt(p++) != s.charAt(i)) {
  • 2857 break;
  • 2858 }
  • 2859 i++;
  • 2860 }
  • 2861 return (i == sn);
  • 2862 }
  • 2863
  • 2864
  • 2865 // -- Scanning --
  • 2866
  • 2867 // The various scan and parse methods that follow use a uniform
  • 2868 // convention of taking the current start position and end index as
  • 2869 // their first two arguments. The start is inclusive while the end is
  • 2870 // exclusive, just as in the String class, i.e., a start/end pair
  • 2871 // denotes the left-open interval [start, end) of the input string.
  • 2872 //
  • 2873 // These methods never proceed past the end position. They may return
  • 2874 // -1 to indicate outright failure, but more often they simply return
  • 2875 // the position of the first char after the last char scanned. Thus
  • 2876 // a typical idiom is
  • 2877 //
  • 2878 // int p = start;
  • 2879 // int q = scan(p, end, ...);
  • 2880 // if (q > p)
  • 2881 // // We scanned something
  • 2882 // ...;
  • 2883 // else if (q == p)
  • 2884 // // We scanned nothing
  • 2885 // ...;
  • 2886 // else if (q == -1)
  • 2887 // // Something went wrong
  • 2888 // ...;
  • 2889
  • 2890
  • 2891 // Scan a specific char: If the char at the given start position is
  • 2892 // equal to c, return the index of the next char; otherwise, return the
  • 2893 // start position.
  • 2894 //
  • 2895 private int scan(int start, int end, char c) {
  • 2896 if ((start < end) && (charAt(start) == c))
  • 2897 return start + 1;
  • 2898 return start;
  • 2899 }
  • 2900
  • 2901 // Scan forward from the given start position. Stop at the first char
  • 2902 // in the err string (in which case -1 is returned), or the first char
  • 2903 // in the stop string (in which case the index of the preceding char is
  • 2904 // returned), or the end of the input string (in which case the length
  • 2905 // of the input string is returned). May return the start position if
  • 2906 // nothing matches.
  • 2907 //
  • 2908 private int scan(int start, int end, String err, String stop) {
  • 2909 int p = start;
  • 2910 while (p < end) {
  • 2911 char c = charAt(p);
  • 2912 if (err.indexOf(c) >= 0)
  • 2913 return -1;
  • 2914 if (stop.indexOf(c) >= 0)
  • 2915 break;
  • 2916 p++;
  • 2917 }
  • 2918 return p;
  • 2919 }
  • 2920
  • 2921 // Scan a potential escape sequence, starting at the given position,
  • 2922 // with the given first char (i.e., charAt(start) == c).
  • 2923 //
  • 2924 // This method assumes that if escapes are allowed then visible
  • 2925 // non-US-ASCII chars are also allowed.
  • 2926 //
  • 2927 private int scanEscape(int start, int n, char first)
  • 2928 throws URISyntaxException
  • 2929 {
  • 2930 int p = start;
  • 2931 char c = first;
  • 2932 if (c == '%') {
  • 2933 // Process escape pair
  • 2934 if ((p + 3 <= n)
  • 2935 && match(charAt(p + 1), L_HEX, H_HEX)
  • 2936 && match(charAt(p + 2), L_HEX, H_HEX)) {
  • 2937 return p + 3;
  • 2938 }
  • 2939 fail("Malformed escape pair", p);
  • 2940 } else if ((c > 128)
  • 2941 && !Character.isSpaceChar(c)
  • 2942 && !Character.isISOControl(c)) {
  • 2943 // Allow unescaped but visible non-US-ASCII chars
  • 2944 return p + 1;
  • 2945 }
  • 2946 return p;
  • 2947 }
  • 2948
  • 2949 // Scan chars that match the given mask pair
  • 2950 //
  • 2951 private int scan(int start, int n, long lowMask, long highMask)
  • 2952 throws URISyntaxException
  • 2953 {
  • 2954 int p = start;
  • 2955 while (p < n) {
  • 2956 char c = charAt(p);
  • 2957 if (match(c, lowMask, highMask)) {
  • 2958 p++;
  • 2959 continue;
  • 2960 }
  • 2961 if ((lowMask & L_ESCAPED) != 0) {
  • 2962 int q = scanEscape(p, n, c);
  • 2963 if (q > p) {
  • 2964 p = q;
  • 2965 continue;
  • 2966 }
  • 2967 }
  • 2968 break;
  • 2969 }
  • 2970 return p;
  • 2971 }
  • 2972
  • 2973 // Check that each of the chars in [start, end) matches the given mask
  • 2974 //
  • 2975 private void checkChars(int start, int end,
  • 2976 long lowMask, long highMask,
  • 2977 String what)
  • 2978 throws URISyntaxException
  • 2979 {
  • 2980 int p = scan(start, end, lowMask, highMask);
  • 2981 if (p < end)
  • 2982 fail("Illegal character in " + what, p);
  • 2983 }
  • 2984
  • 2985 // Check that the char at position p matches the given mask
  • 2986 //
  • 2987 private void checkChar(int p,
  • 2988 long lowMask, long highMask,
  • 2989 String what)
  • 2990 throws URISyntaxException
  • 2991 {
  • 2992 checkChars(p, p + 1, lowMask, highMask, what);
  • 2993 }
  • 2994
  • 2995
  • 2996 // -- Parsing --
  • 2997
  • 2998 // [<scheme>:]<scheme-specific-part>[#<fragment>]
  • 2999 //
  • 3000 void parse(boolean rsa) throws URISyntaxException {
  • 3001 requireServerAuthority = rsa;
  • 3002 int ssp; // Start of scheme-specific part
  • 3003 int n = input.length();
  • 3004 int p = scan(0, n, "/?#", ":");
  • 3005 if ((p >= 0) && at(p, n, ':')) {
  • 3006 if (p == 0)
  • 3007 failExpecting("scheme name", 0);
  • 3008 checkChar(0, L_ALPHA, H_ALPHA, "scheme name");
  • 3009 checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name");
  • 3010 scheme = substring(0, p);
  • 3011 p++; // Skip ':'
  • 3012 ssp = p;
  • 3013 if (at(p, n, '/')) {
  • 3014 p = parseHierarchical(p, n);
  • 3015 } else {
  • 3016 int q = scan(p, n, "", "#");
  • 3017 if (q <= p)
  • 3018 failExpecting("scheme-specific part", p);
  • 3019 checkChars(p, q, L_URIC, H_URIC, "opaque part");
  • 3020 p = q;
  • 3021 }
  • 3022 } else {
  • 3023 ssp = 0;
  • 3024 p = parseHierarchical(0, n);
  • 3025 }
  • 3026 schemeSpecificPart = substring(ssp, p);
  • 3027 if (at(p, n, '#')) {
  • 3028 checkChars(p + 1, n, L_URIC, H_URIC, "fragment");
  • 3029 fragment = substring(p + 1, n);
  • 3030 p = n;
  • 3031 }
  • 3032 if (p < n)
  • 3033 fail("end of URI", p);
  • 3034 }
  • 3035
  • 3036 // [//authority]<path>[?<query>]
  • 3037 //
  • 3038 // DEVIATION from RFC2396: We allow an empty authority component as
  • 3039 // long as it's followed by a non-empty path, query component, or
  • 3040 // fragment component. This is so that URIs such as "file:///foo/bar"
  • 3041 // will parse. This seems to be the intent of RFC2396, though the
  • 3042 // grammar does not permit it. If the authority is empty then the
  • 3043 // userInfo, host, and port components are undefined.
  • 3044 //
  • 3045 // DEVIATION from RFC2396: We allow empty relative paths. This seems
  • 3046 // to be the intent of RFC2396, but the grammar does not permit it.
  • 3047 // The primary consequence of this deviation is that "#f" parses as a
  • 3048 // relative URI with an empty path.
  • 3049 //
  • 3050 private int parseHierarchical(int start, int n)
  • 3051 throws URISyntaxException
  • 3052 {
  • 3053 int p = start;
  • 3054 if (at(p, n, '/') && at(p + 1, n, '/')) {
  • 3055 p += 2;
  • 3056 int q = scan(p, n, "", "/?#");
  • 3057 if (q > p) {
  • 3058 p = parseAuthority(p, q);
  • 3059 } else if (q < n) {
  • 3060 // DEVIATION: Allow empty authority prior to non-empty
  • 3061 // path, query component or fragment identifier
  • 3062 } else
  • 3063 failExpecting("authority", p);
  • 3064 }
  • 3065 int q = scan(p, n, "", "?#"); // DEVIATION: May be empty
  • 3066 checkChars(p, q, L_PATH, H_PATH, "path");
  • 3067 path = substring(p, q);
  • 3068 p = q;
  • 3069 if (at(p, n, '?')) {
  • 3070 p++;
  • 3071 q = scan(p, n, "", "#");
  • 3072 checkChars(p, q, L_URIC, H_URIC, "query");
  • 3073 query = substring(p, q);
  • 3074 p = q;
  • 3075 }
  • 3076 return p;
  • 3077 }
  • 3078
  • 3079 // authority = server | reg_name
  • 3080 //
  • 3081 // Ambiguity: An authority that is a registry name rather than a server
  • 3082 // might have a prefix that parses as a server. We use the fact that
  • 3083 // the authority component is always followed by '/' or the end of the
  • 3084 // input string to resolve this: If the complete authority did not
  • 3085 // parse as a server then we try to parse it as a registry name.
  • 3086 //
  • 3087 private int parseAuthority(int start, int n)
  • 3088 throws URISyntaxException
  • 3089 {
  • 3090 int p = start;
  • 3091 int q = p;
  • 3092 URISyntaxException ex = null;
  • 3093
  • 3094 boolean serverChars;
  • 3095 boolean regChars;
  • 3096
  • 3097 if (scan(p, n, "", "]") > p) {
  • 3098 // contains a literal IPv6 address, therefore % is allowed
  • 3099 serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n);
  • 3100 } else {
  • 3101 serverChars = (scan(p, n, L_SERVER, H_SERVER) == n);
  • 3102 }
  • 3103 regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n);
  • 3104
  • 3105 if (regChars && !serverChars) {
  • 3106 // Must be a registry-based authority
  • 3107 authority = substring(p, n);
  • 3108 return n;
  • 3109 }
  • 3110
  • 3111 if (serverChars) {
  • 3112 // Might be (probably is) a server-based authority, so attempt
  • 3113 // to parse it as such. If the attempt fails, try to treat it
  • 3114 // as a registry-based authority.
  • 3115 try {
  • 3116 q = parseServer(p, n);
  • 3117 if (q < n)
  • 3118 failExpecting("end of authority", q);
  • 3119 authority = substring(p, n);
  • 3120 } catch (URISyntaxException x) {
  • 3121 // Undo results of failed parse
  • 3122 userInfo = null;
  • 3123 host = null;
  • 3124 port = -1;
  • 3125 if (requireServerAuthority) {
  • 3126 // If we're insisting upon a server-based authority,
  • 3127 // then just re-throw the exception
  • 3128 throw x;
  • 3129 } else {
  • 3130 // Save the exception in case it doesn't parse as a
  • 3131 // registry either
  • 3132 ex = x;
  • 3133 q = p;
  • 3134 }
  • 3135 }
  • 3136 }
  • 3137
  • 3138 if (q < n) {
  • 3139 if (regChars) {
  • 3140 // Registry-based authority
  • 3141 authority = substring(p, n);
  • 3142 } else if (ex != null) {
  • 3143 // Re-throw exception; it was probably due to
  • 3144 // a malformed IPv6 address
  • 3145 throw ex;
  • 3146 } else {
  • 3147 fail("Illegal character in authority", q);
  • 3148 }
  • 3149 }
  • 3150
  • 3151 return n;
  • 3152 }
  • 3153
  • 3154
  • 3155 // [<userinfo>@]<host>[:<port>]
  • 3156 //
  • 3157 private int parseServer(int start, int n)
  • 3158 throws URISyntaxException
  • 3159 {
  • 3160 int p = start;
  • 3161 int q;
  • 3162
  • 3163 // userinfo
  • 3164 q = scan(p, n, "/?#", "@");
  • 3165 if ((q >= p) && at(q, n, '@')) {
  • 3166 checkChars(p, q, L_USERINFO, H_USERINFO, "user info");
  • 3167 userInfo = substring(p, q);
  • 3168 p = q + 1; // Skip '@'
  • 3169 }
  • 3170
  • 3171 // hostname, IPv4 address, or IPv6 address
  • 3172 if (at(p, n, '[')) {
  • 3173 // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732
  • 3174 p++;
  • 3175 q = scan(p, n, "/?#", "]");
  • 3176 if ((q > p) && at(q, n, ']')) {
  • 3177 // look for a "%" scope id
  • 3178 int r = scan (p, q, "", "%");
  • 3179 if (r > p) {
  • 3180 parseIPv6Reference(p, r);
  • 3181 if (r+1 == q) {
  • 3182 fail ("scope id expected");
  • 3183 }
  • 3184 checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM,
  • 3185 "scope id");
  • 3186 } else {
  • 3187 parseIPv6Reference(p, q);
  • 3188 }
  • 3189 host = substring(p-1, q+1);
  • 3190 p = q + 1;
  • 3191 } else {
  • 3192 failExpecting("closing bracket for IPv6 address", q);
  • 3193 }
  • 3194 } else {
  • 3195 q = parseIPv4Address(p, n);
  • 3196 if (q <= p)
  • 3197 q = parseHostname(p, n);
  • 3198 p = q;
  • 3199 }
  • 3200
  • 3201 // port
  • 3202 if (at(p, n, ':')) {
  • 3203 p++;
  • 3204 q = scan(p, n, "", "/");
  • 3205 if (q > p) {
  • 3206 checkChars(p, q, L_DIGIT, H_DIGIT, "port number");
  • 3207 try {
  • 3208 port = Integer.parseInt(substring(p, q));
  • 3209 } catch (NumberFormatException x) {
  • 3210 fail("Malformed port number", p);
  • 3211 }
  • 3212 p = q;
  • 3213 }
  • 3214 }
  • 3215 if (p < n)
  • 3216 failExpecting("port number", p);
  • 3217
  • 3218 return p;
  • 3219 }
  • 3220
  • 3221 // Scan a string of decimal digits whose value fits in a byte
  • 3222 //
  • 3223 private int scanByte(int start, int n)
  • 3224 throws URISyntaxException
  • 3225 {
  • 3226 int p = start;
  • 3227 int q = scan(p, n, L_DIGIT, H_DIGIT);
  • 3228 if (q <= p) return q;
  • 3229 if (Integer.parseInt(substring(p, q)) > 255) return p;
  • 3230 return q;
  • 3231 }
  • 3232
  • 3233 // Scan an IPv4 address.
  • 3234 //
  • 3235 // If the strict argument is true then we require that the given
  • 3236 // interval contain nothing besides an IPv4 address; if it is false
  • 3237 // then we only require that it start with an IPv4 address.
  • 3238 //
  • 3239 // If the interval does not contain or start with (depending upon the
  • 3240 // strict argument) a legal IPv4 address characters then we return -1
  • 3241 // immediately; otherwise we insist that these characters parse as a
  • 3242 // legal IPv4 address and throw an exception on failure.
  • 3243 //
  • 3244 // We assume that any string of decimal digits and dots must be an IPv4
  • 3245 // address. It won't parse as a hostname anyway, so making that
  • 3246 // assumption here allows more meaningful exceptions to be thrown.
  • 3247 //
  • 3248 private int scanIPv4Address(int start, int n, boolean strict)
  • 3249 throws URISyntaxException
  • 3250 {
  • 3251 int p = start;
  • 3252 int q;
  • 3253 int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT);
  • 3254 if ((m <= p) || (strict && (m != n)))
  • 3255 return -1;
  • 3256 for (;;) {
  • 3257 // Per RFC2732: At most three digits per byte
  • 3258 // Further constraint: Each element fits in a byte
  • 3259 if ((q = scanByte(p, m)) <= p) break; p = q;
  • 3260 if ((q = scan(p, m, '.')) <= p) break; p = q;
  • 3261 if ((q = scanByte(p, m)) <= p) break; p = q;
  • 3262 if ((q = scan(p, m, '.')) <= p) break; p = q;
  • 3263 if ((q = scanByte(p, m)) <= p) break; p = q;
  • 3264 if ((q = scan(p, m, '.')) <= p) break; p = q;
  • 3265 if ((q = scanByte(p, m)) <= p) break; p = q;
  • 3266 if (q < m) break;
  • 3267 return q;
  • 3268 }
  • 3269 fail("Malformed IPv4 address", q);
  • 3270 return -1;
  • 3271 }
  • 3272
  • 3273 // Take an IPv4 address: Throw an exception if the given interval
  • 3274 // contains anything except an IPv4 address
  • 3275 //
  • 3276 private int takeIPv4Address(int start, int n, String expected)
  • 3277 throws URISyntaxException
  • 3278 {
  • 3279 int p = scanIPv4Address(start, n, true);
  • 3280 if (p <= start)
  • 3281 failExpecting(expected, start);
  • 3282 return p;
  • 3283 }
  • 3284
  • 3285 // Attempt to parse an IPv4 address, returning -1 on failure but
  • 3286 // allowing the given interval to contain [:<characters>] after
  • 3287 // the IPv4 address.
  • 3288 //
  • 3289 private int parseIPv4Address(int start, int n) {
  • 3290 int p;
  • 3291
  • 3292 try {
  • 3293 p = scanIPv4Address(start, n, false);
  • 3294 } catch (URISyntaxException x) {
  • 3295 return -1;
  • 3296 } catch (NumberFormatException nfe) {
  • 3297 return -1;
  • 3298 }
  • 3299
  • 3300 if (p > start && p < n) {
  • 3301 // IPv4 address is followed by something - check that
  • 3302 // it's a ":" as this is the only valid character to
  • 3303 // follow an address.
  • 3304 if (charAt(p) != ':') {
  • 3305 p = -1;
  • 3306 }
  • 3307 }
  • 3308
  • 3309 if (p > start)
  • 3310 host = substring(start, p);
  • 3311
  • 3312 return p;
  • 3313 }
  • 3314
  • 3315 // hostname = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ]
  • 3316 // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  • 3317 // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  • 3318 //
  • 3319 private int parseHostname(int start, int n)
  • 3320 throws URISyntaxException
  • 3321 {
  • 3322 int p = start;
  • 3323 int q;
  • 3324 int l = -1; // Start of last parsed label
  • 3325
  • 3326 do {
  • 3327 // domainlabel = alphanum [ *( alphanum | "-" ) alphanum ]
  • 3328 q = scan(p, n, L_ALPHANUM, H_ALPHANUM);
  • 3329 if (q <= p)
  • 3330 break;
  • 3331 l = p;
  • 3332 if (q > p) {
  • 3333 p = q;
  • 3334 q = scan(p, n, L_ALPHANUM | L_DASH, H_ALPHANUM | H_DASH);
  • 3335 if (q > p) {
  • 3336 if (charAt(q - 1) == '-')
  • 3337 fail("Illegal character in hostname", q - 1);
  • 3338 p = q;
  • 3339 }
  • 3340 }
  • 3341 q = scan(p, n, '.');
  • 3342 if (q <= p)
  • 3343 break;
  • 3344 p = q;
  • 3345 } while (p < n);
  • 3346
  • 3347 if ((p < n) && !at(p, n, ':'))
  • 3348 fail("Illegal character in hostname", p);
  • 3349
  • 3350 if (l < 0)
  • 3351 failExpecting("hostname", start);
  • 3352
  • 3353 // for a fully qualified hostname check that the rightmost
  • 3354 // label starts with an alpha character.
  • 3355 if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) {
  • 3356 fail("Illegal character in hostname", l);
  • 3357 }
  • 3358
  • 3359 host = substring(start, p);
  • 3360 return p;
  • 3361 }
  • 3362
  • 3363
  • 3364 // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture
  • 3365 //
  • 3366 // Bug: The grammar in RFC2373 Appendix B does not allow addresses of
  • 3367 // the form ::12.34.56.78, which are clearly shown in the examples
  • 3368 // earlier in the document. Here is the original grammar:
  • 3369 //
  • 3370 // IPv6address = hexpart [ ":" IPv4address ]
  • 3371 // hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
  • 3372 // hexseq = hex4 *( ":" hex4)
  • 3373 // hex4 = 1*4HEXDIG
  • 3374 //
  • 3375 // We therefore use the following revised grammar:
  • 3376 //
  • 3377 // IPv6address = hexseq [ ":" IPv4address ]
  • 3378 // | hexseq [ "::" [ hexpost ] ]
  • 3379 // | "::" [ hexpost ]
  • 3380 // hexpost = hexseq | hexseq ":" IPv4address | IPv4address
  • 3381 // hexseq = hex4 *( ":" hex4)
  • 3382 // hex4 = 1*4HEXDIG
  • 3383 //
  • 3384 // This covers all and only the following cases:
  • 3385 //
  • 3386 // hexseq
  • 3387 // hexseq : IPv4address
  • 3388 // hexseq ::
  • 3389 // hexseq :: hexseq
  • 3390 // hexseq :: hexseq : IPv4address
  • 3391 // hexseq :: IPv4address
  • 3392 // :: hexseq
  • 3393 // :: hexseq : IPv4address
  • 3394 // :: IPv4address
  • 3395 // ::
  • 3396 //
  • 3397 // Additionally we constrain the IPv6 address as follows :-
  • 3398 //
  • 3399 // i. IPv6 addresses without compressed zeros should contain
  • 3400 // exactly 16 bytes.
  • 3401 //
  • 3402 // ii. IPv6 addresses with compressed zeros should contain
  • 3403 // less than 16 bytes.
  • 3404
  • 3405 private int ipv6byteCount = 0;
  • 3406
  • 3407 private int parseIPv6Reference(int start, int n)
  • 3408 throws URISyntaxException
  • 3409 {
  • 3410 int p = start;
  • 3411 int q;
  • 3412 boolean compressedZeros = false;
  • 3413
  • 3414 q = scanHexSeq(p, n);
  • 3415
  • 3416 if (q > p) {
  • 3417 p = q;
  • 3418 if (at(p, n, "::")) {
  • 3419 compressedZeros = true;
  • 3420 p = scanHexPost(p + 2, n);
  • 3421 } else if (at(p, n, ':')) {
  • 3422 p = takeIPv4Address(p + 1, n, "IPv4 address");
  • 3423 ipv6byteCount += 4;
  • 3424 }
  • 3425 } else if (at(p, n, "::")) {
  • 3426 compressedZeros = true;
  • 3427 p = scanHexPost(p + 2, n);
  • 3428 }
  • 3429 if (p < n)
  • 3430 fail("Malformed IPv6 address", start);
  • 3431 if (ipv6byteCount > 16)
  • 3432 fail("IPv6 address too long", start);
  • 3433 if (!compressedZeros && ipv6byteCount < 16)
  • 3434 fail("IPv6 address too short", start);
  • 3435 if (compressedZeros && ipv6byteCount == 16)
  • 3436 fail("Malformed IPv6 address", start);
  • 3437
  • 3438 return p;
  • 3439 }
  • 3440
  • 3441 private int scanHexPost(int start, int n)
  • 3442 throws URISyntaxException
  • 3443 {
  • 3444 int p = start;
  • 3445 int q;
  • 3446
  • 3447 if (p == n)
  • 3448 return p;
  • 3449
  • 3450 q = scanHexSeq(p, n);
  • 3451 if (q > p) {
  • 3452 p = q;
  • 3453 if (at(p, n, ':')) {
  • 3454 p++;
  • 3455 p = takeIPv4Address(p, n, "hex digits or IPv4 address");
  • 3456 ipv6byteCount += 4;
  • 3457 }
  • 3458 } else {
  • 3459 p = takeIPv4Address(p, n, "hex digits or IPv4 address");
  • 3460 ipv6byteCount += 4;
  • 3461 }
  • 3462 return p;
  • 3463 }
  • 3464
  • 3465 // Scan a hex sequence; return -1 if one could not be scanned
  • 3466 //
  • 3467 private int scanHexSeq(int start, int n)
  • 3468 throws URISyntaxException
  • 3469 {
  • 3470 int p = start;
  • 3471 int q;
  • 3472
  • 3473 q = scan(p, n, L_HEX, H_HEX);
  • 3474 if (q <= p)
  • 3475 return -1;
  • 3476 if (at(q, n, '.')) // Beginning of IPv4 address
  • 3477 return -1;
  • 3478 if (q > p + 4)
  • 3479 fail("IPv6 hexadecimal digit sequence too long", p);
  • 3480 ipv6byteCount += 2;
  • 3481 p = q;
  • 3482 while (p < n) {
  • 3483 if (!at(p, n, ':'))
  • 3484 break;
  • 3485 if (at(p + 1, n, ':'))
  • 3486 break; // "::"
  • 3487 p++;
  • 3488 q = scan(p, n, L_HEX, H_HEX);
  • 3489 if (q <= p)
  • 3490 failExpecting("digits for an IPv6 address", p);
  • 3491 if (at(q, n, '.')) { // Beginning of IPv4 address
  • 3492 p--;
  • 3493 break;
  • 3494 }
  • 3495 if (q > p + 4)
  • 3496 fail("IPv6 hexadecimal digit sequence too long", p);
  • 3497 ipv6byteCount += 2;
  • 3498 p = q;
  • 3499 }
  • 3500
  • 3501 return p;
  • 3502 }
  • 3503
  • 3504 }
  • 3505
  • 3506}

文件:URI.java
包名:java.net
类名:URI
继承:
接口:[Comparable][Serializable]