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