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