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