PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/java-1.7.0-openjdk/openjdk/jdk/src/share/classes/java/net/URI.java

#
Java | 3526 lines | 1523 code | 282 blank | 1721 comment | 564 complexity | e917807aea7e39135d35cd0637573bf1 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, LGPL-2.0
  1. /*
  2. * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package java.net;
  26. import java.io.IOException;
  27. import java.io.InvalidObjectException;
  28. import java.io.ObjectInputStream;
  29. import java.io.ObjectOutputStream;
  30. import java.io.Serializable;
  31. import java.nio.ByteBuffer;
  32. import java.nio.CharBuffer;
  33. import java.nio.charset.CharsetDecoder;
  34. import java.nio.charset.CharsetEncoder;
  35. import java.nio.charset.CoderResult;
  36. import java.nio.charset.CodingErrorAction;
  37. import java.nio.charset.CharacterCodingException;
  38. import java.text.Normalizer;
  39. import sun.nio.cs.ThreadLocalCoders;
  40. import java.lang.Character; // for javadoc
  41. import java.lang.NullPointerException; // for javadoc
  42. /**
  43. * Represents a Uniform Resource Identifier (URI) reference.
  44. *
  45. * <p> Aside from some minor deviations noted below, an instance of this
  46. * class represents a URI reference as defined by
  47. * <a href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
  48. * Resource Identifiers (URI): Generic Syntax</i></a>, amended by <a
  49. * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
  50. * Literal IPv6 Addresses in URLs</i></a>. The Literal IPv6 address format
  51. * also supports scope_ids. The syntax and usage of scope_ids is described
  52. * <a href="Inet6Address.html#scoped">here</a>.
  53. * This class provides constructors for creating URI instances from
  54. * their components or by parsing their string forms, methods for accessing the
  55. * various components of an instance, and methods for normalizing, resolving,
  56. * and relativizing URI instances. Instances of this class are immutable.
  57. *
  58. *
  59. * <h4> URI syntax and components </h4>
  60. *
  61. * At the highest level a URI reference (hereinafter simply "URI") in string
  62. * form has the syntax
  63. *
  64. * <blockquote>
  65. * [<i>scheme</i><tt><b>:</b></tt><i></i>]<i>scheme-specific-part</i>[<tt><b>#</b></tt><i>fragment</i>]
  66. * </blockquote>
  67. *
  68. * where square brackets [...] delineate optional components and the characters
  69. * <tt><b>:</b></tt> and <tt><b>#</b></tt> stand for themselves.
  70. *
  71. * <p> An <i>absolute</i> URI specifies a scheme; a URI that is not absolute is
  72. * said to be <i>relative</i>. URIs are also classified according to whether
  73. * they are <i>opaque</i> or <i>hierarchical</i>.
  74. *
  75. * <p> An <i>opaque</i> URI is an absolute URI whose scheme-specific part does
  76. * not begin with a slash character (<tt>'/'</tt>). Opaque URIs are not
  77. * subject to further parsing. Some examples of opaque URIs are:
  78. *
  79. * <blockquote><table cellpadding=0 cellspacing=0 summary="layout">
  80. * <tr><td><tt>mailto:java-net@java.sun.com</tt><td></tr>
  81. * <tr><td><tt>news:comp.lang.java</tt><td></tr>
  82. * <tr><td><tt>urn:isbn:096139210x</tt></td></tr>
  83. * </table></blockquote>
  84. *
  85. * <p> A <i>hierarchical</i> URI is either an absolute URI whose
  86. * scheme-specific part begins with a slash character, or a relative URI, that
  87. * is, a URI that does not specify a scheme. Some examples of hierarchical
  88. * URIs are:
  89. *
  90. * <blockquote>
  91. * <tt>http://java.sun.com/j2se/1.3/</tt><br>
  92. * <tt>docs/guide/collections/designfaq.html#28</tt><br>
  93. * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java</tt><br>
  94. * <tt>file:///~/calendar</tt>
  95. * </blockquote>
  96. *
  97. * <p> A hierarchical URI is subject to further parsing according to the syntax
  98. *
  99. * <blockquote>
  100. * [<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>]
  101. * </blockquote>
  102. *
  103. * where the characters <tt><b>:</b></tt>, <tt><b>/</b></tt>,
  104. * <tt><b>?</b></tt>, and <tt><b>#</b></tt> stand for themselves. The
  105. * scheme-specific part of a hierarchical URI consists of the characters
  106. * between the scheme and fragment components.
  107. *
  108. * <p> The authority component of a hierarchical URI is, if specified, either
  109. * <i>server-based</i> or <i>registry-based</i>. A server-based authority
  110. * parses according to the familiar syntax
  111. *
  112. * <blockquote>
  113. * [<i>user-info</i><tt><b>@</b></tt>]<i>host</i>[<tt><b>:</b></tt><i>port</i>]
  114. * </blockquote>
  115. *
  116. * where the characters <tt><b>@</b></tt> and <tt><b>:</b></tt> stand for
  117. * themselves. Nearly all URI schemes currently in use are server-based. An
  118. * authority component that does not parse in this way is considered to be
  119. * registry-based.
  120. *
  121. * <p> The path component of a hierarchical URI is itself said to be absolute
  122. * if it begins with a slash character (<tt>'/'</tt>); otherwise it is
  123. * relative. The path of a hierarchical URI that is either absolute or
  124. * specifies an authority is always absolute.
  125. *
  126. * <p> All told, then, a URI instance has the following nine components:
  127. *
  128. * <blockquote><table summary="Describes the components of a URI:scheme,scheme-specific-part,authority,user-info,host,port,path,query,fragment">
  129. * <tr><th><i>Component</i></th><th><i>Type</i></th></tr>
  130. * <tr><td>scheme</td><td><tt>String</tt></td></tr>
  131. * <tr><td>scheme-specific-part&nbsp;&nbsp;&nbsp;&nbsp;</td><td><tt>String</tt></td></tr>
  132. * <tr><td>authority</td><td><tt>String</tt></td></tr>
  133. * <tr><td>user-info</td><td><tt>String</tt></td></tr>
  134. * <tr><td>host</td><td><tt>String</tt></td></tr>
  135. * <tr><td>port</td><td><tt>int</tt></td></tr>
  136. * <tr><td>path</td><td><tt>String</tt></td></tr>
  137. * <tr><td>query</td><td><tt>String</tt></td></tr>
  138. * <tr><td>fragment</td><td><tt>String</tt></td></tr>
  139. * </table></blockquote>
  140. *
  141. * In a given instance any particular component is either <i>undefined</i> or
  142. * <i>defined</i> with a distinct value. Undefined string components are
  143. * represented by <tt>null</tt>, while undefined integer components are
  144. * represented by <tt>-1</tt>. A string component may be defined to have the
  145. * empty string as its value; this is not equivalent to that component being
  146. * undefined.
  147. *
  148. * <p> Whether a particular component is or is not defined in an instance
  149. * depends upon the type of the URI being represented. An absolute URI has a
  150. * scheme component. An opaque URI has a scheme, a scheme-specific part, and
  151. * possibly a fragment, but has no other components. A hierarchical URI always
  152. * has a path (though it may be empty) and a scheme-specific-part (which at
  153. * least contains the path), and may have any of the other components. If the
  154. * authority component is present and is server-based then the host component
  155. * will be defined and the user-information and port components may be defined.
  156. *
  157. *
  158. * <h4> Operations on URI instances </h4>
  159. *
  160. * The key operations supported by this class are those of
  161. * <i>normalization</i>, <i>resolution</i>, and <i>relativization</i>.
  162. *
  163. * <p> <i>Normalization</i> is the process of removing unnecessary <tt>"."</tt>
  164. * and <tt>".."</tt> segments from the path component of a hierarchical URI.
  165. * Each <tt>"."</tt> segment is simply removed. A <tt>".."</tt> segment is
  166. * removed only if it is preceded by a non-<tt>".."</tt> segment.
  167. * Normalization has no effect upon opaque URIs.
  168. *
  169. * <p> <i>Resolution</i> is the process of resolving one URI against another,
  170. * <i>base</i> URI. The resulting URI is constructed from components of both
  171. * URIs in the manner specified by RFC&nbsp;2396, taking components from the
  172. * base URI for those not specified in the original. For hierarchical URIs,
  173. * the path of the original is resolved against the path of the base and then
  174. * normalized. The result, for example, of resolving
  175. *
  176. * <blockquote>
  177. * <tt>docs/guide/collections/designfaq.html#28&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt>(1)
  178. * </blockquote>
  179. *
  180. * against the base URI <tt>http://java.sun.com/j2se/1.3/</tt> is the result
  181. * URI
  182. *
  183. * <blockquote>
  184. * <tt>http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28</tt>
  185. * </blockquote>
  186. *
  187. * Resolving the relative URI
  188. *
  189. * <blockquote>
  190. * <tt>../../../demo/jfc/SwingSet2/src/SwingSet2.java&nbsp;&nbsp;&nbsp;&nbsp;</tt>(2)
  191. * </blockquote>
  192. *
  193. * against this result yields, in turn,
  194. *
  195. * <blockquote>
  196. * <tt>http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java</tt>
  197. * </blockquote>
  198. *
  199. * Resolution of both absolute and relative URIs, and of both absolute and
  200. * relative paths in the case of hierarchical URIs, is supported. Resolving
  201. * the URI <tt>file:///~calendar</tt> against any other URI simply yields the
  202. * original URI, since it is absolute. Resolving the relative URI (2) above
  203. * against the relative base URI (1) yields the normalized, but still relative,
  204. * URI
  205. *
  206. * <blockquote>
  207. * <tt>demo/jfc/SwingSet2/src/SwingSet2.java</tt>
  208. * </blockquote>
  209. *
  210. * <p> <i>Relativization</i>, finally, is the inverse of resolution: For any
  211. * two normalized URIs <i>u</i> and&nbsp;<i>v</i>,
  212. *
  213. * <blockquote>
  214. * <i>u</i><tt>.relativize(</tt><i>u</i><tt>.resolve(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;and<br>
  215. * <i>u</i><tt>.resolve(</tt><i>u</i><tt>.relativize(</tt><i>v</i><tt>)).equals(</tt><i>v</i><tt>)</tt>&nbsp;&nbsp;.<br>
  216. * </blockquote>
  217. *
  218. * This operation is often useful when constructing a document containing URIs
  219. * that must be made relative to the base URI of the document wherever
  220. * possible. For example, relativizing the URI
  221. *
  222. * <blockquote>
  223. * <tt>http://java.sun.com/j2se/1.3/docs/guide/index.html</tt>
  224. * </blockquote>
  225. *
  226. * against the base URI
  227. *
  228. * <blockquote>
  229. * <tt>http://java.sun.com/j2se/1.3</tt>
  230. * </blockquote>
  231. *
  232. * yields the relative URI <tt>docs/guide/index.html</tt>.
  233. *
  234. *
  235. * <h4> Character categories </h4>
  236. *
  237. * RFC&nbsp;2396 specifies precisely which characters are permitted in the
  238. * various components of a URI reference. The following categories, most of
  239. * which are taken from that specification, are used below to describe these
  240. * constraints:
  241. *
  242. * <blockquote><table cellspacing=2 summary="Describes categories alpha,digit,alphanum,unreserved,punct,reserved,escaped,and other">
  243. * <tr><th valign=top><i>alpha</i></th>
  244. * <td>The US-ASCII alphabetic characters,
  245. * <tt>'A'</tt>&nbsp;through&nbsp;<tt>'Z'</tt>
  246. * and <tt>'a'</tt>&nbsp;through&nbsp;<tt>'z'</tt></td></tr>
  247. * <tr><th valign=top><i>digit</i></th>
  248. * <td>The US-ASCII decimal digit characters,
  249. * <tt>'0'</tt>&nbsp;through&nbsp;<tt>'9'</tt></td></tr>
  250. * <tr><th valign=top><i>alphanum</i></th>
  251. * <td>All <i>alpha</i> and <i>digit</i> characters</td></tr>
  252. * <tr><th valign=top><i>unreserved</i>&nbsp;&nbsp;&nbsp;&nbsp;</th>
  253. * <td>All <i>alphanum</i> characters together with those in the string
  254. * <tt>"_-!.~'()*"</tt></td></tr>
  255. * <tr><th valign=top><i>punct</i></th>
  256. * <td>The characters in the string <tt>",;:$&+="</tt></td></tr>
  257. * <tr><th valign=top><i>reserved</i></th>
  258. * <td>All <i>punct</i> characters together with those in the string
  259. * <tt>"?/[]@"</tt></td></tr>
  260. * <tr><th valign=top><i>escaped</i></th>
  261. * <td>Escaped octets, that is, triplets consisting of the percent
  262. * character (<tt>'%'</tt>) followed by two hexadecimal digits
  263. * (<tt>'0'</tt>-<tt>'9'</tt>, <tt>'A'</tt>-<tt>'F'</tt>, and
  264. * <tt>'a'</tt>-<tt>'f'</tt>)</td></tr>
  265. * <tr><th valign=top><i>other</i></th>
  266. * <td>The Unicode characters that are not in the US-ASCII character set,
  267. * are not control characters (according to the {@link
  268. * java.lang.Character#isISOControl(char) Character.isISOControl}
  269. * method), and are not space characters (according to the {@link
  270. * java.lang.Character#isSpaceChar(char) Character.isSpaceChar}
  271. * method)&nbsp;&nbsp;<i>(<b>Deviation from RFC 2396</b>, which is
  272. * limited to US-ASCII)</i></td></tr>
  273. * </table></blockquote>
  274. *
  275. * <p><a name="legal-chars"></a> The set of all legal URI characters consists of
  276. * the <i>unreserved</i>, <i>reserved</i>, <i>escaped</i>, and <i>other</i>
  277. * characters.
  278. *
  279. *
  280. * <h4> Escaped octets, quotation, encoding, and decoding </h4>
  281. *
  282. * RFC 2396 allows escaped octets to appear in the user-info, path, query, and
  283. * fragment components. Escaping serves two purposes in URIs:
  284. *
  285. * <ul>
  286. *
  287. * <li><p> To <i>encode</i> non-US-ASCII characters when a URI is required to
  288. * conform strictly to RFC&nbsp;2396 by not containing any <i>other</i>
  289. * characters. </p></li>
  290. *
  291. * <li><p> To <i>quote</i> characters that are otherwise illegal in a
  292. * component. The user-info, path, query, and fragment components differ
  293. * slightly in terms of which characters are considered legal and illegal.
  294. * </p></li>
  295. *
  296. * </ul>
  297. *
  298. * These purposes are served in this class by three related operations:
  299. *
  300. * <ul>
  301. *
  302. * <li><p><a name="encode"></a> A character is <i>encoded</i> by replacing it
  303. * with the sequence of escaped octets that represent that character in the
  304. * UTF-8 character set. The Euro currency symbol (<tt>'&#92;u20AC'</tt>),
  305. * for example, is encoded as <tt>"%E2%82%AC"</tt>. <i>(<b>Deviation from
  306. * RFC&nbsp;2396</b>, which does not specify any particular character
  307. * set.)</i> </p></li>
  308. *
  309. * <li><p><a name="quote"></a> An illegal character is <i>quoted</i> simply by
  310. * encoding it. The space character, for example, is quoted by replacing it
  311. * with <tt>"%20"</tt>. UTF-8 contains US-ASCII, hence for US-ASCII
  312. * characters this transformation has exactly the effect required by
  313. * RFC&nbsp;2396. </p></li>
  314. *
  315. * <li><p><a name="decode"></a>
  316. * A sequence of escaped octets is <i>decoded</i> by
  317. * replacing it with the sequence of characters that it represents in the
  318. * UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the
  319. * effect of de-quoting any quoted US-ASCII characters as well as that of
  320. * decoding any encoded non-US-ASCII characters. If a <a
  321. * href="../nio/charset/CharsetDecoder.html#ce">decoding error</a> occurs
  322. * when decoding the escaped octets then the erroneous octets are replaced by
  323. * <tt>'&#92;uFFFD'</tt>, the Unicode replacement character. </p></li>
  324. *
  325. * </ul>
  326. *
  327. * These operations are exposed in the constructors and methods of this class
  328. * as follows:
  329. *
  330. * <ul>
  331. *
  332. * <li><p> The {@link #URI(java.lang.String) <code>single-argument
  333. * constructor</code>} requires any illegal characters in its argument to be
  334. * quoted and preserves any escaped octets and <i>other</i> characters that
  335. * are present. </p></li>
  336. *
  337. * <li><p> The {@link
  338. * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
  339. * <code>multi-argument constructors</code>} quote illegal characters as
  340. * required by the components in which they appear. The percent character
  341. * (<tt>'%'</tt>) is always quoted by these constructors. Any <i>other</i>
  342. * characters are preserved. </p></li>
  343. *
  344. * <li><p> The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath()
  345. * getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment()
  346. * getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link
  347. * #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the
  348. * values of their corresponding components in raw form, without interpreting
  349. * any escaped octets. The strings returned by these methods may contain
  350. * both escaped octets and <i>other</i> characters, and will not contain any
  351. * illegal characters. </p></li>
  352. *
  353. * <li><p> The {@link #getUserInfo() getUserInfo}, {@link #getPath()
  354. * getPath}, {@link #getQuery() getQuery}, {@link #getFragment()
  355. * getFragment}, {@link #getAuthority() getAuthority}, and {@link
  356. * #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped
  357. * octets in their corresponding components. The strings returned by these
  358. * methods may contain both <i>other</i> characters and illegal characters,
  359. * and will not contain any escaped octets. </p></li>
  360. *
  361. * <li><p> The {@link #toString() toString} method returns a URI string with
  362. * all necessary quotation but which may contain <i>other</i> characters.
  363. * </p></li>
  364. *
  365. * <li><p> The {@link #toASCIIString() toASCIIString} method returns a fully
  366. * quoted and encoded URI string that does not contain any <i>other</i>
  367. * characters. </p></li>
  368. *
  369. * </ul>
  370. *
  371. *
  372. * <h4> Identities </h4>
  373. *
  374. * For any URI <i>u</i>, it is always the case that
  375. *
  376. * <blockquote>
  377. * <tt>new URI(</tt><i>u</i><tt>.toString()).equals(</tt><i>u</i><tt>)</tt>&nbsp;.
  378. * </blockquote>
  379. *
  380. * For any URI <i>u</i> that does not contain redundant syntax such as two
  381. * slashes before an empty authority (as in <tt>file:///tmp/</tt>&nbsp;) or a
  382. * colon following a host name but no port (as in
  383. * <tt>http://java.sun.com:</tt>&nbsp;), and that does not encode characters
  384. * except those that must be quoted, the following identities also hold:
  385. *
  386. * <blockquote>
  387. * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  388. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getSchemeSpecificPart(),<br>
  389. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
  390. * .equals(</tt><i>u</i><tt>)</tt>
  391. * </blockquote>
  392. *
  393. * in all cases,
  394. *
  395. * <blockquote>
  396. * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  397. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getAuthority(),<br>
  398. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
  399. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
  400. * .equals(</tt><i>u</i><tt>)</tt>
  401. * </blockquote>
  402. *
  403. * if <i>u</i> is hierarchical, and
  404. *
  405. * <blockquote>
  406. * <tt>new URI(</tt><i>u</i><tt>.getScheme(),<br>
  407. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getUserInfo(),&nbsp;</tt><i>u</i><tt>.getHost(),&nbsp;</tt><i>u</i><tt>.getPort(),<br>
  408. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getPath(),&nbsp;</tt><i>u</i><tt>.getQuery(),<br>
  409. * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt><i>u</i><tt>.getFragment())<br>
  410. * .equals(</tt><i>u</i><tt>)</tt>
  411. * </blockquote>
  412. *
  413. * if <i>u</i> is hierarchical and has either no authority or a server-based
  414. * authority.
  415. *
  416. *
  417. * <h4> URIs, URLs, and URNs </h4>
  418. *
  419. * A URI is a uniform resource <i>identifier</i> while a URL is a uniform
  420. * resource <i>locator</i>. Hence every URL is a URI, abstractly speaking, but
  421. * not every URI is a URL. This is because there is another subcategory of
  422. * URIs, uniform resource <i>names</i> (URNs), which name resources but do not
  423. * specify how to locate them. The <tt>mailto</tt>, <tt>news</tt>, and
  424. * <tt>isbn</tt> URIs shown above are examples of URNs.
  425. *
  426. * <p> The conceptual distinction between URIs and URLs is reflected in the
  427. * differences between this class and the {@link URL} class.
  428. *
  429. * <p> An instance of this class represents a URI reference in the syntactic
  430. * sense defined by RFC&nbsp;2396. A URI may be either absolute or relative.
  431. * A URI string is parsed according to the generic syntax without regard to the
  432. * scheme, if any, that it specifies. No lookup of the host, if any, is
  433. * performed, and no scheme-dependent stream handler is constructed. Equality,
  434. * hashing, and comparison are defined strictly in terms of the character
  435. * content of the instance. In other words, a URI instance is little more than
  436. * a structured string that supports the syntactic, scheme-independent
  437. * operations of comparison, normalization, resolution, and relativization.
  438. *
  439. * <p> An instance of the {@link URL} class, by contrast, represents the
  440. * syntactic components of a URL together with some of the information required
  441. * to access the resource that it describes. A URL must be absolute, that is,
  442. * it must always specify a scheme. A URL string is parsed according to its
  443. * scheme. A stream handler is always established for a URL, and in fact it is
  444. * impossible to create a URL instance for a scheme for which no handler is
  445. * available. Equality and hashing depend upon both the scheme and the
  446. * Internet address of the host, if any; comparison is not defined. In other
  447. * words, a URL is a structured string that supports the syntactic operation of
  448. * resolution as well as the network I/O operations of looking up the host and
  449. * opening a connection to the specified resource.
  450. *
  451. *
  452. * @author Mark Reinhold
  453. * @since 1.4
  454. *
  455. * @see <a href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279: UTF-8, a
  456. * transformation format of ISO 10646</i></a>, <br><a
  457. * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6 Addressing
  458. * Architecture</i></a>, <br><a
  459. * href="http://www.ietf.org/rfc/rfc2396.txt"><i>RFC&nbsp;2396: Uniform
  460. * Resource Identifiers (URI): Generic Syntax</i></a>, <br><a
  461. * href="http://www.ietf.org/rfc/rfc2732.txt"><i>RFC&nbsp;2732: Format for
  462. * Literal IPv6 Addresses in URLs</i></a>, <br><a
  463. * href="URISyntaxException.html">URISyntaxException</a>
  464. */
  465. public final class URI
  466. implements Comparable<URI>, Serializable
  467. {
  468. // Note: Comments containing the word "ASSERT" indicate places where a
  469. // throw of an InternalError should be replaced by an appropriate assertion
  470. // statement once asserts are enabled in the build.
  471. static final long serialVersionUID = -6052424284110960213L;
  472. // -- Properties and components of this instance --
  473. // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
  474. private transient String scheme; // null ==> relative URI
  475. private transient String fragment;
  476. // Hierarchical URI components: [//<authority>]<path>[?<query>]
  477. private transient String authority; // Registry or server
  478. // Server-based authority: [<userInfo>@]<host>[:<port>]
  479. private transient String userInfo;
  480. private transient String host; // null ==> registry-based
  481. private transient int port = -1; // -1 ==> undefined
  482. // Remaining components of hierarchical URIs
  483. private transient String path; // null ==> opaque
  484. private transient String query;
  485. // The remaining fields may be computed on demand
  486. private volatile transient String schemeSpecificPart;
  487. private volatile transient int hash; // Zero ==> undefined
  488. private volatile transient String decodedUserInfo = null;
  489. private volatile transient String decodedAuthority = null;
  490. private volatile transient String decodedPath = null;
  491. private volatile transient String decodedQuery = null;
  492. private volatile transient String decodedFragment = null;
  493. private volatile transient String decodedSchemeSpecificPart = null;
  494. /**
  495. * The string form of this URI.
  496. *
  497. * @serial
  498. */
  499. private volatile String string; // The only serializable field
  500. // -- Constructors and factories --
  501. private URI() { } // Used internally
  502. /**
  503. * Constructs a URI by parsing the given string.
  504. *
  505. * <p> This constructor parses the given string exactly as specified by the
  506. * grammar in <a
  507. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  508. * Appendix&nbsp;A, <b><i>except for the following deviations:</i></b> </p>
  509. *
  510. * <ul type=disc>
  511. *
  512. * <li><p> An empty authority component is permitted as long as it is
  513. * followed by a non-empty path, a query component, or a fragment
  514. * component. This allows the parsing of URIs such as
  515. * <tt>"file:///foo/bar"</tt>, which seems to be the intent of
  516. * RFC&nbsp;2396 although the grammar does not permit it. If the
  517. * authority component is empty then the user-information, host, and port
  518. * components are undefined. </p></li>
  519. *
  520. * <li><p> Empty relative paths are permitted; this seems to be the
  521. * intent of RFC&nbsp;2396 although the grammar does not permit it. The
  522. * primary consequence of this deviation is that a standalone fragment
  523. * such as <tt>"#foo"</tt> parses as a relative URI with an empty path
  524. * and the given fragment, and can be usefully <a
  525. * href="#resolve-frag">resolved</a> against a base URI.
  526. *
  527. * <li><p> IPv4 addresses in host components are parsed rigorously, as
  528. * specified by <a
  529. * href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>: Each
  530. * element of a dotted-quad address must contain no more than three
  531. * decimal digits. Each element is further constrained to have a value
  532. * no greater than 255. </p></li>
  533. *
  534. * <li> <p> Hostnames in host components that comprise only a single
  535. * domain label are permitted to start with an <i>alphanum</i>
  536. * character. This seems to be the intent of <a
  537. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
  538. * section&nbsp;3.2.2 although the grammar does not permit it. The
  539. * consequence of this deviation is that the authority component of a
  540. * hierarchical URI such as <tt>s://123</tt>, will parse as a server-based
  541. * authority. </p></li>
  542. *
  543. * <li><p> IPv6 addresses are permitted for the host component. An IPv6
  544. * address must be enclosed in square brackets (<tt>'['</tt> and
  545. * <tt>']'</tt>) as specified by <a
  546. * href="http://www.ietf.org/rfc/rfc2732.txt">RFC&nbsp;2732</a>. The
  547. * IPv6 address itself must parse according to <a
  548. * href="http://www.ietf.org/rfc/rfc2373.txt">RFC&nbsp;2373</a>. IPv6
  549. * addresses are further constrained to describe no more than sixteen
  550. * bytes of address information, a constraint implicit in RFC&nbsp;2373
  551. * but not expressible in the grammar. </p></li>
  552. *
  553. * <li><p> Characters in the <i>other</i> category are permitted wherever
  554. * RFC&nbsp;2396 permits <i>escaped</i> octets, that is, in the
  555. * user-information, path, query, and fragment components, as well as in
  556. * the authority component if the authority is registry-based. This
  557. * allows URIs to contain Unicode characters beyond those in the US-ASCII
  558. * character set. </p></li>
  559. *
  560. * </ul>
  561. *
  562. * @param str The string to be parsed into a URI
  563. *
  564. * @throws NullPointerException
  565. * If <tt>str</tt> is <tt>null</tt>
  566. *
  567. * @throws URISyntaxException
  568. * If the given string violates RFC&nbsp;2396, as augmented
  569. * by the above deviations
  570. */
  571. public URI(String str) throws URISyntaxException {
  572. new Parser(str).parse(false);
  573. }
  574. /**
  575. * Constructs a hierarchical URI from the given components.
  576. *
  577. * <p> If a scheme is given then the path, if also given, must either be
  578. * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
  579. * component of the new URI may be left undefined by passing <tt>null</tt>
  580. * for the corresponding parameter or, in the case of the <tt>port</tt>
  581. * parameter, by passing <tt>-1</tt>.
  582. *
  583. * <p> This constructor first builds a URI string from the given components
  584. * according to the rules specified in <a
  585. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  586. * section&nbsp;5.2, step&nbsp;7: </p>
  587. *
  588. * <ol>
  589. *
  590. * <li><p> Initially, the result string is empty. </p></li>
  591. *
  592. * <li><p> If a scheme is given then it is appended to the result,
  593. * followed by a colon character (<tt>':'</tt>). </p></li>
  594. *
  595. * <li><p> If user information, a host, or a port are given then the
  596. * string <tt>"//"</tt> is appended. </p></li>
  597. *
  598. * <li><p> If user information is given then it is appended, followed by
  599. * a commercial-at character (<tt>'@'</tt>). Any character not in the
  600. * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  601. * categories is <a href="#quote">quoted</a>. </p></li>
  602. *
  603. * <li><p> If a host is given then it is appended. If the host is a
  604. * literal IPv6 address but is not enclosed in square brackets
  605. * (<tt>'['</tt> and <tt>']'</tt>) then the square brackets are added.
  606. * </p></li>
  607. *
  608. * <li><p> If a port number is given then a colon character
  609. * (<tt>':'</tt>) is appended, followed by the port number in decimal.
  610. * </p></li>
  611. *
  612. * <li><p> If a path is given then it is appended. Any character not in
  613. * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  614. * categories, and not equal to the slash character (<tt>'/'</tt>) or the
  615. * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
  616. *
  617. * <li><p> If a query is given then a question-mark character
  618. * (<tt>'?'</tt>) is appended, followed by the query. Any character that
  619. * is not a <a href="#legal-chars">legal URI character</a> is quoted.
  620. * </p></li>
  621. *
  622. * <li><p> Finally, if a fragment is given then a hash character
  623. * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
  624. * that is not a legal URI character is quoted. </p></li>
  625. *
  626. * </ol>
  627. *
  628. * <p> The resulting URI string is then parsed as if by invoking the {@link
  629. * #URI(String)} constructor and then invoking the {@link
  630. * #parseServerAuthority()} method upon the result; this may cause a {@link
  631. * URISyntaxException} to be thrown. </p>
  632. *
  633. * @param scheme Scheme name
  634. * @param userInfo User name and authorization information
  635. * @param host Host name
  636. * @param port Port number
  637. * @param path Path
  638. * @param query Query
  639. * @param fragment Fragment
  640. *
  641. * @throws URISyntaxException
  642. * If both a scheme and a path are given but the path is relative,
  643. * if the URI string constructed from the given components violates
  644. * RFC&nbsp;2396, or if the authority component of the string is
  645. * present but cannot be parsed as a server-based authority
  646. */
  647. public URI(String scheme,
  648. String userInfo, String host, int port,
  649. String path, String query, String fragment)
  650. throws URISyntaxException
  651. {
  652. String s = toString(scheme, null,
  653. null, userInfo, host, port,
  654. path, query, fragment);
  655. checkPath(s, scheme, path);
  656. new Parser(s).parse(true);
  657. }
  658. /**
  659. * Constructs a hierarchical URI from the given components.
  660. *
  661. * <p> If a scheme is given then the path, if also given, must either be
  662. * empty or begin with a slash character (<tt>'/'</tt>). Otherwise a
  663. * component of the new URI may be left undefined by passing <tt>null</tt>
  664. * for the corresponding parameter.
  665. *
  666. * <p> This constructor first builds a URI string from the given components
  667. * according to the rules specified in <a
  668. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  669. * section&nbsp;5.2, step&nbsp;7: </p>
  670. *
  671. * <ol>
  672. *
  673. * <li><p> Initially, the result string is empty. </p></li>
  674. *
  675. * <li><p> If a scheme is given then it is appended to the result,
  676. * followed by a colon character (<tt>':'</tt>). </p></li>
  677. *
  678. * <li><p> If an authority is given then the string <tt>"//"</tt> is
  679. * appended, followed by the authority. If the authority contains a
  680. * literal IPv6 address then the address must be enclosed in square
  681. * brackets (<tt>'['</tt> and <tt>']'</tt>). Any character not in the
  682. * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  683. * categories, and not equal to the commercial-at character
  684. * (<tt>'@'</tt>), is <a href="#quote">quoted</a>. </p></li>
  685. *
  686. * <li><p> If a path is given then it is appended. Any character not in
  687. * the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, or <i>other</i>
  688. * categories, and not equal to the slash character (<tt>'/'</tt>) or the
  689. * commercial-at character (<tt>'@'</tt>), is quoted. </p></li>
  690. *
  691. * <li><p> If a query is given then a question-mark character
  692. * (<tt>'?'</tt>) is appended, followed by the query. Any character that
  693. * is not a <a href="#legal-chars">legal URI character</a> is quoted.
  694. * </p></li>
  695. *
  696. * <li><p> Finally, if a fragment is given then a hash character
  697. * (<tt>'#'</tt>) is appended, followed by the fragment. Any character
  698. * that is not a legal URI character is quoted. </p></li>
  699. *
  700. * </ol>
  701. *
  702. * <p> The resulting URI string is then parsed as if by invoking the {@link
  703. * #URI(String)} constructor and then invoking the {@link
  704. * #parseServerAuthority()} method upon the result; this may cause a {@link
  705. * URISyntaxException} to be thrown. </p>
  706. *
  707. * @param scheme Scheme name
  708. * @param authority Authority
  709. * @param path Path
  710. * @param query Query
  711. * @param fragment Fragment
  712. *
  713. * @throws URISyntaxException
  714. * If both a scheme and a path are given but the path is relative,
  715. * if the URI string constructed from the given components violates
  716. * RFC&nbsp;2396, or if the authority component of the string is
  717. * present but cannot be parsed as a server-based authority
  718. */
  719. public URI(String scheme,
  720. String authority,
  721. String path, String query, String fragment)
  722. throws URISyntaxException
  723. {
  724. String s = toString(scheme, null,
  725. authority, null, null, -1,
  726. path, query, fragment);
  727. checkPath(s, scheme, path);
  728. new Parser(s).parse(false);
  729. }
  730. /**
  731. * Constructs a hierarchical URI from the given components.
  732. *
  733. * <p> A component may be left undefined by passing <tt>null</tt>.
  734. *
  735. * <p> This convenience constructor works as if by invoking the
  736. * seven-argument constructor as follows:
  737. *
  738. * <blockquote><tt>
  739. * new&nbsp;{@link #URI(String, String, String, int, String, String, String)
  740. * URI}(scheme,&nbsp;null,&nbsp;host,&nbsp;-1,&nbsp;path,&nbsp;null,&nbsp;fragment);
  741. * </tt></blockquote>
  742. *
  743. * @param scheme Scheme name
  744. * @param host Host name
  745. * @param path Path
  746. * @param fragment Fragment
  747. *
  748. * @throws URISyntaxException
  749. * If the URI string constructed from the given components
  750. * violates RFC&nbsp;2396
  751. */
  752. public URI(String scheme, String host, String path, String fragment)
  753. throws URISyntaxException
  754. {
  755. this(scheme, null, host, -1, path, null, fragment);
  756. }
  757. /**
  758. * Constructs a URI from the given components.
  759. *
  760. * <p> A component may be left undefined by passing <tt>null</tt>.
  761. *
  762. * <p> This constructor first builds a URI in string form using the given
  763. * components as follows: </p>
  764. *
  765. * <ol>
  766. *
  767. * <li><p> Initially, the result string is empty. </p></li>
  768. *
  769. * <li><p> If a scheme is given then it is appended to the result,
  770. * followed by a colon character (<tt>':'</tt>). </p></li>
  771. *
  772. * <li><p> If a scheme-specific part is given then it is appended. Any
  773. * character that is not a <a href="#legal-chars">legal URI character</a>
  774. * is <a href="#quote">quoted</a>. </p></li>
  775. *
  776. * <li><p> Finally, if a fragment is given then a hash character
  777. * (<tt>'#'</tt>) is appended to the string, followed by the fragment.
  778. * Any character that is not a legal URI character is quoted. </p></li>
  779. *
  780. * </ol>
  781. *
  782. * <p> The resulting URI string is then parsed in order to create the new
  783. * URI instance as if by invoking the {@link #URI(String)} constructor;
  784. * this may cause a {@link URISyntaxException} to be thrown. </p>
  785. *
  786. * @param scheme Scheme name
  787. * @param ssp Scheme-specific part
  788. * @param fragment Fragment
  789. *
  790. * @throws URISyntaxException
  791. * If the URI string constructed from the given components
  792. * violates RFC&nbsp;2396
  793. */
  794. public URI(String scheme, String ssp, String fragment)
  795. throws URISyntaxException
  796. {
  797. new Parser(toString(scheme, ssp,
  798. null, null, null, -1,
  799. null, null, fragment))
  800. .parse(false);
  801. }
  802. /**
  803. * Creates a URI by parsing the given string.
  804. *
  805. * <p> This convenience factory method works as if by invoking the {@link
  806. * #URI(String)} constructor; any {@link URISyntaxException} thrown by the
  807. * constructor is caught and wrapped in a new {@link
  808. * IllegalArgumentException} object, which is then thrown.
  809. *
  810. * <p> This method is provided for use in situations where it is known that
  811. * the given string is a legal URI, for example for URI constants declared
  812. * within in a program, and so it would be considered a programming error
  813. * for the string not to parse as such. The constructors, which throw
  814. * {@link URISyntaxException} directly, should be used situations where a
  815. * URI is being constructed from user input or from some other source that
  816. * may be prone to errors. </p>
  817. *
  818. * @param str The string to be parsed into a URI
  819. * @return The new URI
  820. *
  821. * @throws NullPointerException
  822. * If <tt>str</tt> is <tt>null</tt>
  823. *
  824. * @throws IllegalArgumentException
  825. * If the given string violates RFC&nbsp;2396
  826. */
  827. public static URI create(String str) {
  828. try {
  829. return new URI(str);
  830. } catch (URISyntaxException x) {
  831. throw new IllegalArgumentException(x.getMessage(), x);
  832. }
  833. }
  834. // -- Operations --
  835. /**
  836. * Attempts to parse this URI's authority component, if defined, into
  837. * user-information, host, and port components.
  838. *
  839. * <p> If this URI's authority component has already been recognized as
  840. * being server-based then it will already have been parsed into
  841. * user-information, host, and port components. In this case, or if this
  842. * URI has no authority component, this method simply returns this URI.
  843. *
  844. * <p> Otherwise this method attempts once more to parse the authority
  845. * component into user-information, host, and port components, and throws
  846. * an exception describing why the authority component could not be parsed
  847. * in that way.
  848. *
  849. * <p> This method is provided because the generic URI syntax specified in
  850. * <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>
  851. * cannot always distinguish a malformed server-based authority from a
  852. * legitimate registry-based authority. It must therefore treat some
  853. * instances of the former as instances of the latter. The authority
  854. * component in the URI string <tt>"//foo:bar"</tt>, for example, is not a
  855. * legal server-based authority but it is legal as a registry-based
  856. * authority.
  857. *
  858. * <p> In many common situations, for example when working URIs that are
  859. * known to be either URNs or URLs, the hierarchical URIs being used will
  860. * always be server-based. They therefore must either be parsed as such or
  861. * treated as an error. In these cases a statement such as
  862. *
  863. * <blockquote>
  864. * <tt>URI </tt><i>u</i><tt> = new URI(str).parseServerAuthority();</tt>
  865. * </blockquote>
  866. *
  867. * <p> can be used to ensure that <i>u</i> always refers to a URI that, if
  868. * it has an authority component, has a server-based authority with proper
  869. * user-information, host, and port components. Invoking this method also
  870. * ensures that if the authority could not be parsed in that way then an
  871. * appropriate diagnostic message can be issued based upon the exception
  872. * that is thrown. </p>
  873. *
  874. * @return A URI whose authority field has been parsed
  875. * as a server-based authority
  876. *
  877. * @throws URISyntaxException
  878. * If the authority component of this URI is defined
  879. * but cannot be parsed as a server-based authority
  880. * according to RFC&nbsp;2396
  881. */
  882. public URI parseServerAuthority()
  883. throws URISyntaxException
  884. {
  885. // We could be clever and cache the error message and index from the
  886. // exception thrown during the original parse, but that would require
  887. // either more fields or a more-obscure representation.
  888. if ((host != null) || (authority == null))
  889. return this;
  890. defineString();
  891. new Parser(string).parse(true);
  892. return this;
  893. }
  894. /**
  895. * Normalizes this URI's path.
  896. *
  897. * <p> If this URI is opaque, or if its path is already in normal form,
  898. * then this URI is returned. Otherwise a new URI is constructed that is
  899. * identical to this URI except that its path is computed by normalizing
  900. * this URI's path in a manner consistent with <a
  901. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  902. * section&nbsp;5.2, step&nbsp;6, sub-steps&nbsp;c through&nbsp;f; that is:
  903. * </p>
  904. *
  905. * <ol>
  906. *
  907. * <li><p> All <tt>"."</tt> segments are removed. </p></li>
  908. *
  909. * <li><p> If a <tt>".."</tt> segment is preceded by a non-<tt>".."</tt>
  910. * segment then both of these segments are removed. This step is
  911. * repeated until it is no longer applicable. </p></li>
  912. *
  913. * <li><p> If the path is relative, and if its first segment contains a
  914. * colon character (<tt>':'</tt>), then a <tt>"."</tt> segment is
  915. * prepended. This prevents a relative URI with a path such as
  916. * <tt>"a:b/c/d"</tt> from later being re-parsed as an opaque URI with a
  917. * scheme of <tt>"a"</tt> and a scheme-specific part of <tt>"b/c/d"</tt>.
  918. * <b><i>(Deviation from RFC&nbsp;2396)</i></b> </p></li>
  919. *
  920. * </ol>
  921. *
  922. * <p> A normalized path will begin with one or more <tt>".."</tt> segments
  923. * if there were insufficient non-<tt>".."</tt> segments preceding them to
  924. * allow their removal. A normalized path will begin with a <tt>"."</tt>
  925. * segment if one was inserted by step 3 above. Otherwise, a normalized
  926. * path will not contain any <tt>"."</tt> or <tt>".."</tt> segments. </p>
  927. *
  928. * @return A URI equivalent to this URI,
  929. * but whose path is in normal form
  930. */
  931. public URI normalize() {
  932. return normalize(this);
  933. }
  934. /**
  935. * Resolves the given URI against this URI.
  936. *
  937. * <p> If the given URI is already absolute, or if this URI is opaque, then
  938. * the given URI is returned.
  939. *
  940. * <p><a name="resolve-frag"></a> If the given URI's fragment component is
  941. * defined, its path component is empty, and its scheme, authority, and
  942. * query components are undefined, then a URI with the given fragment but
  943. * with all other components equal to those of this URI is returned. This
  944. * allows a URI representing a standalone fragment reference, such as
  945. * <tt>"#foo"</tt>, to be usefully resolved against a base URI.
  946. *
  947. * <p> Otherwise this method constructs a new hierarchical URI in a manner
  948. * consistent with <a
  949. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  950. * section&nbsp;5.2; that is: </p>
  951. *
  952. * <ol>
  953. *
  954. * <li><p> A new URI is constructed with this URI's scheme and the given
  955. * URI's query and fragment components. </p></li>
  956. *
  957. * <li><p> If the given URI has an authority component then the new URI's
  958. * authority and path are taken from the given URI. </p></li>
  959. *
  960. * <li><p> Otherwise the new URI's authority component is copied from
  961. * this URI, and its path is computed as follows: </p>
  962. *
  963. * <ol type=a>
  964. *
  965. * <li><p> If the given URI's path is absolute then the new URI's path
  966. * is taken from the given URI. </p></li>
  967. *
  968. * <li><p> Otherwise the given URI's path is relative, and so the new
  969. * URI's path is computed by resolving the path of the given URI
  970. * against the path of this URI. This is done by concatenating all but
  971. * the last segment of this URI's path, if any, with the given URI's
  972. * path and then normalizing the result as if by invoking the {@link
  973. * #normalize() normalize} method. </p></li>
  974. *
  975. * </ol></li>
  976. *
  977. * </ol>
  978. *
  979. * <p> The result of this method is absolute if, and only if, either this
  980. * URI is absolute or the given URI is absolute. </p>
  981. *
  982. * @param uri The URI to be resolved against this URI
  983. * @return The resulting URI
  984. *
  985. * @throws NullPointerException
  986. * If <tt>uri</tt> is <tt>null</tt>
  987. */
  988. public URI resolve(URI uri) {
  989. return resolve(this, uri);
  990. }
  991. /**
  992. * Constructs a new URI by parsing the given string and then resolving it
  993. * against this URI.
  994. *
  995. * <p> This convenience method works as if invoking it were equivalent to
  996. * evaluating the expression <tt>{@link #resolve(java.net.URI)
  997. * resolve}(URI.{@link #create(String) create}(str))</tt>. </p>
  998. *
  999. * @param str The string to be parsed into a URI
  1000. * @return The resulting URI
  1001. *
  1002. * @throws NullPointerException
  1003. * If <tt>str</tt> is <tt>null</tt>
  1004. *
  1005. * @throws IllegalArgumentException
  1006. * If the given string violates RFC&nbsp;2396
  1007. */
  1008. public URI resolve(String str) {
  1009. return resolve(URI.create(str));
  1010. }
  1011. /**
  1012. * Relativizes the given URI against this URI.
  1013. *
  1014. * <p> The relativization of the given URI against this URI is computed as
  1015. * follows: </p>
  1016. *
  1017. * <ol>
  1018. *
  1019. * <li><p> If either this URI or the given URI are opaque, or if the
  1020. * scheme and authority components of the two URIs are not identical, or
  1021. * if the path of this URI is not a prefix of the path of the given URI,
  1022. * then the given URI is returned. </p></li>
  1023. *
  1024. * <li><p> Otherwise a new relative hierarchical URI is constructed with
  1025. * query and fragment components taken from the given URI and with a path
  1026. * component computed by removing this URI's path from the beginning of
  1027. * the given URI's path. </p></li>
  1028. *
  1029. * </ol>
  1030. *
  1031. * @param uri The URI to be relativized against this URI
  1032. * @return The resulting URI
  1033. *
  1034. * @throws NullPointerException
  1035. * If <tt>uri</tt> is <tt>null</tt>
  1036. */
  1037. public URI relativize(URI uri) {
  1038. return relativize(this, uri);
  1039. }
  1040. /**
  1041. * Constructs a URL from this URI.
  1042. *
  1043. * <p> This convenience method works as if invoking it were equivalent to
  1044. * evaluating the expression <tt>new&nbsp;URL(this.toString())</tt> after
  1045. * first checking that this URI is absolute. </p>
  1046. *
  1047. * @return A URL constructed from this URI
  1048. *
  1049. * @throws IllegalArgumentException
  1050. * If this URL is not absolute
  1051. *
  1052. * @throws MalformedURLException
  1053. * If a protocol handler for the URL could not be found,
  1054. * or if some other error occurred while constructing the URL
  1055. */
  1056. public URL toURL()
  1057. throws MalformedURLException {
  1058. if (!isAbsolute())
  1059. throw new IllegalArgumentException("URI is not absolute");
  1060. return new URL(toString());
  1061. }
  1062. // -- Component access methods --
  1063. /**
  1064. * Returns the scheme component of this URI.
  1065. *
  1066. * <p> The scheme component of a URI, if defined, only contains characters
  1067. * in the <i>alphanum</i> category and in the string <tt>"-.+"</tt>. A
  1068. * scheme always starts with an <i>alpha</i> character. <p>
  1069. *
  1070. * The scheme component of a URI cannot contain escaped octets, hence this
  1071. * method does not perform any decoding.
  1072. *
  1073. * @return The scheme component of this URI,
  1074. * or <tt>null</tt> if the scheme is undefined
  1075. */
  1076. public String getScheme() {
  1077. return scheme;
  1078. }
  1079. /**
  1080. * Tells whether or not this URI is absolute.
  1081. *
  1082. * <p> A URI is absolute if, and only if, it has a scheme component. </p>
  1083. *
  1084. * @return <tt>true</tt> if, and only if, this URI is absolute
  1085. */
  1086. public boolean isAbsolute() {
  1087. return scheme != null;
  1088. }
  1089. /**
  1090. * Tells whether or not this URI is opaque.
  1091. *
  1092. * <p> A URI is opaque if, and only if, it is absolute and its
  1093. * scheme-specific part does not begin with a slash character ('/').
  1094. * An opaque URI has a scheme, a scheme-specific part, and possibly
  1095. * a fragment; all other components are undefined. </p>
  1096. *
  1097. * @return <tt>true</tt> if, and only if, this URI is opaque
  1098. */
  1099. public boolean isOpaque() {
  1100. return path == null;
  1101. }
  1102. /**
  1103. * Returns the raw scheme-specific part of this URI. The scheme-specific
  1104. * part is never undefined, though it may be empty.
  1105. *
  1106. * <p> The scheme-specific part of a URI only contains legal URI
  1107. * characters. </p>
  1108. *
  1109. * @return The raw scheme-specific part of this URI
  1110. * (never <tt>null</tt>)
  1111. */
  1112. public String getRawSchemeSpecificPart() {
  1113. defineSchemeSpecificPart();
  1114. return schemeSpecificPart;
  1115. }
  1116. /**
  1117. * Returns the decoded scheme-specific part of this URI.
  1118. *
  1119. * <p> The string returned by this method is equal to that returned by the
  1120. * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method
  1121. * except that all sequences of escaped octets are <a
  1122. * href="#decode">decoded</a>. </p>
  1123. *
  1124. * @return The decoded scheme-specific part of this URI
  1125. * (never <tt>null</tt>)
  1126. */
  1127. public String getSchemeSpecificPart() {
  1128. if (decodedSchemeSpecificPart == null)
  1129. decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart());
  1130. return decodedSchemeSpecificPart;
  1131. }
  1132. /**
  1133. * Returns the raw authority component of this URI.
  1134. *
  1135. * <p> The authority component of a URI, if defined, only contains the
  1136. * commercial-at character (<tt>'@'</tt>) and characters in the
  1137. * <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and <i>other</i>
  1138. * categories. If the authority is server-based then it is further
  1139. * constrained to have valid user-information, host, and port
  1140. * components. </p>
  1141. *
  1142. * @return The raw authority component of this URI,
  1143. * or <tt>null</tt> if the authority is undefined
  1144. */
  1145. public String getRawAuthority() {
  1146. return authority;
  1147. }
  1148. /**
  1149. * Returns the decoded authority component of this URI.
  1150. *
  1151. * <p> The string returned by this method is equal to that returned by the
  1152. * {@link #getRawAuthority() getRawAuthority} method except that all
  1153. * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  1154. *
  1155. * @return The decoded authority component of this URI,
  1156. * or <tt>null</tt> if the authority is undefined
  1157. */
  1158. public String getAuthority() {
  1159. if (decodedAuthority == null)
  1160. decodedAuthority = decode(authority);
  1161. return decodedAuthority;
  1162. }
  1163. /**
  1164. * Returns the raw user-information component of this URI.
  1165. *
  1166. * <p> The user-information component of a URI, if defined, only contains
  1167. * characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>, and
  1168. * <i>other</i> categories. </p>
  1169. *
  1170. * @return The raw user-information component of this URI,
  1171. * or <tt>null</tt> if the user information is undefined
  1172. */
  1173. public String getRawUserInfo() {
  1174. return userInfo;
  1175. }
  1176. /**
  1177. * Returns the decoded user-information component of this URI.
  1178. *
  1179. * <p> The string returned by this method is equal to that returned by the
  1180. * {@link #getRawUserInfo() getRawUserInfo} method except that all
  1181. * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  1182. *
  1183. * @return The decoded user-information component of this URI,
  1184. * or <tt>null</tt> if the user information is undefined
  1185. */
  1186. public String getUserInfo() {
  1187. if ((decodedUserInfo == null) && (userInfo != null))
  1188. decodedUserInfo = decode(userInfo);
  1189. return decodedUserInfo;
  1190. }
  1191. /**
  1192. * Returns the host component of this URI.
  1193. *
  1194. * <p> The host component of a URI, if defined, will have one of the
  1195. * following forms: </p>
  1196. *
  1197. * <ul type=disc>
  1198. *
  1199. * <li><p> A domain name consisting of one or more <i>labels</i>
  1200. * separated by period characters (<tt>'.'</tt>), optionally followed by
  1201. * a period character. Each label consists of <i>alphanum</i> characters
  1202. * as well as hyphen characters (<tt>'-'</tt>), though hyphens never
  1203. * occur as the first or last characters in a label. The rightmost
  1204. * label of a domain name consisting of two or more labels, begins
  1205. * with an <i>alpha</i> character. </li>
  1206. *
  1207. * <li><p> A dotted-quad IPv4 address of the form
  1208. * <i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+.</tt><i>digit</i><tt>+</tt>,
  1209. * where no <i>digit</i> sequence is longer than three characters and no
  1210. * sequence has a value larger than 255. </p></li>
  1211. *
  1212. * <li><p> An IPv6 address enclosed in square brackets (<tt>'['</tt> and
  1213. * <tt>']'</tt>) and consisting of hexadecimal digits, colon characters
  1214. * (<tt>':'</tt>), and possibly an embedded IPv4 address. The full
  1215. * syntax of IPv6 addresses is specified in <a
  1216. * href="http://www.ietf.org/rfc/rfc2373.txt"><i>RFC&nbsp;2373: IPv6
  1217. * Addressing Architecture</i></a>. </p></li>
  1218. *
  1219. * </ul>
  1220. *
  1221. * The host component of a URI cannot contain escaped octets, hence this
  1222. * method does not perform any decoding.
  1223. *
  1224. * @return The host component of this URI,
  1225. * or <tt>null</tt> if the host is undefined
  1226. */
  1227. public String getHost() {
  1228. return host;
  1229. }
  1230. /**
  1231. * Returns the port number of this URI.
  1232. *
  1233. * <p> The port component of a URI, if defined, is a non-negative
  1234. * integer. </p>
  1235. *
  1236. * @return The port component of this URI,
  1237. * or <tt>-1</tt> if the port is undefined
  1238. */
  1239. public int getPort() {
  1240. return port;
  1241. }
  1242. /**
  1243. * Returns the raw path component of this URI.
  1244. *
  1245. * <p> The path component of a URI, if defined, only contains the slash
  1246. * character (<tt>'/'</tt>), the commercial-at character (<tt>'@'</tt>),
  1247. * and characters in the <i>unreserved</i>, <i>punct</i>, <i>escaped</i>,
  1248. * and <i>other</i> categories. </p>
  1249. *
  1250. * @return The path component of this URI,
  1251. * or <tt>null</tt> if the path is undefined
  1252. */
  1253. public String getRawPath() {
  1254. return path;
  1255. }
  1256. /**
  1257. * Returns the decoded path component of this URI.
  1258. *
  1259. * <p> The string returned by this method is equal to that returned by the
  1260. * {@link #getRawPath() getRawPath} method except that all sequences of
  1261. * escaped octets are <a href="#decode">decoded</a>. </p>
  1262. *
  1263. * @return The decoded path component of this URI,
  1264. * or <tt>null</tt> if the path is undefined
  1265. */
  1266. public String getPath() {
  1267. if ((decodedPath == null) && (path != null))
  1268. decodedPath = decode(path);
  1269. return decodedPath;
  1270. }
  1271. /**
  1272. * Returns the raw query component of this URI.
  1273. *
  1274. * <p> The query component of a URI, if defined, only contains legal URI
  1275. * characters. </p>
  1276. *
  1277. * @return The raw query component of this URI,
  1278. * or <tt>null</tt> if the query is undefined
  1279. */
  1280. public String getRawQuery() {
  1281. return query;
  1282. }
  1283. /**
  1284. * Returns the decoded query component of this URI.
  1285. *
  1286. * <p> The string returned by this method is equal to that returned by the
  1287. * {@link #getRawQuery() getRawQuery} method except that all sequences of
  1288. * escaped octets are <a href="#decode">decoded</a>. </p>
  1289. *
  1290. * @return The decoded query component of this URI,
  1291. * or <tt>null</tt> if the query is undefined
  1292. */
  1293. public String getQuery() {
  1294. if ((decodedQuery == null) && (query != null))
  1295. decodedQuery = decode(query);
  1296. return decodedQuery;
  1297. }
  1298. /**
  1299. * Returns the raw fragment component of this URI.
  1300. *
  1301. * <p> The fragment component of a URI, if defined, only contains legal URI
  1302. * characters. </p>
  1303. *
  1304. * @return The raw fragment component of this URI,
  1305. * or <tt>null</tt> if the fragment is undefined
  1306. */
  1307. public String getRawFragment() {
  1308. return fragment;
  1309. }
  1310. /**
  1311. * Returns the decoded fragment component of this URI.
  1312. *
  1313. * <p> The string returned by this method is equal to that returned by the
  1314. * {@link #getRawFragment() getRawFragment} method except that all
  1315. * sequences of escaped octets are <a href="#decode">decoded</a>. </p>
  1316. *
  1317. * @return The decoded fragment component of this URI,
  1318. * or <tt>null</tt> if the fragment is undefined
  1319. */
  1320. public String getFragment() {
  1321. if ((decodedFragment == null) && (fragment != null))
  1322. decodedFragment = decode(fragment);
  1323. return decodedFragment;
  1324. }
  1325. // -- Equality, comparison, hash code, toString, and serialization --
  1326. /**
  1327. * Tests this URI for equality with another object.
  1328. *
  1329. * <p> If the given object is not a URI then this method immediately
  1330. * returns <tt>false</tt>.
  1331. *
  1332. * <p> For two URIs to be considered equal requires that either both are
  1333. * opaque or both are hierarchical. Their schemes must either both be
  1334. * undefined or else be equal without regard to case. Their fragments
  1335. * must either both be undefined or else be equal.
  1336. *
  1337. * <p> For two opaque URIs to be considered equal, their scheme-specific
  1338. * parts must be equal.
  1339. *
  1340. * <p> For two hierarchical URIs to be considered equal, their paths must
  1341. * be equal and their queries must either both be undefined or else be
  1342. * equal. Their authorities must either both be undefined, or both be
  1343. * registry-based, or both be server-based. If their authorities are
  1344. * defined and are registry-based, then they must be equal. If their
  1345. * authorities are defined and are server-based, then their hosts must be
  1346. * equal without regard to case, their port numbers must be equal, and
  1347. * their user-information components must be equal.
  1348. *
  1349. * <p> When testing the user-information, path, query, fragment, authority,
  1350. * or scheme-specific parts of two URIs for equality, the raw forms rather
  1351. * than the encoded forms of these components are compared and the
  1352. * hexadecimal digits of escaped octets are compared without regard to
  1353. * case.
  1354. *
  1355. * <p> This method satisfies the general contract of the {@link
  1356. * java.lang.Object#equals(Object) Object.equals} method. </p>
  1357. *
  1358. * @param ob The object to which this object is to be compared
  1359. *
  1360. * @return <tt>true</tt> if, and only if, the given object is a URI that
  1361. * is identical to this URI
  1362. */
  1363. public boolean equals(Object ob) {
  1364. if (ob == this)
  1365. return true;
  1366. if (!(ob instanceof URI))
  1367. return false;
  1368. URI that = (URI)ob;
  1369. if (this.isOpaque() != that.isOpaque()) return false;
  1370. if (!equalIgnoringCase(this.scheme, that.scheme)) return false;
  1371. if (!equal(this.fragment, that.fragment)) return false;
  1372. // Opaque
  1373. if (this.isOpaque())
  1374. return equal(this.schemeSpecificPart, that.schemeSpecificPart);
  1375. // Hierarchical
  1376. if (!equal(this.path, that.path)) return false;
  1377. if (!equal(this.query, that.query)) return false;
  1378. // Authorities
  1379. if (this.authority == that.authority) return true;
  1380. if (this.host != null) {
  1381. // Server-based
  1382. if (!equal(this.userInfo, that.userInfo)) return false;
  1383. if (!equalIgnoringCase(this.host, that.host)) return false;
  1384. if (this.port != that.port) return false;
  1385. } else if (this.authority != null) {
  1386. // Registry-based
  1387. if (!equal(this.authority, that.authority)) return false;
  1388. } else if (this.authority != that.authority) {
  1389. return false;
  1390. }
  1391. return true;
  1392. }
  1393. /**
  1394. * Returns a hash-code value for this URI. The hash code is based upon all
  1395. * of the URI's components, and satisfies the general contract of the
  1396. * {@link java.lang.Object#hashCode() Object.hashCode} method.
  1397. *
  1398. * @return A hash-code value for this URI
  1399. */
  1400. public int hashCode() {
  1401. if (hash != 0)
  1402. return hash;
  1403. int h = hashIgnoringCase(0, scheme);
  1404. h = hash(h, fragment);
  1405. if (isOpaque()) {
  1406. h = hash(h, schemeSpecificPart);
  1407. } else {
  1408. h = hash(h, path);
  1409. h = hash(h, query);
  1410. if (host != null) {
  1411. h = hash(h, userInfo);
  1412. h = hashIgnoringCase(h, host);
  1413. h += 1949 * port;
  1414. } else {
  1415. h = hash(h, authority);
  1416. }
  1417. }
  1418. hash = h;
  1419. return h;
  1420. }
  1421. /**
  1422. * Compares this URI to another object, which must be a URI.
  1423. *
  1424. * <p> When comparing corresponding components of two URIs, if one
  1425. * component is undefined but the other is defined then the first is
  1426. * considered to be less than the second. Unless otherwise noted, string
  1427. * components are ordered according to their natural, case-sensitive
  1428. * ordering as defined by the {@link java.lang.String#compareTo(Object)
  1429. * String.compareTo} method. String components that are subject to
  1430. * encoding are compared by comparing their raw forms rather than their
  1431. * encoded forms.
  1432. *
  1433. * <p> The ordering of URIs is defined as follows: </p>
  1434. *
  1435. * <ul type=disc>
  1436. *
  1437. * <li><p> Two URIs with different schemes are ordered according the
  1438. * ordering of their schemes, without regard to case. </p></li>
  1439. *
  1440. * <li><p> A hierarchical URI is considered to be less than an opaque URI
  1441. * with an identical scheme. </p></li>
  1442. *
  1443. * <li><p> Two opaque URIs with identical schemes are ordered according
  1444. * to the ordering of their scheme-specific parts. </p></li>
  1445. *
  1446. * <li><p> Two opaque URIs with identical schemes and scheme-specific
  1447. * parts are ordered according to the ordering of their
  1448. * fragments. </p></li>
  1449. *
  1450. * <li><p> Two hierarchical URIs with identical schemes are ordered
  1451. * according to the ordering of their authority components: </p>
  1452. *
  1453. * <ul type=disc>
  1454. *
  1455. * <li><p> If both authority components are server-based then the URIs
  1456. * are ordered according to their user-information components; if these
  1457. * components are identical then the URIs are ordered according to the
  1458. * ordering of their hosts, without regard to case; if the hosts are
  1459. * identical then the URIs are ordered according to the ordering of
  1460. * their ports. </p></li>
  1461. *
  1462. * <li><p> If one or both authority components are registry-based then
  1463. * the URIs are ordered according to the ordering of their authority
  1464. * components. </p></li>
  1465. *
  1466. * </ul></li>
  1467. *
  1468. * <li><p> Finally, two hierarchical URIs with identical schemes and
  1469. * authority components are ordered according to the ordering of their
  1470. * paths; if their paths are identical then they are ordered according to
  1471. * the ordering of their queries; if the queries are identical then they
  1472. * are ordered according to the order of their fragments. </p></li>
  1473. *
  1474. * </ul>
  1475. *
  1476. * <p> This method satisfies the general contract of the {@link
  1477. * java.lang.Comparable#compareTo(Object) Comparable.compareTo}
  1478. * method. </p>
  1479. *
  1480. * @param that
  1481. * The object to which this URI is to be compared
  1482. *
  1483. * @return A negative integer, zero, or a positive integer as this URI is
  1484. * less than, equal to, or greater than the given URI
  1485. *
  1486. * @throws ClassCastException
  1487. * If the given object is not a URI
  1488. */
  1489. public int compareTo(URI that) {
  1490. int c;
  1491. if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0)
  1492. return c;
  1493. if (this.isOpaque()) {
  1494. if (that.isOpaque()) {
  1495. // Both opaque
  1496. if ((c = compare(this.schemeSpecificPart,
  1497. that.schemeSpecificPart)) != 0)
  1498. return c;
  1499. return compare(this.fragment, that.fragment);
  1500. }
  1501. return +1; // Opaque > hierarchical
  1502. } else if (that.isOpaque()) {
  1503. return -1; // Hierarchical < opaque
  1504. }
  1505. // Hierarchical
  1506. if ((this.host != null) && (that.host != null)) {
  1507. // Both server-based
  1508. if ((c = compare(this.userInfo, that.userInfo)) != 0)
  1509. return c;
  1510. if ((c = compareIgnoringCase(this.host, that.host)) != 0)
  1511. return c;
  1512. if ((c = this.port - that.port) != 0)
  1513. return c;
  1514. } else {
  1515. // If one or both authorities are registry-based then we simply
  1516. // compare them in the usual, case-sensitive way. If one is
  1517. // registry-based and one is server-based then the strings are
  1518. // guaranteed to be unequal, hence the comparison will never return
  1519. // zero and the compareTo and equals methods will remain
  1520. // consistent.
  1521. if ((c = compare(this.authority, that.authority)) != 0) return c;
  1522. }
  1523. if ((c = compare(this.path, that.path)) != 0) return c;
  1524. if ((c = compare(this.query, that.query)) != 0) return c;
  1525. return compare(this.fragment, that.fragment);
  1526. }
  1527. /**
  1528. * Returns the content of this URI as a string.
  1529. *
  1530. * <p> If this URI was created by invoking one of the constructors in this
  1531. * class then a string equivalent to the original input string, or to the
  1532. * string computed from the originally-given components, as appropriate, is
  1533. * returned. Otherwise this URI was created by normalization, resolution,
  1534. * or relativization, and so a string is constructed from this URI's
  1535. * components according to the rules specified in <a
  1536. * href="http://www.ietf.org/rfc/rfc2396.txt">RFC&nbsp;2396</a>,
  1537. * section&nbsp;5.2, step&nbsp;7. </p>
  1538. *
  1539. * @return The string form of this URI
  1540. */
  1541. public String toString() {
  1542. defineString();
  1543. return string;
  1544. }
  1545. /**
  1546. * Returns the content of this URI as a US-ASCII string.
  1547. *
  1548. * <p> If this URI does not contain any characters in the <i>other</i>
  1549. * category then an invocation of this method will return the same value as
  1550. * an invocation of the {@link #toString() toString} method. Otherwise
  1551. * this method works as if by invoking that method and then <a
  1552. * href="#encode">encoding</a> the result. </p>
  1553. *
  1554. * @return The string form of this URI, encoded as needed
  1555. * so that it only contains characters in the US-ASCII
  1556. * charset
  1557. */
  1558. public String toASCIIString() {
  1559. defineString();
  1560. return encode(string);
  1561. }
  1562. // -- Serialization support --
  1563. /**
  1564. * Saves the content of this URI to the given serial stream.
  1565. *
  1566. * <p> The only serializable field of a URI instance is its <tt>string</tt>
  1567. * field. That field is given a value, if it does not have one already,
  1568. * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()}
  1569. * method of the given object-output stream is invoked. </p>
  1570. *
  1571. * @param os The object-output stream to which this object
  1572. * is to be written
  1573. */
  1574. private void writeObject(ObjectOutputStream os)
  1575. throws IOException
  1576. {
  1577. defineString();
  1578. os.defaultWriteObject(); // Writes the string field only
  1579. }
  1580. /**
  1581. * Reconstitutes a URI from the given serial stream.
  1582. *
  1583. * <p> The {@link java.io.ObjectInputStream#defaultReadObject()} method is
  1584. * invoked to read the value of the <tt>string</tt> field. The result is
  1585. * then parsed in the usual way.
  1586. *
  1587. * @param is The object-input stream from which this object
  1588. * is being read
  1589. */
  1590. private void readObject(ObjectInputStream is)
  1591. throws ClassNotFoundException, IOException
  1592. {
  1593. port = -1; // Argh
  1594. is.defaultReadObject();
  1595. try {
  1596. new Parser(string).parse(false);
  1597. } catch (URISyntaxException x) {
  1598. IOException y = new InvalidObjectException("Invalid URI");
  1599. y.initCause(x);
  1600. throw y;
  1601. }
  1602. }
  1603. // -- End of public methods --
  1604. // -- Utility methods for string-field comparison and hashing --
  1605. // These methods return appropriate values for null string arguments,
  1606. // thereby simplifying the equals, hashCode, and compareTo methods.
  1607. //
  1608. // The case-ignoring methods should only be applied to strings whose
  1609. // characters are all known to be US-ASCII. Because of this restriction,
  1610. // these methods are faster than the similar methods in the String class.
  1611. // US-ASCII only
  1612. private static int toLower(char c) {
  1613. if ((c >= 'A') && (c <= 'Z'))
  1614. return c + ('a' - 'A');
  1615. return c;
  1616. }
  1617. private static boolean equal(String s, String t) {
  1618. if (s == t) return true;
  1619. if ((s != null) && (t != null)) {
  1620. if (s.length() != t.length())
  1621. return false;
  1622. if (s.indexOf('%') < 0)
  1623. return s.equals(t);
  1624. int n = s.length();
  1625. for (int i = 0; i < n;) {
  1626. char c = s.charAt(i);
  1627. char d = t.charAt(i);
  1628. if (c != '%') {
  1629. if (c != d)
  1630. return false;
  1631. i++;
  1632. continue;
  1633. }
  1634. if (d != '%')
  1635. return false;
  1636. i++;
  1637. if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  1638. return false;
  1639. i++;
  1640. if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  1641. return false;
  1642. i++;
  1643. }
  1644. return true;
  1645. }
  1646. return false;
  1647. }
  1648. // US-ASCII only
  1649. private static boolean equalIgnoringCase(String s, String t) {
  1650. if (s == t) return true;
  1651. if ((s != null) && (t != null)) {
  1652. int n = s.length();
  1653. if (t.length() != n)
  1654. return false;
  1655. for (int i = 0; i < n; i++) {
  1656. if (toLower(s.charAt(i)) != toLower(t.charAt(i)))
  1657. return false;
  1658. }
  1659. return true;
  1660. }
  1661. return false;
  1662. }
  1663. private static int hash(int hash, String s) {
  1664. if (s == null) return hash;
  1665. return hash * 127 + s.hashCode();
  1666. }
  1667. // US-ASCII only
  1668. private static int hashIgnoringCase(int hash, String s) {
  1669. if (s == null) return hash;
  1670. int h = hash;
  1671. int n = s.length();
  1672. for (int i = 0; i < n; i++)
  1673. h = 31 * h + toLower(s.charAt(i));
  1674. return h;
  1675. }
  1676. private static int compare(String s, String t) {
  1677. if (s == t) return 0;
  1678. if (s != null) {
  1679. if (t != null)
  1680. return s.compareTo(t);
  1681. else
  1682. return +1;
  1683. } else {
  1684. return -1;
  1685. }
  1686. }
  1687. // US-ASCII only
  1688. private static int compareIgnoringCase(String s, String t) {
  1689. if (s == t) return 0;
  1690. if (s != null) {
  1691. if (t != null) {
  1692. int sn = s.length();
  1693. int tn = t.length();
  1694. int n = sn < tn ? sn : tn;
  1695. for (int i = 0; i < n; i++) {
  1696. int c = toLower(s.charAt(i)) - toLower(t.charAt(i));
  1697. if (c != 0)
  1698. return c;
  1699. }
  1700. return sn - tn;
  1701. }
  1702. return +1;
  1703. } else {
  1704. return -1;
  1705. }
  1706. }
  1707. // -- String construction --
  1708. // If a scheme is given then the path, if given, must be absolute
  1709. //
  1710. private static void checkPath(String s, String scheme, String path)
  1711. throws URISyntaxException
  1712. {
  1713. if (scheme != null) {
  1714. if ((path != null)
  1715. && ((path.length() > 0) && (path.charAt(0) != '/')))
  1716. throw new URISyntaxException(s,
  1717. "Relative path in absolute URI");
  1718. }
  1719. }
  1720. private void appendAuthority(StringBuffer sb,
  1721. String authority,
  1722. String userInfo,
  1723. String host,
  1724. int port)
  1725. {
  1726. if (host != null) {
  1727. sb.append("//");
  1728. if (userInfo != null) {
  1729. sb.append(quote(userInfo, L_USERINFO, H_USERINFO));
  1730. sb.append('@');
  1731. }
  1732. boolean needBrackets = ((host.indexOf(':') >= 0)
  1733. && !host.startsWith("[")
  1734. && !host.endsWith("]"));
  1735. if (needBrackets) sb.append('[');
  1736. sb.append(host);
  1737. if (needBrackets) sb.append(']');
  1738. if (port != -1) {
  1739. sb.append(':');
  1740. sb.append(port);
  1741. }
  1742. } else if (authority != null) {
  1743. sb.append("//");
  1744. if (authority.startsWith("[")) {
  1745. // authority should (but may not) contain an embedded IPv6 address
  1746. int end = authority.indexOf("]");
  1747. String doquote = authority, dontquote = "";
  1748. if (end != -1 && authority.indexOf(":") != -1) {
  1749. // the authority contains an IPv6 address
  1750. if (end == authority.length()) {
  1751. dontquote = authority;
  1752. doquote = "";
  1753. } else {
  1754. dontquote = authority.substring(0 , end + 1);
  1755. doquote = authority.substring(end + 1);
  1756. }
  1757. }
  1758. sb.append(dontquote);
  1759. sb.append(quote(doquote,
  1760. L_REG_NAME | L_SERVER,
  1761. H_REG_NAME | H_SERVER));
  1762. } else {
  1763. sb.append(quote(authority,
  1764. L_REG_NAME | L_SERVER,
  1765. H_REG_NAME | H_SERVER));
  1766. }
  1767. }
  1768. }
  1769. private void appendSchemeSpecificPart(StringBuffer sb,
  1770. String opaquePart,
  1771. String authority,
  1772. String userInfo,
  1773. String host,
  1774. int port,
  1775. String path,
  1776. String query)
  1777. {
  1778. if (opaquePart != null) {
  1779. /* check if SSP begins with an IPv6 address
  1780. * because we must not quote a literal IPv6 address
  1781. */
  1782. if (opaquePart.startsWith("//[")) {
  1783. int end = opaquePart.indexOf("]");
  1784. if (end != -1 && opaquePart.indexOf(":")!=-1) {
  1785. String doquote, dontquote;
  1786. if (end == opaquePart.length()) {
  1787. dontquote = opaquePart;
  1788. doquote = "";
  1789. } else {
  1790. dontquote = opaquePart.substring(0,end+1);
  1791. doquote = opaquePart.substring(end+1);
  1792. }
  1793. sb.append (dontquote);
  1794. sb.append(quote(doquote, L_URIC, H_URIC));
  1795. }
  1796. } else {
  1797. sb.append(quote(opaquePart, L_URIC, H_URIC));
  1798. }
  1799. } else {
  1800. appendAuthority(sb, authority, userInfo, host, port);
  1801. if (path != null)
  1802. sb.append(quote(path, L_PATH, H_PATH));
  1803. if (query != null) {
  1804. sb.append('?');
  1805. sb.append(quote(query, L_URIC, H_URIC));
  1806. }
  1807. }
  1808. }
  1809. private void appendFragment(StringBuffer sb, String fragment) {
  1810. if (fragment != null) {
  1811. sb.append('#');
  1812. sb.append(quote(fragment, L_URIC, H_URIC));
  1813. }
  1814. }
  1815. private String toString(String scheme,
  1816. String opaquePart,
  1817. String authority,
  1818. String userInfo,
  1819. String host,
  1820. int port,
  1821. String path,
  1822. String query,
  1823. String fragment)
  1824. {
  1825. StringBuffer sb = new StringBuffer();
  1826. if (scheme != null) {
  1827. sb.append(scheme);
  1828. sb.append(':');
  1829. }
  1830. appendSchemeSpecificPart(sb, opaquePart,
  1831. authority, userInfo, host, port,
  1832. path, query);
  1833. appendFragment(sb, fragment);
  1834. return sb.toString();
  1835. }
  1836. private void defineSchemeSpecificPart() {
  1837. if (schemeSpecificPart != null) return;
  1838. StringBuffer sb = new StringBuffer();
  1839. appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(),
  1840. host, port, getPath(), getQuery());
  1841. if (sb.length() == 0) return;
  1842. schemeSpecificPart = sb.toString();
  1843. }
  1844. private void defineString() {
  1845. if (string != null) return;
  1846. StringBuffer sb = new StringBuffer();
  1847. if (scheme != null) {
  1848. sb.append(scheme);
  1849. sb.append(':');
  1850. }
  1851. if (isOpaque()) {
  1852. sb.append(schemeSpecificPart);
  1853. } else {
  1854. if (host != null) {
  1855. sb.append("//");
  1856. if (userInfo != null) {
  1857. sb.append(userInfo);
  1858. sb.append('@');
  1859. }
  1860. boolean needBrackets = ((host.indexOf(':') >= 0)
  1861. && !host.startsWith("[")
  1862. && !host.endsWith("]"));
  1863. if (needBrackets) sb.append('[');
  1864. sb.append(host);
  1865. if (needBrackets) sb.append(']');
  1866. if (port != -1) {
  1867. sb.append(':');
  1868. sb.append(port);
  1869. }
  1870. } else if (authority != null) {
  1871. sb.append("//");
  1872. sb.append(authority);
  1873. }
  1874. if (path != null)
  1875. sb.append(path);
  1876. if (query != null) {
  1877. sb.append('?');
  1878. sb.append(query);
  1879. }
  1880. }
  1881. if (fragment != null) {
  1882. sb.append('#');
  1883. sb.append(fragment);
  1884. }
  1885. string = sb.toString();
  1886. }
  1887. // -- Normalization, resolution, and relativization --
  1888. // RFC2396 5.2 (6)
  1889. private static String resolvePath(String base, String child,
  1890. boolean absolute)
  1891. {
  1892. int i = base.lastIndexOf('/');
  1893. int cn = child.length();
  1894. String path = "";
  1895. if (cn == 0) {
  1896. // 5.2 (6a)
  1897. if (i >= 0)
  1898. path = base.substring(0, i + 1);
  1899. } else {
  1900. StringBuffer sb = new StringBuffer(base.length() + cn);
  1901. // 5.2 (6a)
  1902. if (i >= 0)
  1903. sb.append(base.substring(0, i + 1));
  1904. // 5.2 (6b)
  1905. sb.append(child);
  1906. path = sb.toString();
  1907. }
  1908. // 5.2 (6c-f)
  1909. String np = normalize(path);
  1910. // 5.2 (6g): If the result is absolute but the path begins with "../",
  1911. // then we simply leave the path as-is
  1912. return np;
  1913. }
  1914. // RFC2396 5.2
  1915. private static URI resolve(URI base, URI child) {
  1916. // check if child if opaque first so that NPE is thrown
  1917. // if child is null.
  1918. if (child.isOpaque() || base.isOpaque())
  1919. return child;
  1920. // 5.2 (2): Reference to current document (lone fragment)
  1921. if ((child.scheme == null) && (child.authority == null)
  1922. && child.path.equals("") && (child.fragment != null)
  1923. && (child.query == null)) {
  1924. if ((base.fragment != null)
  1925. && child.fragment.equals(base.fragment)) {
  1926. return base;
  1927. }
  1928. URI ru = new URI();
  1929. ru.scheme = base.scheme;
  1930. ru.authority = base.authority;
  1931. ru.userInfo = base.userInfo;
  1932. ru.host = base.host;
  1933. ru.port = base.port;
  1934. ru.path = base.path;
  1935. ru.fragment = child.fragment;
  1936. ru.query = base.query;
  1937. return ru;
  1938. }
  1939. // 5.2 (3): Child is absolute
  1940. if (child.scheme != null)
  1941. return child;
  1942. URI ru = new URI(); // Resolved URI
  1943. ru.scheme = base.scheme;
  1944. ru.query = child.query;
  1945. ru.fragment = child.fragment;
  1946. // 5.2 (4): Authority
  1947. if (child.authority == null) {
  1948. ru.authority = base.authority;
  1949. ru.host = base.host;
  1950. ru.userInfo = base.userInfo;
  1951. ru.port = base.port;
  1952. String cp = (child.path == null) ? "" : child.path;
  1953. if ((cp.length() > 0) && (cp.charAt(0) == '/')) {
  1954. // 5.2 (5): Child path is absolute
  1955. ru.path = child.path;
  1956. } else {
  1957. // 5.2 (6): Resolve relative path
  1958. ru.path = resolvePath(base.path, cp, base.isAbsolute());
  1959. }
  1960. } else {
  1961. ru.authority = child.authority;
  1962. ru.host = child.host;
  1963. ru.userInfo = child.userInfo;
  1964. ru.host = child.host;
  1965. ru.port = child.port;
  1966. ru.path = child.path;
  1967. }
  1968. // 5.2 (7): Recombine (nothing to do here)
  1969. return ru;
  1970. }
  1971. // If the given URI's path is normal then return the URI;
  1972. // o.w., return a new URI containing the normalized path.
  1973. //
  1974. private static URI normalize(URI u) {
  1975. if (u.isOpaque() || (u.path == null) || (u.path.length() == 0))
  1976. return u;
  1977. String np = normalize(u.path);
  1978. if (np == u.path)
  1979. return u;
  1980. URI v = new URI();
  1981. v.scheme = u.scheme;
  1982. v.fragment = u.fragment;
  1983. v.authority = u.authority;
  1984. v.userInfo = u.userInfo;
  1985. v.host = u.host;
  1986. v.port = u.port;
  1987. v.path = np;
  1988. v.query = u.query;
  1989. return v;
  1990. }
  1991. // If both URIs are hierarchical, their scheme and authority components are
  1992. // identical, and the base path is a prefix of the child's path, then
  1993. // return a relative URI that, when resolved against the base, yields the
  1994. // child; otherwise, return the child.
  1995. //
  1996. private static URI relativize(URI base, URI child) {
  1997. // check if child if opaque first so that NPE is thrown
  1998. // if child is null.
  1999. if (child.isOpaque() || base.isOpaque())
  2000. return child;
  2001. if (!equalIgnoringCase(base.scheme, child.scheme)
  2002. || !equal(base.authority, child.authority))
  2003. return child;
  2004. String bp = normalize(base.path);
  2005. String cp = normalize(child.path);
  2006. if (!bp.equals(cp)) {
  2007. if (!bp.endsWith("/"))
  2008. bp = bp + "/";
  2009. if (!cp.startsWith(bp))
  2010. return child;
  2011. }
  2012. URI v = new URI();
  2013. v.path = cp.substring(bp.length());
  2014. v.query = child.query;
  2015. v.fragment = child.fragment;
  2016. return v;
  2017. }
  2018. // -- Path normalization --
  2019. // The following algorithm for path normalization avoids the creation of a
  2020. // string object for each segment, as well as the use of a string buffer to
  2021. // compute the final result, by using a single char array and editing it in
  2022. // place. The array is first split into segments, replacing each slash
  2023. // with '\0' and creating a segment-index array, each element of which is
  2024. // the index of the first char in the corresponding segment. We then walk
  2025. // through both arrays, removing ".", "..", and other segments as necessary
  2026. // by setting their entries in the index array to -1. Finally, the two
  2027. // arrays are used to rejoin the segments and compute the final result.
  2028. //
  2029. // This code is based upon src/solaris/native/java/io/canonicalize_md.c
  2030. // Check the given path to see if it might need normalization. A path
  2031. // might need normalization if it contains duplicate slashes, a "."
  2032. // segment, or a ".." segment. Return -1 if no further normalization is
  2033. // possible, otherwise return the number of segments found.
  2034. //
  2035. // This method takes a string argument rather than a char array so that
  2036. // this test can be performed without invoking path.toCharArray().
  2037. //
  2038. static private int needsNormalization(String path) {
  2039. boolean normal = true;
  2040. int ns = 0; // Number of segments
  2041. int end = path.length() - 1; // Index of last char in path
  2042. int p = 0; // Index of next char in path
  2043. // Skip initial slashes
  2044. while (p <= end) {
  2045. if (path.charAt(p) != '/') break;
  2046. p++;
  2047. }
  2048. if (p > 1) normal = false;
  2049. // Scan segments
  2050. while (p <= end) {
  2051. // Looking at "." or ".." ?
  2052. if ((path.charAt(p) == '.')
  2053. && ((p == end)
  2054. || ((path.charAt(p + 1) == '/')
  2055. || ((path.charAt(p + 1) == '.')
  2056. && ((p + 1 == end)
  2057. || (path.charAt(p + 2) == '/')))))) {
  2058. normal = false;
  2059. }
  2060. ns++;
  2061. // Find beginning of next segment
  2062. while (p <= end) {
  2063. if (path.charAt(p++) != '/')
  2064. continue;
  2065. // Skip redundant slashes
  2066. while (p <= end) {
  2067. if (path.charAt(p) != '/') break;
  2068. normal = false;
  2069. p++;
  2070. }
  2071. break;
  2072. }
  2073. }
  2074. return normal ? -1 : ns;
  2075. }
  2076. // Split the given path into segments, replacing slashes with nulls and
  2077. // filling in the given segment-index array.
  2078. //
  2079. // Preconditions:
  2080. // segs.length == Number of segments in path
  2081. //
  2082. // Postconditions:
  2083. // All slashes in path replaced by '\0'
  2084. // segs[i] == Index of first char in segment i (0 <= i < segs.length)
  2085. //
  2086. static private void split(char[] path, int[] segs) {
  2087. int end = path.length - 1; // Index of last char in path
  2088. int p = 0; // Index of next char in path
  2089. int i = 0; // Index of current segment
  2090. // Skip initial slashes
  2091. while (p <= end) {
  2092. if (path[p] != '/') break;
  2093. path[p] = '\0';
  2094. p++;
  2095. }
  2096. while (p <= end) {
  2097. // Note start of segment
  2098. segs[i++] = p++;
  2099. // Find beginning of next segment
  2100. while (p <= end) {
  2101. if (path[p++] != '/')
  2102. continue;
  2103. path[p - 1] = '\0';
  2104. // Skip redundant slashes
  2105. while (p <= end) {
  2106. if (path[p] != '/') break;
  2107. path[p++] = '\0';
  2108. }
  2109. break;
  2110. }
  2111. }
  2112. if (i != segs.length)
  2113. throw new InternalError(); // ASSERT
  2114. }
  2115. // Join the segments in the given path according to the given segment-index
  2116. // array, ignoring those segments whose index entries have been set to -1,
  2117. // and inserting slashes as needed. Return the length of the resulting
  2118. // path.
  2119. //
  2120. // Preconditions:
  2121. // segs[i] == -1 implies segment i is to be ignored
  2122. // path computed by split, as above, with '\0' having replaced '/'
  2123. //
  2124. // Postconditions:
  2125. // path[0] .. path[return value] == Resulting path
  2126. //
  2127. static private int join(char[] path, int[] segs) {
  2128. int ns = segs.length; // Number of segments
  2129. int end = path.length - 1; // Index of last char in path
  2130. int p = 0; // Index of next path char to write
  2131. if (path[p] == '\0') {
  2132. // Restore initial slash for absolute paths
  2133. path[p++] = '/';
  2134. }
  2135. for (int i = 0; i < ns; i++) {
  2136. int q = segs[i]; // Current segment
  2137. if (q == -1)
  2138. // Ignore this segment
  2139. continue;
  2140. if (p == q) {
  2141. // We're already at this segment, so just skip to its end
  2142. while ((p <= end) && (path[p] != '\0'))
  2143. p++;
  2144. if (p <= end) {
  2145. // Preserve trailing slash
  2146. path[p++] = '/';
  2147. }
  2148. } else if (p < q) {
  2149. // Copy q down to p
  2150. while ((q <= end) && (path[q] != '\0'))
  2151. path[p++] = path[q++];
  2152. if (q <= end) {
  2153. // Preserve trailing slash
  2154. path[p++] = '/';
  2155. }
  2156. } else
  2157. throw new InternalError(); // ASSERT false
  2158. }
  2159. return p;
  2160. }
  2161. // Remove "." segments from the given path, and remove segment pairs
  2162. // consisting of a non-".." segment followed by a ".." segment.
  2163. //
  2164. private static void removeDots(char[] path, int[] segs) {
  2165. int ns = segs.length;
  2166. int end = path.length - 1;
  2167. for (int i = 0; i < ns; i++) {
  2168. int dots = 0; // Number of dots found (0, 1, or 2)
  2169. // Find next occurrence of "." or ".."
  2170. do {
  2171. int p = segs[i];
  2172. if (path[p] == '.') {
  2173. if (p == end) {
  2174. dots = 1;
  2175. break;
  2176. } else if (path[p + 1] == '\0') {
  2177. dots = 1;
  2178. break;
  2179. } else if ((path[p + 1] == '.')
  2180. && ((p + 1 == end)
  2181. || (path[p + 2] == '\0'))) {
  2182. dots = 2;
  2183. break;
  2184. }
  2185. }
  2186. i++;
  2187. } while (i < ns);
  2188. if ((i > ns) || (dots == 0))
  2189. break;
  2190. if (dots == 1) {
  2191. // Remove this occurrence of "."
  2192. segs[i] = -1;
  2193. } else {
  2194. // If there is a preceding non-".." segment, remove both that
  2195. // segment and this occurrence of ".."; otherwise, leave this
  2196. // ".." segment as-is.
  2197. int j;
  2198. for (j = i - 1; j >= 0; j--) {
  2199. if (segs[j] != -1) break;
  2200. }
  2201. if (j >= 0) {
  2202. int q = segs[j];
  2203. if (!((path[q] == '.')
  2204. && (path[q + 1] == '.')
  2205. && (path[q + 2] == '\0'))) {
  2206. segs[i] = -1;
  2207. segs[j] = -1;
  2208. }
  2209. }
  2210. }
  2211. }
  2212. }
  2213. // DEVIATION: If the normalized path is relative, and if the first
  2214. // segment could be parsed as a scheme name, then prepend a "." segment
  2215. //
  2216. private static void maybeAddLeadingDot(char[] path, int[] segs) {
  2217. if (path[0] == '\0')
  2218. // The path is absolute
  2219. return;
  2220. int ns = segs.length;
  2221. int f = 0; // Index of first segment
  2222. while (f < ns) {
  2223. if (segs[f] >= 0)
  2224. break;
  2225. f++;
  2226. }
  2227. if ((f >= ns) || (f == 0))
  2228. // The path is empty, or else the original first segment survived,
  2229. // in which case we already know that no leading "." is needed
  2230. return;
  2231. int p = segs[f];
  2232. while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++;
  2233. if (p >= path.length || path[p] == '\0')
  2234. // No colon in first segment, so no "." needed
  2235. return;
  2236. // At this point we know that the first segment is unused,
  2237. // hence we can insert a "." segment at that position
  2238. path[0] = '.';
  2239. path[1] = '\0';
  2240. segs[0] = 0;
  2241. }
  2242. // Normalize the given path string. A normal path string has no empty
  2243. // segments (i.e., occurrences of "//"), no segments equal to ".", and no
  2244. // segments equal to ".." that are preceded by a segment not equal to "..".
  2245. // In contrast to Unix-style pathname normalization, for URI paths we
  2246. // always retain trailing slashes.
  2247. //
  2248. private static String normalize(String ps) {
  2249. // Does this path need normalization?
  2250. int ns = needsNormalization(ps); // Number of segments
  2251. if (ns < 0)
  2252. // Nope -- just return it
  2253. return ps;
  2254. char[] path = ps.toCharArray(); // Path in char-array form
  2255. // Split path into segments
  2256. int[] segs = new int[ns]; // Segment-index array
  2257. split(path, segs);
  2258. // Remove dots
  2259. removeDots(path, segs);
  2260. // Prevent scheme-name confusion
  2261. maybeAddLeadingDot(path, segs);
  2262. // Join the remaining segments and return the result
  2263. String s = new String(path, 0, join(path, segs));
  2264. if (s.equals(ps)) {
  2265. // string was already normalized
  2266. return ps;
  2267. }
  2268. return s;
  2269. }
  2270. // -- Character classes for parsing --
  2271. // RFC2396 precisely specifies which characters in the US-ASCII charset are
  2272. // permissible in the various components of a URI reference. We here
  2273. // define a set of mask pairs to aid in enforcing these restrictions. Each
  2274. // mask pair consists of two longs, a low mask and a high mask. Taken
  2275. // together they represent a 128-bit mask, where bit i is set iff the
  2276. // character with value i is permitted.
  2277. //
  2278. // This approach is more efficient than sequentially searching arrays of
  2279. // permitted characters. It could be made still more efficient by
  2280. // precompiling the mask information so that a character's presence in a
  2281. // given mask could be determined by a single table lookup.
  2282. // Compute the low-order mask for the characters in the given string
  2283. private static long lowMask(String chars) {
  2284. int n = chars.length();
  2285. long m = 0;
  2286. for (int i = 0; i < n; i++) {
  2287. char c = chars.charAt(i);
  2288. if (c < 64)
  2289. m |= (1L << c);
  2290. }
  2291. return m;
  2292. }
  2293. // Compute the high-order mask for the characters in the given string
  2294. private static long highMask(String chars) {
  2295. int n = chars.length();
  2296. long m = 0;
  2297. for (int i = 0; i < n; i++) {
  2298. char c = chars.charAt(i);
  2299. if ((c >= 64) && (c < 128))
  2300. m |= (1L << (c - 64));
  2301. }
  2302. return m;
  2303. }
  2304. // Compute a low-order mask for the characters
  2305. // between first and last, inclusive
  2306. private static long lowMask(char first, char last) {
  2307. long m = 0;
  2308. int f = Math.max(Math.min(first, 63), 0);
  2309. int l = Math.max(Math.min(last, 63), 0);
  2310. for (int i = f; i <= l; i++)
  2311. m |= 1L << i;
  2312. return m;
  2313. }
  2314. // Compute a high-order mask for the characters
  2315. // between first and last, inclusive
  2316. private static long highMask(char first, char last) {
  2317. long m = 0;
  2318. int f = Math.max(Math.min(first, 127), 64) - 64;
  2319. int l = Math.max(Math.min(last, 127), 64) - 64;
  2320. for (int i = f; i <= l; i++)
  2321. m |= 1L << i;
  2322. return m;
  2323. }
  2324. // Tell whether the given character is permitted by the given mask pair
  2325. private static boolean match(char c, long lowMask, long highMask) {
  2326. if (c == 0) // 0 doesn't have a slot in the mask. So, it never matches.
  2327. return false;
  2328. if (c < 64)
  2329. return ((1L << c) & lowMask) != 0;
  2330. if (c < 128)
  2331. return ((1L << (c - 64)) & highMask) != 0;
  2332. return false;
  2333. }
  2334. // Character-class masks, in reverse order from RFC2396 because
  2335. // initializers for static fields cannot make forward references.
  2336. // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
  2337. // "8" | "9"
  2338. private static final long L_DIGIT = lowMask('0', '9');
  2339. private static final long H_DIGIT = 0L;
  2340. // upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" |
  2341. // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" |
  2342. // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z"
  2343. private static final long L_UPALPHA = 0L;
  2344. private static final long H_UPALPHA = highMask('A', 'Z');
  2345. // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" |
  2346. // "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" |
  2347. // "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z"
  2348. private static final long L_LOWALPHA = 0L;
  2349. private static final long H_LOWALPHA = highMask('a', 'z');
  2350. // alpha = lowalpha | upalpha
  2351. private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA;
  2352. private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA;
  2353. // alphanum = alpha | digit
  2354. private static final long L_ALPHANUM = L_DIGIT | L_ALPHA;
  2355. private static final long H_ALPHANUM = H_DIGIT | H_ALPHA;
  2356. // hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
  2357. // "a" | "b" | "c" | "d" | "e" | "f"
  2358. private static final long L_HEX = L_DIGIT;
  2359. private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f');
  2360. // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
  2361. // "(" | ")"
  2362. private static final long L_MARK = lowMask("-_.!~*'()");
  2363. private static final long H_MARK = highMask("-_.!~*'()");
  2364. // unreserved = alphanum | mark
  2365. private static final long L_UNRESERVED = L_ALPHANUM | L_MARK;
  2366. private static final long H_UNRESERVED = H_ALPHANUM | H_MARK;
  2367. // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  2368. // "$" | "," | "[" | "]"
  2369. // Added per RFC2732: "[", "]"
  2370. private static final long L_RESERVED = lowMask(";/?:@&=+$,[]");
  2371. private static final long H_RESERVED = highMask(";/?:@&=+$,[]");
  2372. // The zero'th bit is used to indicate that escape pairs and non-US-ASCII
  2373. // characters are allowed; this is handled by the scanEscape method below.
  2374. private static final long L_ESCAPED = 1L;
  2375. private static final long H_ESCAPED = 0L;
  2376. // uric = reserved | unreserved | escaped
  2377. private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED;
  2378. private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED;
  2379. // pchar = unreserved | escaped |
  2380. // ":" | "@" | "&" | "=" | "+" | "$" | ","
  2381. private static final long L_PCHAR
  2382. = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,");
  2383. private static final long H_PCHAR
  2384. = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,");
  2385. // All valid path characters
  2386. private static final long L_PATH = L_PCHAR | lowMask(";/");
  2387. private static final long H_PATH = H_PCHAR | highMask(";/");
  2388. // Dash, for use in domainlabel and toplabel
  2389. private static final long L_DASH = lowMask("-");
  2390. private static final long H_DASH = highMask("-");
  2391. // Dot, for use in hostnames
  2392. private static final long L_DOT = lowMask(".");
  2393. private static final long H_DOT = highMask(".");
  2394. // userinfo = *( unreserved | escaped |
  2395. // ";" | ":" | "&" | "=" | "+" | "$" | "," )
  2396. private static final long L_USERINFO
  2397. = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,");
  2398. private static final long H_USERINFO
  2399. = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,");
  2400. // reg_name = 1*( unreserved | escaped | "$" | "," |
  2401. // ";" | ":" | "@" | "&" | "=" | "+" )
  2402. private static final long L_REG_NAME
  2403. = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+");
  2404. private static final long H_REG_NAME
  2405. = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+");
  2406. // All valid characters for server-based authorities
  2407. private static final long L_SERVER
  2408. = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]");
  2409. private static final long H_SERVER
  2410. = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]");
  2411. // Special case of server authority that represents an IPv6 address
  2412. // In this case, a % does not signify an escape sequence
  2413. private static final long L_SERVER_PERCENT
  2414. = L_SERVER | lowMask("%");
  2415. private static final long H_SERVER_PERCENT
  2416. = H_SERVER | highMask("%");
  2417. private static final long L_LEFT_BRACKET = lowMask("[");
  2418. private static final long H_LEFT_BRACKET = highMask("[");
  2419. // scheme = alpha *( alpha | digit | "+" | "-" | "." )
  2420. private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-.");
  2421. private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-.");
  2422. // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
  2423. // "&" | "=" | "+" | "$" | ","
  2424. private static final long L_URIC_NO_SLASH
  2425. = L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,");
  2426. private static final long H_URIC_NO_SLASH
  2427. = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,");
  2428. // -- Escaping and encoding --
  2429. private final static char[] hexDigits = {
  2430. '0', '1', '2', '3', '4', '5', '6', '7',
  2431. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  2432. };
  2433. private static void appendEscape(StringBuffer sb, byte b) {
  2434. sb.append('%');
  2435. sb.append(hexDigits[(b >> 4) & 0x0f]);
  2436. sb.append(hexDigits[(b >> 0) & 0x0f]);
  2437. }
  2438. private static void appendEncoded(StringBuffer sb, char c) {
  2439. ByteBuffer bb = null;
  2440. try {
  2441. bb = ThreadLocalCoders.encoderFor("UTF-8")
  2442. .encode(CharBuffer.wrap("" + c));
  2443. } catch (CharacterCodingException x) {
  2444. assert false;
  2445. }
  2446. while (bb.hasRemaining()) {
  2447. int b = bb.get() & 0xff;
  2448. if (b >= 0x80)
  2449. appendEscape(sb, (byte)b);
  2450. else
  2451. sb.append((char)b);
  2452. }
  2453. }
  2454. // Quote any characters in s that are not permitted
  2455. // by the given mask pair
  2456. //
  2457. private static String quote(String s, long lowMask, long highMask) {
  2458. int n = s.length();
  2459. StringBuffer sb = null;
  2460. boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0);
  2461. for (int i = 0; i < s.length(); i++) {
  2462. char c = s.charAt(i);
  2463. if (c < '\u0080') {
  2464. if (!match(c, lowMask, highMask)) {
  2465. if (sb == null) {
  2466. sb = new StringBuffer();
  2467. sb.append(s.substring(0, i));
  2468. }
  2469. appendEscape(sb, (byte)c);
  2470. } else {
  2471. if (sb != null)
  2472. sb.append(c);
  2473. }
  2474. } else if (allowNonASCII
  2475. && (Character.isSpaceChar(c)
  2476. || Character.isISOControl(c))) {
  2477. if (sb == null) {
  2478. sb = new StringBuffer();
  2479. sb.append(s.substring(0, i));
  2480. }
  2481. appendEncoded(sb, c);
  2482. } else {
  2483. if (sb != null)
  2484. sb.append(c);
  2485. }
  2486. }
  2487. return (sb == null) ? s : sb.toString();
  2488. }
  2489. // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets,
  2490. // assuming that s is otherwise legal
  2491. //
  2492. private static String encode(String s) {
  2493. int n = s.length();
  2494. if (n == 0)
  2495. return s;
  2496. // First check whether we actually need to encode
  2497. for (int i = 0;;) {
  2498. if (s.charAt(i) >= '\u0080')
  2499. break;
  2500. if (++i >= n)
  2501. return s;
  2502. }
  2503. String ns = Normalizer.normalize(s, Normalizer.Form.NFC);
  2504. ByteBuffer bb = null;
  2505. try {
  2506. bb = ThreadLocalCoders.encoderFor("UTF-8")
  2507. .encode(CharBuffer.wrap(ns));
  2508. } catch (CharacterCodingException x) {
  2509. assert false;
  2510. }
  2511. StringBuffer sb = new StringBuffer();
  2512. while (bb.hasRemaining()) {
  2513. int b = bb.get() & 0xff;
  2514. if (b >= 0x80)
  2515. appendEscape(sb, (byte)b);
  2516. else
  2517. sb.append((char)b);
  2518. }
  2519. return sb.toString();
  2520. }
  2521. private static int decode(char c) {
  2522. if ((c >= '0') && (c <= '9'))
  2523. return c - '0';
  2524. if ((c >= 'a') && (c <= 'f'))
  2525. return c - 'a' + 10;
  2526. if ((c >= 'A') && (c <= 'F'))
  2527. return c - 'A' + 10;
  2528. assert false;
  2529. return -1;
  2530. }
  2531. private static byte decode(char c1, char c2) {
  2532. return (byte)( ((decode(c1) & 0xf) << 4)
  2533. | ((decode(c2) & 0xf) << 0));
  2534. }
  2535. // Evaluates all escapes in s, applying UTF-8 decoding if needed. Assumes
  2536. // that escapes are well-formed syntactically, i.e., of the form %XX. If a
  2537. // sequence of escaped octets is not valid UTF-8 then the erroneous octets
  2538. // are replaced with '\uFFFD'.
  2539. // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal
  2540. // with a scope_id
  2541. //
  2542. private static String decode(String s) {
  2543. if (s == null)
  2544. return s;
  2545. int n = s.length();
  2546. if (n == 0)
  2547. return s;
  2548. if (s.indexOf('%') < 0)
  2549. return s;
  2550. StringBuffer sb = new StringBuffer(n);
  2551. ByteBuffer bb = ByteBuffer.allocate(n);
  2552. CharBuffer cb = CharBuffer.allocate(n);
  2553. CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8")
  2554. .onMalformedInput(CodingErrorAction.REPLACE)
  2555. .onUnmappableCharacter(CodingErrorAction.REPLACE);
  2556. // This is not horribly efficient, but it will do for now
  2557. char c = s.charAt(0);
  2558. boolean betweenBrackets = false;
  2559. for (int i = 0; i < n;) {
  2560. assert c == s.charAt(i); // Loop invariant
  2561. if (c == '[') {
  2562. betweenBrackets = true;
  2563. } else if (betweenBrackets && c == ']') {
  2564. betweenBrackets = false;
  2565. }
  2566. if (c != '%' || betweenBrackets) {
  2567. sb.append(c);
  2568. if (++i >= n)
  2569. break;
  2570. c = s.charAt(i);
  2571. continue;
  2572. }
  2573. bb.clear();
  2574. int ui = i;
  2575. for (;;) {
  2576. assert (n - i >= 2);
  2577. bb.put(decode(s.charAt(++i), s.charAt(++i)));
  2578. if (++i >= n)
  2579. break;
  2580. c = s.charAt(i);
  2581. if (c != '%')
  2582. break;
  2583. }
  2584. bb.flip();
  2585. cb.clear();
  2586. dec.reset();
  2587. CoderResult cr = dec.decode(bb, cb, true);
  2588. assert cr.isUnderflow();
  2589. cr = dec.flush(cb);
  2590. assert cr.isUnderflow();
  2591. sb.append(cb.flip().toString());
  2592. }
  2593. return sb.toString();
  2594. }
  2595. // -- Parsing --
  2596. // For convenience we wrap the input URI string in a new instance of the
  2597. // following internal class. This saves always having to pass the input
  2598. // string as an argument to each internal scan/parse method.
  2599. private class Parser {
  2600. private String input; // URI input string
  2601. private boolean requireServerAuthority = false;
  2602. Parser(String s) {
  2603. input = s;
  2604. string = s;
  2605. }
  2606. // -- Methods for throwing URISyntaxException in various ways --
  2607. private void fail(String reason) throws URISyntaxException {
  2608. throw new URISyntaxException(input, reason);
  2609. }
  2610. private void fail(String reason, int p) throws URISyntaxException {
  2611. throw new URISyntaxException(input, reason, p);
  2612. }
  2613. private void failExpecting(String expected, int p)
  2614. throws URISyntaxException
  2615. {
  2616. fail("Expected " + expected, p);
  2617. }
  2618. private void failExpecting(String expected, String prior, int p)
  2619. throws URISyntaxException
  2620. {
  2621. fail("Expected " + expected + " following " + prior, p);
  2622. }
  2623. // -- Simple access to the input string --
  2624. // Return a substring of the input string
  2625. //
  2626. private String substring(int start, int end) {
  2627. return input.substring(start, end);
  2628. }
  2629. // Return the char at position p,
  2630. // assuming that p < input.length()
  2631. //
  2632. private char charAt(int p) {
  2633. return input.charAt(p);
  2634. }
  2635. // Tells whether start < end and, if so, whether charAt(start) == c
  2636. //
  2637. private boolean at(int start, int end, char c) {
  2638. return (start < end) && (charAt(start) == c);
  2639. }
  2640. // Tells whether start + s.length() < end and, if so,
  2641. // whether the chars at the start position match s exactly
  2642. //
  2643. private boolean at(int start, int end, String s) {
  2644. int p = start;
  2645. int sn = s.length();
  2646. if (sn > end - p)
  2647. return false;
  2648. int i = 0;
  2649. while (i < sn) {
  2650. if (charAt(p++) != s.charAt(i)) {
  2651. break;
  2652. }
  2653. i++;
  2654. }
  2655. return (i == sn);
  2656. }
  2657. // -- Scanning --
  2658. // The various scan and parse methods that follow use a uniform
  2659. // convention of taking the current start position and end index as
  2660. // their first two arguments. The start is inclusive while the end is
  2661. // exclusive, just as in the String class, i.e., a start/end pair
  2662. // denotes the left-open interval [start, end) of the input string.
  2663. //
  2664. // These methods never proceed past the end position. They may return
  2665. // -1 to indicate outright failure, but more often they simply return
  2666. // the position of the first char after the last char scanned. Thus
  2667. // a typical idiom is
  2668. //
  2669. // int p = start;
  2670. // int q = scan(p, end, ...);
  2671. // if (q > p)
  2672. // // We scanned something
  2673. // ...;
  2674. // else if (q == p)
  2675. // // We scanned nothing
  2676. // ...;
  2677. // else if (q == -1)
  2678. // // Something went wrong
  2679. // ...;
  2680. // Scan a specific char: If the char at the given start position is
  2681. // equal to c, return the index of the next char; otherwise, return the
  2682. // start position.
  2683. //
  2684. private int scan(int start, int end, char c) {
  2685. if ((start < end) && (charAt(start) == c))
  2686. return start + 1;
  2687. return start;
  2688. }
  2689. // Scan forward from the given start position. Stop at the first char
  2690. // in the err string (in which case -1 is returned), or the first char
  2691. // in the stop string (in which case the index of the preceding char is
  2692. // returned), or the end of the input string (in which case the length
  2693. // of the input string is returned). May return the start position if
  2694. // nothing matches.
  2695. //
  2696. private int scan(int start, int end, String err, String stop) {
  2697. int p = start;
  2698. while (p < end) {
  2699. char c = charAt(p);
  2700. if (err.indexOf(c) >= 0)
  2701. return -1;
  2702. if (stop.indexOf(c) >= 0)
  2703. break;
  2704. p++;
  2705. }
  2706. return p;
  2707. }
  2708. // Scan a potential escape sequence, starting at the given position,
  2709. // with the given first char (i.e., charAt(start) == c).
  2710. //
  2711. // This method assumes that if escapes are allowed then visible
  2712. // non-US-ASCII chars are also allowed.
  2713. //
  2714. private int scanEscape(int start, int n, char first)
  2715. throws URISyntaxException
  2716. {
  2717. int p = start;
  2718. char c = first;
  2719. if (c == '%') {
  2720. // Process escape pair
  2721. if ((p + 3 <= n)
  2722. && match(charAt(p + 1), L_HEX, H_HEX)
  2723. && match(charAt(p + 2), L_HEX, H_HEX)) {
  2724. return p + 3;
  2725. }
  2726. fail("Malformed escape pair", p);
  2727. } else if ((c > 128)
  2728. && !Character.isSpaceChar(c)
  2729. && !Character.isISOControl(c)) {
  2730. // Allow unescaped but visible non-US-ASCII chars
  2731. return p + 1;
  2732. }
  2733. return p;
  2734. }
  2735. // Scan chars that match the given mask pair
  2736. //
  2737. private int scan(int start, int n, long lowMask, long highMask)
  2738. throws URISyntaxException
  2739. {
  2740. int p = start;
  2741. while (p < n) {
  2742. char c = charAt(p);
  2743. if (match(c, lowMask, highMask)) {
  2744. p++;
  2745. continue;
  2746. }
  2747. if ((lowMask & L_ESCAPED) != 0) {
  2748. int q = scanEscape(p, n, c);
  2749. if (q > p) {
  2750. p = q;
  2751. continue;
  2752. }
  2753. }
  2754. break;
  2755. }
  2756. return p;
  2757. }
  2758. // Check that each of the chars in [start, end) matches the given mask
  2759. //
  2760. private void checkChars(int start, int end,
  2761. long lowMask, long highMask,
  2762. String what)
  2763. throws URISyntaxException
  2764. {
  2765. int p = scan(start, end, lowMask, highMask);
  2766. if (p < end)
  2767. fail("Illegal character in " + what, p);
  2768. }
  2769. // Check that the char at position p matches the given mask
  2770. //
  2771. private void checkChar(int p,
  2772. long lowMask, long highMask,
  2773. String what)
  2774. throws URISyntaxException
  2775. {
  2776. checkChars(p, p + 1, lowMask, highMask, what);
  2777. }
  2778. // -- Parsing --
  2779. // [<scheme>:]<scheme-specific-part>[#<fragment>]
  2780. //
  2781. void parse(boolean rsa) throws URISyntaxException {
  2782. requireServerAuthority = rsa;
  2783. int ssp; // Start of scheme-specific part
  2784. int n = input.length();
  2785. int p = scan(0, n, "/?#", ":");
  2786. if ((p >= 0) && at(p, n, ':')) {
  2787. if (p == 0)
  2788. failExpecting("scheme name", 0);
  2789. checkChar(0, L_ALPHA, H_ALPHA, "scheme name");
  2790. checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name");
  2791. scheme = substring(0, p);
  2792. p++; // Skip ':'
  2793. ssp = p;
  2794. if (at(p, n, '/')) {
  2795. p = parseHierarchical(p, n);
  2796. } else {
  2797. int q = scan(p, n, "", "#");
  2798. if (q <= p)
  2799. failExpecting("scheme-specific part", p);
  2800. checkChars(p, q, L_URIC, H_URIC, "opaque part");
  2801. p = q;
  2802. }
  2803. } else {
  2804. ssp = 0;
  2805. p = parseHierarchical(0, n);
  2806. }
  2807. schemeSpecificPart = substring(ssp, p);
  2808. if (at(p, n, '#')) {
  2809. checkChars(p + 1, n, L_URIC, H_URIC, "fragment");
  2810. fragment = substring(p + 1, n);
  2811. p = n;
  2812. }
  2813. if (p < n)
  2814. fail("end of URI", p);
  2815. }
  2816. // [//authority]<path>[?<query>]
  2817. //
  2818. // DEVIATION from RFC2396: We allow an empty authority component as
  2819. // long as it's followed by a non-empty path, query component, or
  2820. // fragment component. This is so that URIs such as "file:///foo/bar"
  2821. // will parse. This seems to be the intent of RFC2396, though the
  2822. // grammar does not permit it. If the authority is empty then the
  2823. // userInfo, host, and port components are undefined.
  2824. //
  2825. // DEVIATION from RFC2396: We allow empty relative paths. This seems
  2826. // to be the intent of RFC2396, but the grammar does not permit it.
  2827. // The primary consequence of this deviation is that "#f" parses as a
  2828. // relative URI with an empty path.
  2829. //
  2830. private int parseHierarchical(int start, int n)
  2831. throws URISyntaxException
  2832. {
  2833. int p = start;
  2834. if (at(p, n, '/') && at(p + 1, n, '/')) {
  2835. p += 2;
  2836. int q = scan(p, n, "", "/?#");
  2837. if (q > p) {
  2838. p = parseAuthority(p, q);
  2839. } else if (q < n) {
  2840. // DEVIATION: Allow empty authority prior to non-empty
  2841. // path, query component or fragment identifier
  2842. } else
  2843. failExpecting("authority", p);
  2844. }
  2845. int q = scan(p, n, "", "?#"); // DEVIATION: May be empty
  2846. checkChars(p, q, L_PATH, H_PATH, "path");
  2847. path = substring(p, q);
  2848. p = q;
  2849. if (at(p, n, '?')) {
  2850. p++;
  2851. q = scan(p, n, "", "#");
  2852. checkChars(p, q, L_URIC, H_URIC, "query");
  2853. query = substring(p, q);
  2854. p = q;
  2855. }
  2856. return p;
  2857. }
  2858. // authority = server | reg_name
  2859. //
  2860. // Ambiguity: An authority that is a registry name rather than a server
  2861. // might have a prefix that parses as a server. We use the fact that
  2862. // the authority component is always followed by '/' or the end of the
  2863. // input string to resolve this: If the complete authority did not
  2864. // parse as a server then we try to parse it as a registry name.
  2865. //
  2866. private int parseAuthority(int start, int n)
  2867. throws URISyntaxException
  2868. {
  2869. int p = start;
  2870. int q = p;
  2871. URISyntaxException ex = null;
  2872. boolean serverChars;
  2873. boolean regChars;
  2874. if (scan(p, n, "", "]") > p) {
  2875. // contains a literal IPv6 address, therefore % is allowed
  2876. serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n);
  2877. } else {
  2878. serverChars = (scan(p, n, L_SERVER, H_SERVER) == n);
  2879. }
  2880. regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n);
  2881. if (regChars && !serverChars) {
  2882. // Must be a registry-based authority
  2883. authority = substring(p, n);
  2884. return n;
  2885. }
  2886. if (serverChars) {
  2887. // Might be (probably is) a server-based authority, so attempt
  2888. // to parse it as such. If the attempt fails, try to treat it
  2889. // as a registry-based authority.
  2890. try {
  2891. q = parseServer(p, n);
  2892. if (q < n)
  2893. failExpecting("end of authority", q);
  2894. authority = substring(p, n);
  2895. } catch (URISyntaxException x) {
  2896. // Undo results of failed parse
  2897. userInfo = null;
  2898. host = null;
  2899. port = -1;
  2900. if (requireServerAuthority) {
  2901. // If we're insisting upon a server-based authority,
  2902. // then just re-throw the exception
  2903. throw x;
  2904. } else {
  2905. // Save the exception in case it doesn't parse as a
  2906. // registry either
  2907. ex = x;
  2908. q = p;
  2909. }
  2910. }
  2911. }
  2912. if (q < n) {
  2913. if (regChars) {
  2914. // Registry-based authority
  2915. authority = substring(p, n);
  2916. } else if (ex != null) {
  2917. // Re-throw exception; it was probably due to
  2918. // a malformed IPv6 address
  2919. throw ex;
  2920. } else {
  2921. fail("Illegal character in authority", q);
  2922. }
  2923. }
  2924. return n;
  2925. }
  2926. // [<userinfo>@]<host>[:<port>]
  2927. //
  2928. private int parseServer(int start, int n)
  2929. throws URISyntaxException
  2930. {
  2931. int p = start;
  2932. int q;
  2933. // userinfo
  2934. q = scan(p, n, "/?#", "@");
  2935. if ((q >= p) && at(q, n, '@')) {
  2936. checkChars(p, q, L_USERINFO, H_USERINFO, "user info");
  2937. userInfo = substring(p, q);
  2938. p = q + 1; // Skip '@'
  2939. }
  2940. // hostname, IPv4 address, or IPv6 address
  2941. if (at(p, n, '[')) {
  2942. // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732
  2943. p++;
  2944. q = scan(p, n, "/?#", "]");
  2945. if ((q > p) && at(q, n, ']')) {
  2946. // look for a "%" scope id
  2947. int r = scan (p, q, "", "%");
  2948. if (r > p) {
  2949. parseIPv6Reference(p, r);
  2950. if (r+1 == q) {
  2951. fail ("scope id expected");
  2952. }
  2953. checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM,
  2954. "scope id");
  2955. } else {
  2956. parseIPv6Reference(p, q);
  2957. }
  2958. host = substring(p-1, q+1);
  2959. p = q + 1;
  2960. } else {
  2961. failExpecting("closing bracket for IPv6 address", q);
  2962. }
  2963. } else {
  2964. q = parseIPv4Address(p, n);
  2965. if (q <= p)
  2966. q = parseHostname(p, n);
  2967. p = q;
  2968. }
  2969. // port
  2970. if (at(p, n, ':')) {
  2971. p++;
  2972. q = scan(p, n, "", "/");
  2973. if (q > p) {
  2974. checkChars(p, q, L_DIGIT, H_DIGIT, "port number");
  2975. try {
  2976. port = Integer.parseInt(substring(p, q));
  2977. } catch (NumberFormatException x) {
  2978. fail("Malformed port number", p);
  2979. }
  2980. p = q;
  2981. }
  2982. }
  2983. if (p < n)
  2984. failExpecting("port number", p);
  2985. return p;
  2986. }
  2987. // Scan a string of decimal digits whose value fits in a byte
  2988. //
  2989. private int scanByte(int start, int n)
  2990. throws URISyntaxException
  2991. {
  2992. int p = start;
  2993. int q = scan(p, n, L_DIGIT, H_DIGIT);
  2994. if (q <= p) return q;
  2995. if (Integer.parseInt(substring(p, q)) > 255) return p;
  2996. return q;
  2997. }
  2998. // Scan an IPv4 address.
  2999. //
  3000. // If the strict argument is true then we require that the given
  3001. // interval contain nothing besides an IPv4 address; if it is false
  3002. // then we only require that it start with an IPv4 address.
  3003. //
  3004. // If the interval does not contain or start with (depending upon the
  3005. // strict argument) a legal IPv4 address characters then we return -1
  3006. // immediately; otherwise we insist that these characters parse as a
  3007. // legal IPv4 address and throw an exception on failure.
  3008. //
  3009. // We assume that any string of decimal digits and dots must be an IPv4
  3010. // address. It won't parse as a hostname anyway, so making that
  3011. // assumption here allows more meaningful exceptions to be thrown.
  3012. //
  3013. private int scanIPv4Address(int start, int n, boolean strict)
  3014. throws URISyntaxException
  3015. {
  3016. int p = start;
  3017. int q;
  3018. int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT);
  3019. if ((m <= p) || (strict && (m != n)))
  3020. return -1;
  3021. for (;;) {
  3022. // Per RFC2732: At most three digits per byte
  3023. // Further constraint: Each element fits in a byte
  3024. if ((q = scanByte(p, m)) <= p) break; p = q;
  3025. if ((q = scan(p, m, '.')) <= p) break; p = q;
  3026. if ((q = scanByte(p, m)) <= p) break; p = q;
  3027. if ((q = scan(p, m, '.')) <= p) break; p = q;
  3028. if ((q = scanByte(p, m)) <= p) break; p = q;
  3029. if ((q = scan(p, m, '.')) <= p) break; p = q;
  3030. if ((q = scanByte(p, m)) <= p) break; p = q;
  3031. if (q < m) break;
  3032. return q;
  3033. }
  3034. fail("Malformed IPv4 address", q);
  3035. return -1;
  3036. }
  3037. // Take an IPv4 address: Throw an exception if the given interval
  3038. // contains anything except an IPv4 address
  3039. //
  3040. private int takeIPv4Address(int start, int n, String expected)
  3041. throws URISyntaxException
  3042. {
  3043. int p = scanIPv4Address(start, n, true);
  3044. if (p <= start)
  3045. failExpecting(expected, start);
  3046. return p;
  3047. }
  3048. // Attempt to parse an IPv4 address, returning -1 on failure but
  3049. // allowing the given interval to contain [:<characters>] after
  3050. // the IPv4 address.
  3051. //
  3052. private int parseIPv4Address(int start, int n) {
  3053. int p;
  3054. try {
  3055. p = scanIPv4Address(start, n, false);
  3056. } catch (URISyntaxException x) {
  3057. return -1;
  3058. } catch (NumberFormatException nfe) {
  3059. return -1;
  3060. }
  3061. if (p > start && p < n) {
  3062. // IPv4 address is followed by something - check that
  3063. // it's a ":" as this is the only valid character to
  3064. // follow an address.
  3065. if (charAt(p) != ':') {
  3066. p = -1;
  3067. }
  3068. }
  3069. if (p > start)
  3070. host = substring(start, p);
  3071. return p;
  3072. }
  3073. // hostname = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ]
  3074. // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  3075. // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  3076. //
  3077. private int parseHostname(int start, int n)
  3078. throws URISyntaxException
  3079. {
  3080. int p = start;
  3081. int q;
  3082. int l = -1; // Start of last parsed label
  3083. do {
  3084. // domainlabel = alphanum [ *( alphanum | "-" ) alphanum ]
  3085. q = scan(p, n, L_ALPHANUM, H_ALPHANUM);
  3086. if (q <= p)
  3087. break;
  3088. l = p;
  3089. if (q > p) {
  3090. p = q;
  3091. q = scan(p, n, L_ALPHANUM | L_DASH, H_ALPHANUM | H_DASH);
  3092. if (q > p) {
  3093. if (charAt(q - 1) == '-')
  3094. fail("Illegal character in hostname", q - 1);
  3095. p = q;
  3096. }
  3097. }
  3098. q = scan(p, n, '.');
  3099. if (q <= p)
  3100. break;
  3101. p = q;
  3102. } while (p < n);
  3103. if ((p < n) && !at(p, n, ':'))
  3104. fail("Illegal character in hostname", p);
  3105. if (l < 0)
  3106. failExpecting("hostname", start);
  3107. // for a fully qualified hostname check that the rightmost
  3108. // label starts with an alpha character.
  3109. if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) {
  3110. fail("Illegal character in hostname", l);
  3111. }
  3112. host = substring(start, p);
  3113. return p;
  3114. }
  3115. // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture
  3116. //
  3117. // Bug: The grammar in RFC2373 Appendix B does not allow addresses of
  3118. // the form ::12.34.56.78, which are clearly shown in the examples
  3119. // earlier in the document. Here is the original grammar:
  3120. //
  3121. // IPv6address = hexpart [ ":" IPv4address ]
  3122. // hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
  3123. // hexseq = hex4 *( ":" hex4)
  3124. // hex4 = 1*4HEXDIG
  3125. //
  3126. // We therefore use the following revised grammar:
  3127. //
  3128. // IPv6address = hexseq [ ":" IPv4address ]
  3129. // | hexseq [ "::" [ hexpost ] ]
  3130. // | "::" [ hexpost ]
  3131. // hexpost = hexseq | hexseq ":" IPv4address | IPv4address
  3132. // hexseq = hex4 *( ":" hex4)
  3133. // hex4 = 1*4HEXDIG
  3134. //
  3135. // This covers all and only the following cases:
  3136. //
  3137. // hexseq
  3138. // hexseq : IPv4address
  3139. // hexseq ::
  3140. // hexseq :: hexseq
  3141. // hexseq :: hexseq : IPv4address
  3142. // hexseq :: IPv4address
  3143. // :: hexseq
  3144. // :: hexseq : IPv4address
  3145. // :: IPv4address
  3146. // ::
  3147. //
  3148. // Additionally we constrain the IPv6 address as follows :-
  3149. //
  3150. // i. IPv6 addresses without compressed zeros should contain
  3151. // exactly 16 bytes.
  3152. //
  3153. // ii. IPv6 addresses with compressed zeros should contain
  3154. // less than 16 bytes.
  3155. private int ipv6byteCount = 0;
  3156. private int parseIPv6Reference(int start, int n)
  3157. throws URISyntaxException
  3158. {
  3159. int p = start;
  3160. int q;
  3161. boolean compressedZeros = false;
  3162. q = scanHexSeq(p, n);
  3163. if (q > p) {
  3164. p = q;
  3165. if (at(p, n, "::")) {
  3166. compressedZeros = true;
  3167. p = scanHexPost(p + 2, n);
  3168. } else if (at(p, n, ':')) {
  3169. p = takeIPv4Address(p + 1, n, "IPv4 address");
  3170. ipv6byteCount += 4;
  3171. }
  3172. } else if (at(p, n, "::")) {
  3173. compressedZeros = true;
  3174. p = scanHexPost(p + 2, n);
  3175. }
  3176. if (p < n)
  3177. fail("Malformed IPv6 address", start);
  3178. if (ipv6byteCount > 16)
  3179. fail("IPv6 address too long", start);
  3180. if (!compressedZeros && ipv6byteCount < 16)
  3181. fail("IPv6 address too short", start);
  3182. if (compressedZeros && ipv6byteCount == 16)
  3183. fail("Malformed IPv6 address", start);
  3184. return p;
  3185. }
  3186. private int scanHexPost(int start, int n)
  3187. throws URISyntaxException
  3188. {
  3189. int p = start;
  3190. int q;
  3191. if (p == n)
  3192. return p;
  3193. q = scanHexSeq(p, n);
  3194. if (q > p) {
  3195. p = q;
  3196. if (at(p, n, ':')) {
  3197. p++;
  3198. p = takeIPv4Address(p, n, "hex digits or IPv4 address");
  3199. ipv6byteCount += 4;
  3200. }
  3201. } else {
  3202. p = takeIPv4Address(p, n, "hex digits or IPv4 address");
  3203. ipv6byteCount += 4;
  3204. }
  3205. return p;
  3206. }
  3207. // Scan a hex sequence; return -1 if one could not be scanned
  3208. //
  3209. private int scanHexSeq(int start, int n)
  3210. throws URISyntaxException
  3211. {
  3212. int p = start;
  3213. int q;
  3214. q = scan(p, n, L_HEX, H_HEX);
  3215. if (q <= p)
  3216. return -1;
  3217. if (at(q, n, '.')) // Beginning of IPv4 address
  3218. return -1;
  3219. if (q > p + 4)
  3220. fail("IPv6 hexadecimal digit sequence too long", p);
  3221. ipv6byteCount += 2;
  3222. p = q;
  3223. while (p < n) {
  3224. if (!at(p, n, ':'))
  3225. break;
  3226. if (at(p + 1, n, ':'))
  3227. break; // "::"
  3228. p++;
  3229. q = scan(p, n, L_HEX, H_HEX);
  3230. if (q <= p)
  3231. failExpecting("digits for an IPv6 address", p);
  3232. if (at(q, n, '.')) { // Beginning of IPv4 address
  3233. p--;
  3234. break;
  3235. }
  3236. if (q > p + 4)
  3237. fail("IPv6 hexadecimal digit sequence too long", p);
  3238. ipv6byteCount += 2;
  3239. p = q;
  3240. }
  3241. return p;
  3242. }
  3243. }
  3244. }