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