jaroslav@1258: /* jaroslav@1258: * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. jaroslav@1258: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1258: * jaroslav@1258: * This code is free software; you can redistribute it and/or modify it jaroslav@1258: * under the terms of the GNU General Public License version 2 only, as jaroslav@1258: * published by the Free Software Foundation. Oracle designates this jaroslav@1258: * particular file as subject to the "Classpath" exception as provided jaroslav@1258: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1258: * jaroslav@1258: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1258: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1258: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1258: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1258: * accompanied this code). jaroslav@1258: * jaroslav@1258: * You should have received a copy of the GNU General Public License version jaroslav@1258: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1258: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1258: * jaroslav@1258: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1258: * or visit www.oracle.com if you need additional information or have any jaroslav@1258: * questions. jaroslav@1258: */ jaroslav@1258: jaroslav@1258: package java.net; jaroslav@1258: jaroslav@1258: import java.io.IOException; jaroslav@1258: import java.io.InvalidObjectException; jaroslav@1258: import java.io.ObjectInputStream; jaroslav@1258: import java.io.ObjectOutputStream; jaroslav@1258: import java.io.Serializable; jaroslav@1258: import java.nio.ByteBuffer; jaroslav@1258: import java.nio.CharBuffer; jaroslav@1258: import java.nio.charset.CharsetDecoder; jaroslav@1258: import java.nio.charset.CharsetEncoder; jaroslav@1258: import java.nio.charset.CoderResult; jaroslav@1258: import java.nio.charset.CodingErrorAction; jaroslav@1258: import java.nio.charset.CharacterCodingException; jaroslav@1258: import java.text.Normalizer; jaroslav@1258: import sun.nio.cs.ThreadLocalCoders; jaroslav@1258: jaroslav@1258: import java.lang.Character; // for javadoc jaroslav@1258: import java.lang.NullPointerException; // for javadoc jaroslav@1258: jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Represents a Uniform Resource Identifier (URI) reference. jaroslav@1258: * jaroslav@1258: *

Aside from some minor deviations noted below, an instance of this jaroslav@1258: * class represents a URI reference as defined by jaroslav@1258: * RFC 2396: Uniform jaroslav@1258: * Resource Identifiers (URI): Generic Syntax, amended by RFC 2732: Format for jaroslav@1258: * Literal IPv6 Addresses in URLs. The Literal IPv6 address format jaroslav@1258: * also supports scope_ids. The syntax and usage of scope_ids is described jaroslav@1258: * here. jaroslav@1258: * This class provides constructors for creating URI instances from jaroslav@1258: * their components or by parsing their string forms, methods for accessing the jaroslav@1258: * various components of an instance, and methods for normalizing, resolving, jaroslav@1258: * and relativizing URI instances. Instances of this class are immutable. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

URI syntax and components

jaroslav@1258: * jaroslav@1258: * At the highest level a URI reference (hereinafter simply "URI") in string jaroslav@1258: * form has the syntax jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * [scheme:]scheme-specific-part[#fragment] jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * where square brackets [...] delineate optional components and the characters jaroslav@1258: * : and # stand for themselves. jaroslav@1258: * jaroslav@1258: *

An absolute URI specifies a scheme; a URI that is not absolute is jaroslav@1258: * said to be relative. URIs are also classified according to whether jaroslav@1258: * they are opaque or hierarchical. jaroslav@1258: * jaroslav@1258: *

An opaque URI is an absolute URI whose scheme-specific part does jaroslav@1258: * not begin with a slash character ('/'). Opaque URIs are not jaroslav@1258: * subject to further parsing. Some examples of opaque URIs are: jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *
mailto:java-net@java.sun.com
news:comp.lang.java
urn:isbn:096139210x
jaroslav@1258: * jaroslav@1258: *

A hierarchical URI is either an absolute URI whose jaroslav@1258: * scheme-specific part begins with a slash character, or a relative URI, that jaroslav@1258: * is, a URI that does not specify a scheme. Some examples of hierarchical jaroslav@1258: * URIs are: jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * http://java.sun.com/j2se/1.3/
jaroslav@1258: * docs/guide/collections/designfaq.html#28
jaroslav@1258: * ../../../demo/jfc/SwingSet2/src/SwingSet2.java
jaroslav@1258: * file:///~/calendar jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

A hierarchical URI is subject to further parsing according to the syntax jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * [scheme:][//authority][path][?query][#fragment] jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * where the characters :, /, jaroslav@1258: * ?, and # stand for themselves. The jaroslav@1258: * scheme-specific part of a hierarchical URI consists of the characters jaroslav@1258: * between the scheme and fragment components. jaroslav@1258: * jaroslav@1258: *

The authority component of a hierarchical URI is, if specified, either jaroslav@1258: * server-based or registry-based. A server-based authority jaroslav@1258: * parses according to the familiar syntax jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * [user-info@]host[:port] jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * where the characters @ and : stand for jaroslav@1258: * themselves. Nearly all URI schemes currently in use are server-based. An jaroslav@1258: * authority component that does not parse in this way is considered to be jaroslav@1258: * registry-based. jaroslav@1258: * jaroslav@1258: *

The path component of a hierarchical URI is itself said to be absolute jaroslav@1258: * if it begins with a slash character ('/'); otherwise it is jaroslav@1258: * relative. The path of a hierarchical URI that is either absolute or jaroslav@1258: * specifies an authority is always absolute. jaroslav@1258: * jaroslav@1258: *

All told, then, a URI instance has the following nine components: jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *
ComponentType
schemeString
scheme-specific-part    String
authorityString
user-infoString
hostString
portint
pathString
queryString
fragmentString
jaroslav@1258: * jaroslav@1258: * In a given instance any particular component is either undefined or jaroslav@1258: * defined with a distinct value. Undefined string components are jaroslav@1258: * represented by null, while undefined integer components are jaroslav@1258: * represented by -1. A string component may be defined to have the jaroslav@1258: * empty string as its value; this is not equivalent to that component being jaroslav@1258: * undefined. jaroslav@1258: * jaroslav@1258: *

Whether a particular component is or is not defined in an instance jaroslav@1258: * depends upon the type of the URI being represented. An absolute URI has a jaroslav@1258: * scheme component. An opaque URI has a scheme, a scheme-specific part, and jaroslav@1258: * possibly a fragment, but has no other components. A hierarchical URI always jaroslav@1258: * has a path (though it may be empty) and a scheme-specific-part (which at jaroslav@1258: * least contains the path), and may have any of the other components. If the jaroslav@1258: * authority component is present and is server-based then the host component jaroslav@1258: * will be defined and the user-information and port components may be defined. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

Operations on URI instances

jaroslav@1258: * jaroslav@1258: * The key operations supported by this class are those of jaroslav@1258: * normalization, resolution, and relativization. jaroslav@1258: * jaroslav@1258: *

Normalization is the process of removing unnecessary "." jaroslav@1258: * and ".." segments from the path component of a hierarchical URI. jaroslav@1258: * Each "." segment is simply removed. A ".." segment is jaroslav@1258: * removed only if it is preceded by a non-".." segment. jaroslav@1258: * Normalization has no effect upon opaque URIs. jaroslav@1258: * jaroslav@1258: *

Resolution is the process of resolving one URI against another, jaroslav@1258: * base URI. The resulting URI is constructed from components of both jaroslav@1258: * URIs in the manner specified by RFC 2396, taking components from the jaroslav@1258: * base URI for those not specified in the original. For hierarchical URIs, jaroslav@1258: * the path of the original is resolved against the path of the base and then jaroslav@1258: * normalized. The result, for example, of resolving jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * docs/guide/collections/designfaq.html#28          (1) jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * against the base URI http://java.sun.com/j2se/1.3/ is the result jaroslav@1258: * URI jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * http://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28 jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * Resolving the relative URI jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * ../../../demo/jfc/SwingSet2/src/SwingSet2.java    (2) jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * against this result yields, in turn, jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * http://java.sun.com/j2se/1.3/demo/jfc/SwingSet2/src/SwingSet2.java jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * Resolution of both absolute and relative URIs, and of both absolute and jaroslav@1258: * relative paths in the case of hierarchical URIs, is supported. Resolving jaroslav@1258: * the URI file:///~calendar against any other URI simply yields the jaroslav@1258: * original URI, since it is absolute. Resolving the relative URI (2) above jaroslav@1258: * against the relative base URI (1) yields the normalized, but still relative, jaroslav@1258: * URI jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * demo/jfc/SwingSet2/src/SwingSet2.java jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

Relativization, finally, is the inverse of resolution: For any jaroslav@1258: * two normalized URIs u and v, jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * u.relativize(u.resolve(v)).equals(v)  and
jaroslav@1258: * u.resolve(u.relativize(v)).equals(v)  .
jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * This operation is often useful when constructing a document containing URIs jaroslav@1258: * that must be made relative to the base URI of the document wherever jaroslav@1258: * possible. For example, relativizing the URI jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * http://java.sun.com/j2se/1.3/docs/guide/index.html jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * against the base URI jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * http://java.sun.com/j2se/1.3 jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * yields the relative URI docs/guide/index.html. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

Character categories

jaroslav@1258: * jaroslav@1258: * RFC 2396 specifies precisely which characters are permitted in the jaroslav@1258: * various components of a URI reference. The following categories, most of jaroslav@1258: * which are taken from that specification, are used below to describe these jaroslav@1258: * constraints: jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *
alphaThe US-ASCII alphabetic characters, jaroslav@1258: * 'A' through 'Z' jaroslav@1258: * and 'a' through 'z'
digitThe US-ASCII decimal digit characters, jaroslav@1258: * '0' through '9'
alphanumAll alpha and digit characters
unreserved    All alphanum characters together with those in the string jaroslav@1258: * "_-!.~'()*"
punctThe characters in the string ",;:$&+="
reservedAll punct characters together with those in the string jaroslav@1258: * "?/[]@"
escapedEscaped octets, that is, triplets consisting of the percent jaroslav@1258: * character ('%') followed by two hexadecimal digits jaroslav@1258: * ('0'-'9', 'A'-'F', and jaroslav@1258: * 'a'-'f')
otherThe Unicode characters that are not in the US-ASCII character set, jaroslav@1258: * are not control characters (according to the {@link jaroslav@1258: * java.lang.Character#isISOControl(char) Character.isISOControl} jaroslav@1258: * method), and are not space characters (according to the {@link jaroslav@1258: * java.lang.Character#isSpaceChar(char) Character.isSpaceChar} jaroslav@1258: * method)  (Deviation from RFC 2396, which is jaroslav@1258: * limited to US-ASCII)
jaroslav@1258: * jaroslav@1258: *

The set of all legal URI characters consists of jaroslav@1258: * the unreserved, reserved, escaped, and other jaroslav@1258: * characters. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

Escaped octets, quotation, encoding, and decoding

jaroslav@1258: * jaroslav@1258: * RFC 2396 allows escaped octets to appear in the user-info, path, query, and jaroslav@1258: * fragment components. Escaping serves two purposes in URIs: jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * These purposes are served in this class by three related operations: jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * These operations are exposed in the constructors and methods of this class jaroslav@1258: * as follows: jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

Identities

jaroslav@1258: * jaroslav@1258: * For any URI u, it is always the case that jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * new URI(u.toString()).equals(u) . jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * For any URI u that does not contain redundant syntax such as two jaroslav@1258: * slashes before an empty authority (as in file:///tmp/ ) or a jaroslav@1258: * colon following a host name but no port (as in jaroslav@1258: * http://java.sun.com: ), and that does not encode characters jaroslav@1258: * except those that must be quoted, the following identities also hold: jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * new URI(u.getScheme(),
jaroslav@1258: *         
u.getSchemeSpecificPart(),
jaroslav@1258: *         
u.getFragment())
jaroslav@1258: * .equals(
u) jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * in all cases, jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * new URI(u.getScheme(),
jaroslav@1258: *         
u.getUserInfo(), u.getAuthority(),
jaroslav@1258: *         
u.getPath(), u.getQuery(),
jaroslav@1258: *         
u.getFragment())
jaroslav@1258: * .equals(
u) jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * if u is hierarchical, and jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * new URI(u.getScheme(),
jaroslav@1258: *         
u.getUserInfo(), u.getHost(), u.getPort(),
jaroslav@1258: *         
u.getPath(), u.getQuery(),
jaroslav@1258: *         
u.getFragment())
jaroslav@1258: * .equals(
u) jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * if u is hierarchical and has either no authority or a server-based jaroslav@1258: * authority. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

URIs, URLs, and URNs

jaroslav@1258: * jaroslav@1258: * A URI is a uniform resource identifier while a URL is a uniform jaroslav@1258: * resource locator. Hence every URL is a URI, abstractly speaking, but jaroslav@1258: * not every URI is a URL. This is because there is another subcategory of jaroslav@1258: * URIs, uniform resource names (URNs), which name resources but do not jaroslav@1258: * specify how to locate them. The mailto, news, and jaroslav@1258: * isbn URIs shown above are examples of URNs. jaroslav@1258: * jaroslav@1258: *

The conceptual distinction between URIs and URLs is reflected in the jaroslav@1258: * differences between this class and the {@link URL} class. jaroslav@1258: * jaroslav@1258: *

An instance of this class represents a URI reference in the syntactic jaroslav@1258: * sense defined by RFC 2396. A URI may be either absolute or relative. jaroslav@1258: * A URI string is parsed according to the generic syntax without regard to the jaroslav@1258: * scheme, if any, that it specifies. No lookup of the host, if any, is jaroslav@1258: * performed, and no scheme-dependent stream handler is constructed. Equality, jaroslav@1258: * hashing, and comparison are defined strictly in terms of the character jaroslav@1258: * content of the instance. In other words, a URI instance is little more than jaroslav@1258: * a structured string that supports the syntactic, scheme-independent jaroslav@1258: * operations of comparison, normalization, resolution, and relativization. jaroslav@1258: * jaroslav@1258: *

An instance of the {@link URL} class, by contrast, represents the jaroslav@1258: * syntactic components of a URL together with some of the information required jaroslav@1258: * to access the resource that it describes. A URL must be absolute, that is, jaroslav@1258: * it must always specify a scheme. A URL string is parsed according to its jaroslav@1258: * scheme. A stream handler is always established for a URL, and in fact it is jaroslav@1258: * impossible to create a URL instance for a scheme for which no handler is jaroslav@1258: * available. Equality and hashing depend upon both the scheme and the jaroslav@1258: * Internet address of the host, if any; comparison is not defined. In other jaroslav@1258: * words, a URL is a structured string that supports the syntactic operation of jaroslav@1258: * resolution as well as the network I/O operations of looking up the host and jaroslav@1258: * opening a connection to the specified resource. jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * @author Mark Reinhold jaroslav@1258: * @since 1.4 jaroslav@1258: * jaroslav@1258: * @see RFC 2279: UTF-8, a jaroslav@1258: * transformation format of ISO 10646,
RFC 2373: IPv6 Addressing jaroslav@1258: * Architecture,
RFC 2396: Uniform jaroslav@1258: * Resource Identifiers (URI): Generic Syntax,
RFC 2732: Format for jaroslav@1258: * Literal IPv6 Addresses in URLs,
URISyntaxException jaroslav@1258: */ jaroslav@1258: jaroslav@1258: public final class URI jaroslav@1258: implements Comparable, Serializable jaroslav@1258: { jaroslav@1258: jaroslav@1258: // Note: Comments containing the word "ASSERT" indicate places where a jaroslav@1258: // throw of an InternalError should be replaced by an appropriate assertion jaroslav@1258: // statement once asserts are enabled in the build. jaroslav@1258: jaroslav@1258: static final long serialVersionUID = -6052424284110960213L; jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Properties and components of this instance -- jaroslav@1258: jaroslav@1258: // Components of all URIs: [:][#] jaroslav@1258: private transient String scheme; // null ==> relative URI jaroslav@1258: private transient String fragment; jaroslav@1258: jaroslav@1258: // Hierarchical URI components: [//][?] jaroslav@1258: private transient String authority; // Registry or server jaroslav@1258: jaroslav@1258: // Server-based authority: [@][:] jaroslav@1258: private transient String userInfo; jaroslav@1258: private transient String host; // null ==> registry-based jaroslav@1258: private transient int port = -1; // -1 ==> undefined jaroslav@1258: jaroslav@1258: // Remaining components of hierarchical URIs jaroslav@1258: private transient String path; // null ==> opaque jaroslav@1258: private transient String query; jaroslav@1258: jaroslav@1258: // The remaining fields may be computed on demand jaroslav@1258: jaroslav@1258: private volatile transient String schemeSpecificPart; jaroslav@1258: private volatile transient int hash; // Zero ==> undefined jaroslav@1258: jaroslav@1258: private volatile transient String decodedUserInfo = null; jaroslav@1258: private volatile transient String decodedAuthority = null; jaroslav@1258: private volatile transient String decodedPath = null; jaroslav@1258: private volatile transient String decodedQuery = null; jaroslav@1258: private volatile transient String decodedFragment = null; jaroslav@1258: private volatile transient String decodedSchemeSpecificPart = null; jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * The string form of this URI. jaroslav@1258: * jaroslav@1258: * @serial jaroslav@1258: */ jaroslav@1258: private volatile String string; // The only serializable field jaroslav@1258: jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Constructors and factories -- jaroslav@1258: jaroslav@1258: private URI() { } // Used internally jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a URI by parsing the given string. jaroslav@1258: * jaroslav@1258: *

This constructor parses the given string exactly as specified by the jaroslav@1258: * grammar in RFC 2396, jaroslav@1258: * Appendix A, except for the following deviations:

jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * @param str The string to be parsed into a URI jaroslav@1258: * jaroslav@1258: * @throws NullPointerException jaroslav@1258: * If str is null jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If the given string violates RFC 2396, as augmented jaroslav@1258: * by the above deviations jaroslav@1258: */ jaroslav@1258: public URI(String str) throws URISyntaxException { jaroslav@1258: new Parser(str).parse(false); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a hierarchical URI from the given components. jaroslav@1258: * jaroslav@1258: *

If a scheme is given then the path, if also given, must either be jaroslav@1258: * empty or begin with a slash character ('/'). Otherwise a jaroslav@1258: * component of the new URI may be left undefined by passing null jaroslav@1258: * for the corresponding parameter or, in the case of the port jaroslav@1258: * parameter, by passing -1. jaroslav@1258: * jaroslav@1258: *

This constructor first builds a URI string from the given components jaroslav@1258: * according to the rules specified in RFC 2396, jaroslav@1258: * section 5.2, step 7:

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. Initially, the result string is empty.

  2. jaroslav@1258: * jaroslav@1258: *
  3. If a scheme is given then it is appended to the result, jaroslav@1258: * followed by a colon character (':').

  4. jaroslav@1258: * jaroslav@1258: *
  5. If user information, a host, or a port are given then the jaroslav@1258: * string "//" is appended.

  6. jaroslav@1258: * jaroslav@1258: *
  7. If user information is given then it is appended, followed by jaroslav@1258: * a commercial-at character ('@'). Any character not in the jaroslav@1258: * unreserved, punct, escaped, or other jaroslav@1258: * categories is quoted.

  8. jaroslav@1258: * jaroslav@1258: *
  9. If a host is given then it is appended. If the host is a jaroslav@1258: * literal IPv6 address but is not enclosed in square brackets jaroslav@1258: * ('[' and ']') then the square brackets are added. jaroslav@1258: *

  10. jaroslav@1258: * jaroslav@1258: *
  11. If a port number is given then a colon character jaroslav@1258: * (':') is appended, followed by the port number in decimal. jaroslav@1258: *

  12. jaroslav@1258: * jaroslav@1258: *
  13. If a path is given then it is appended. Any character not in jaroslav@1258: * the unreserved, punct, escaped, or other jaroslav@1258: * categories, and not equal to the slash character ('/') or the jaroslav@1258: * commercial-at character ('@'), is quoted.

  14. jaroslav@1258: * jaroslav@1258: *
  15. If a query is given then a question-mark character jaroslav@1258: * ('?') is appended, followed by the query. Any character that jaroslav@1258: * is not a legal URI character is quoted. jaroslav@1258: *

  16. jaroslav@1258: * jaroslav@1258: *
  17. Finally, if a fragment is given then a hash character jaroslav@1258: * ('#') is appended, followed by the fragment. Any character jaroslav@1258: * that is not a legal URI character is quoted.

  18. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

The resulting URI string is then parsed as if by invoking the {@link jaroslav@1258: * #URI(String)} constructor and then invoking the {@link jaroslav@1258: * #parseServerAuthority()} method upon the result; this may cause a {@link jaroslav@1258: * URISyntaxException} to be thrown.

jaroslav@1258: * jaroslav@1258: * @param scheme Scheme name jaroslav@1258: * @param userInfo User name and authorization information jaroslav@1258: * @param host Host name jaroslav@1258: * @param port Port number jaroslav@1258: * @param path Path jaroslav@1258: * @param query Query jaroslav@1258: * @param fragment Fragment jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If both a scheme and a path are given but the path is relative, jaroslav@1258: * if the URI string constructed from the given components violates jaroslav@1258: * RFC 2396, or if the authority component of the string is jaroslav@1258: * present but cannot be parsed as a server-based authority jaroslav@1258: */ jaroslav@1258: public URI(String scheme, jaroslav@1258: String userInfo, String host, int port, jaroslav@1258: String path, String query, String fragment) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: String s = toString(scheme, null, jaroslav@1258: null, userInfo, host, port, jaroslav@1258: path, query, fragment); jaroslav@1258: checkPath(s, scheme, path); jaroslav@1258: new Parser(s).parse(true); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a hierarchical URI from the given components. jaroslav@1258: * jaroslav@1258: *

If a scheme is given then the path, if also given, must either be jaroslav@1258: * empty or begin with a slash character ('/'). Otherwise a jaroslav@1258: * component of the new URI may be left undefined by passing null jaroslav@1258: * for the corresponding parameter. jaroslav@1258: * jaroslav@1258: *

This constructor first builds a URI string from the given components jaroslav@1258: * according to the rules specified in RFC 2396, jaroslav@1258: * section 5.2, step 7:

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. Initially, the result string is empty.

  2. jaroslav@1258: * jaroslav@1258: *
  3. If a scheme is given then it is appended to the result, jaroslav@1258: * followed by a colon character (':').

  4. jaroslav@1258: * jaroslav@1258: *
  5. If an authority is given then the string "//" is jaroslav@1258: * appended, followed by the authority. If the authority contains a jaroslav@1258: * literal IPv6 address then the address must be enclosed in square jaroslav@1258: * brackets ('[' and ']'). Any character not in the jaroslav@1258: * unreserved, punct, escaped, or other jaroslav@1258: * categories, and not equal to the commercial-at character jaroslav@1258: * ('@'), is quoted.

  6. jaroslav@1258: * jaroslav@1258: *
  7. If a path is given then it is appended. Any character not in jaroslav@1258: * the unreserved, punct, escaped, or other jaroslav@1258: * categories, and not equal to the slash character ('/') or the jaroslav@1258: * commercial-at character ('@'), is quoted.

  8. jaroslav@1258: * jaroslav@1258: *
  9. If a query is given then a question-mark character jaroslav@1258: * ('?') is appended, followed by the query. Any character that jaroslav@1258: * is not a legal URI character is quoted. jaroslav@1258: *

  10. jaroslav@1258: * jaroslav@1258: *
  11. Finally, if a fragment is given then a hash character jaroslav@1258: * ('#') is appended, followed by the fragment. Any character jaroslav@1258: * that is not a legal URI character is quoted.

  12. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

The resulting URI string is then parsed as if by invoking the {@link jaroslav@1258: * #URI(String)} constructor and then invoking the {@link jaroslav@1258: * #parseServerAuthority()} method upon the result; this may cause a {@link jaroslav@1258: * URISyntaxException} to be thrown.

jaroslav@1258: * jaroslav@1258: * @param scheme Scheme name jaroslav@1258: * @param authority Authority jaroslav@1258: * @param path Path jaroslav@1258: * @param query Query jaroslav@1258: * @param fragment Fragment jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If both a scheme and a path are given but the path is relative, jaroslav@1258: * if the URI string constructed from the given components violates jaroslav@1258: * RFC 2396, or if the authority component of the string is jaroslav@1258: * present but cannot be parsed as a server-based authority jaroslav@1258: */ jaroslav@1258: public URI(String scheme, jaroslav@1258: String authority, jaroslav@1258: String path, String query, String fragment) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: String s = toString(scheme, null, jaroslav@1258: authority, null, null, -1, jaroslav@1258: path, query, fragment); jaroslav@1258: checkPath(s, scheme, path); jaroslav@1258: new Parser(s).parse(false); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a hierarchical URI from the given components. jaroslav@1258: * jaroslav@1258: *

A component may be left undefined by passing null. jaroslav@1258: * jaroslav@1258: *

This convenience constructor works as if by invoking the jaroslav@1258: * seven-argument constructor as follows: jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * new {@link #URI(String, String, String, int, String, String, String) jaroslav@1258: * URI}(scheme, null, host, -1, path, null, fragment); jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * @param scheme Scheme name jaroslav@1258: * @param host Host name jaroslav@1258: * @param path Path jaroslav@1258: * @param fragment Fragment jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If the URI string constructed from the given components jaroslav@1258: * violates RFC 2396 jaroslav@1258: */ jaroslav@1258: public URI(String scheme, String host, String path, String fragment) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: this(scheme, null, host, -1, path, null, fragment); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a URI from the given components. jaroslav@1258: * jaroslav@1258: *

A component may be left undefined by passing null. jaroslav@1258: * jaroslav@1258: *

This constructor first builds a URI in string form using the given jaroslav@1258: * components as follows:

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. Initially, the result string is empty.

  2. jaroslav@1258: * jaroslav@1258: *
  3. If a scheme is given then it is appended to the result, jaroslav@1258: * followed by a colon character (':').

  4. jaroslav@1258: * jaroslav@1258: *
  5. If a scheme-specific part is given then it is appended. Any jaroslav@1258: * character that is not a legal URI character jaroslav@1258: * is quoted.

  6. jaroslav@1258: * jaroslav@1258: *
  7. Finally, if a fragment is given then a hash character jaroslav@1258: * ('#') is appended to the string, followed by the fragment. jaroslav@1258: * Any character that is not a legal URI character is quoted.

  8. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

The resulting URI string is then parsed in order to create the new jaroslav@1258: * URI instance as if by invoking the {@link #URI(String)} constructor; jaroslav@1258: * this may cause a {@link URISyntaxException} to be thrown.

jaroslav@1258: * jaroslav@1258: * @param scheme Scheme name jaroslav@1258: * @param ssp Scheme-specific part jaroslav@1258: * @param fragment Fragment jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If the URI string constructed from the given components jaroslav@1258: * violates RFC 2396 jaroslav@1258: */ jaroslav@1258: public URI(String scheme, String ssp, String fragment) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: new Parser(toString(scheme, ssp, jaroslav@1258: null, null, null, -1, jaroslav@1258: null, null, fragment)) jaroslav@1258: .parse(false); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Creates a URI by parsing the given string. jaroslav@1258: * jaroslav@1258: *

This convenience factory method works as if by invoking the {@link jaroslav@1258: * #URI(String)} constructor; any {@link URISyntaxException} thrown by the jaroslav@1258: * constructor is caught and wrapped in a new {@link jaroslav@1258: * IllegalArgumentException} object, which is then thrown. jaroslav@1258: * jaroslav@1258: *

This method is provided for use in situations where it is known that jaroslav@1258: * the given string is a legal URI, for example for URI constants declared jaroslav@1258: * within in a program, and so it would be considered a programming error jaroslav@1258: * for the string not to parse as such. The constructors, which throw jaroslav@1258: * {@link URISyntaxException} directly, should be used situations where a jaroslav@1258: * URI is being constructed from user input or from some other source that jaroslav@1258: * may be prone to errors.

jaroslav@1258: * jaroslav@1258: * @param str The string to be parsed into a URI jaroslav@1258: * @return The new URI jaroslav@1258: * jaroslav@1258: * @throws NullPointerException jaroslav@1258: * If str is null jaroslav@1258: * jaroslav@1258: * @throws IllegalArgumentException jaroslav@1258: * If the given string violates RFC 2396 jaroslav@1258: */ jaroslav@1258: public static URI create(String str) { jaroslav@1258: try { jaroslav@1258: return new URI(str); jaroslav@1258: } catch (URISyntaxException x) { jaroslav@1258: throw new IllegalArgumentException(x.getMessage(), x); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Operations -- jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Attempts to parse this URI's authority component, if defined, into jaroslav@1258: * user-information, host, and port components. jaroslav@1258: * jaroslav@1258: *

If this URI's authority component has already been recognized as jaroslav@1258: * being server-based then it will already have been parsed into jaroslav@1258: * user-information, host, and port components. In this case, or if this jaroslav@1258: * URI has no authority component, this method simply returns this URI. jaroslav@1258: * jaroslav@1258: *

Otherwise this method attempts once more to parse the authority jaroslav@1258: * component into user-information, host, and port components, and throws jaroslav@1258: * an exception describing why the authority component could not be parsed jaroslav@1258: * in that way. jaroslav@1258: * jaroslav@1258: *

This method is provided because the generic URI syntax specified in jaroslav@1258: * RFC 2396 jaroslav@1258: * cannot always distinguish a malformed server-based authority from a jaroslav@1258: * legitimate registry-based authority. It must therefore treat some jaroslav@1258: * instances of the former as instances of the latter. The authority jaroslav@1258: * component in the URI string "//foo:bar", for example, is not a jaroslav@1258: * legal server-based authority but it is legal as a registry-based jaroslav@1258: * authority. jaroslav@1258: * jaroslav@1258: *

In many common situations, for example when working URIs that are jaroslav@1258: * known to be either URNs or URLs, the hierarchical URIs being used will jaroslav@1258: * always be server-based. They therefore must either be parsed as such or jaroslav@1258: * treated as an error. In these cases a statement such as jaroslav@1258: * jaroslav@1258: *

jaroslav@1258: * URI u = new URI(str).parseServerAuthority(); jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

can be used to ensure that u always refers to a URI that, if jaroslav@1258: * it has an authority component, has a server-based authority with proper jaroslav@1258: * user-information, host, and port components. Invoking this method also jaroslav@1258: * ensures that if the authority could not be parsed in that way then an jaroslav@1258: * appropriate diagnostic message can be issued based upon the exception jaroslav@1258: * that is thrown.

jaroslav@1258: * jaroslav@1258: * @return A URI whose authority field has been parsed jaroslav@1258: * as a server-based authority jaroslav@1258: * jaroslav@1258: * @throws URISyntaxException jaroslav@1258: * If the authority component of this URI is defined jaroslav@1258: * but cannot be parsed as a server-based authority jaroslav@1258: * according to RFC 2396 jaroslav@1258: */ jaroslav@1258: public URI parseServerAuthority() jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: // We could be clever and cache the error message and index from the jaroslav@1258: // exception thrown during the original parse, but that would require jaroslav@1258: // either more fields or a more-obscure representation. jaroslav@1258: if ((host != null) || (authority == null)) jaroslav@1258: return this; jaroslav@1258: defineString(); jaroslav@1258: new Parser(string).parse(true); jaroslav@1258: return this; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Normalizes this URI's path. jaroslav@1258: * jaroslav@1258: *

If this URI is opaque, or if its path is already in normal form, jaroslav@1258: * then this URI is returned. Otherwise a new URI is constructed that is jaroslav@1258: * identical to this URI except that its path is computed by normalizing jaroslav@1258: * this URI's path in a manner consistent with RFC 2396, jaroslav@1258: * section 5.2, step 6, sub-steps c through f; that is: jaroslav@1258: *

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. All "." segments are removed.

  2. jaroslav@1258: * jaroslav@1258: *
  3. If a ".." segment is preceded by a non-".." jaroslav@1258: * segment then both of these segments are removed. This step is jaroslav@1258: * repeated until it is no longer applicable.

  4. jaroslav@1258: * jaroslav@1258: *
  5. If the path is relative, and if its first segment contains a jaroslav@1258: * colon character (':'), then a "." segment is jaroslav@1258: * prepended. This prevents a relative URI with a path such as jaroslav@1258: * "a:b/c/d" from later being re-parsed as an opaque URI with a jaroslav@1258: * scheme of "a" and a scheme-specific part of "b/c/d". jaroslav@1258: * (Deviation from RFC 2396)

  6. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

A normalized path will begin with one or more ".." segments jaroslav@1258: * if there were insufficient non-".." segments preceding them to jaroslav@1258: * allow their removal. A normalized path will begin with a "." jaroslav@1258: * segment if one was inserted by step 3 above. Otherwise, a normalized jaroslav@1258: * path will not contain any "." or ".." segments.

jaroslav@1258: * jaroslav@1258: * @return A URI equivalent to this URI, jaroslav@1258: * but whose path is in normal form jaroslav@1258: */ jaroslav@1258: public URI normalize() { jaroslav@1258: return normalize(this); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Resolves the given URI against this URI. jaroslav@1258: * jaroslav@1258: *

If the given URI is already absolute, or if this URI is opaque, then jaroslav@1258: * the given URI is returned. jaroslav@1258: * jaroslav@1258: *

If the given URI's fragment component is jaroslav@1258: * defined, its path component is empty, and its scheme, authority, and jaroslav@1258: * query components are undefined, then a URI with the given fragment but jaroslav@1258: * with all other components equal to those of this URI is returned. This jaroslav@1258: * allows a URI representing a standalone fragment reference, such as jaroslav@1258: * "#foo", to be usefully resolved against a base URI. jaroslav@1258: * jaroslav@1258: *

Otherwise this method constructs a new hierarchical URI in a manner jaroslav@1258: * consistent with RFC 2396, jaroslav@1258: * section 5.2; that is:

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. A new URI is constructed with this URI's scheme and the given jaroslav@1258: * URI's query and fragment components.

  2. jaroslav@1258: * jaroslav@1258: *
  3. If the given URI has an authority component then the new URI's jaroslav@1258: * authority and path are taken from the given URI.

  4. jaroslav@1258: * jaroslav@1258: *
  5. Otherwise the new URI's authority component is copied from jaroslav@1258: * this URI, and its path is computed as follows:

    jaroslav@1258: * jaroslav@1258: *
      jaroslav@1258: * jaroslav@1258: *
    1. If the given URI's path is absolute then the new URI's path jaroslav@1258: * is taken from the given URI.

    2. jaroslav@1258: * jaroslav@1258: *
    3. Otherwise the given URI's path is relative, and so the new jaroslav@1258: * URI's path is computed by resolving the path of the given URI jaroslav@1258: * against the path of this URI. This is done by concatenating all but jaroslav@1258: * the last segment of this URI's path, if any, with the given URI's jaroslav@1258: * path and then normalizing the result as if by invoking the {@link jaroslav@1258: * #normalize() normalize} method.

    4. jaroslav@1258: * jaroslav@1258: *
  6. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: *

The result of this method is absolute if, and only if, either this jaroslav@1258: * URI is absolute or the given URI is absolute.

jaroslav@1258: * jaroslav@1258: * @param uri The URI to be resolved against this URI jaroslav@1258: * @return The resulting URI jaroslav@1258: * jaroslav@1258: * @throws NullPointerException jaroslav@1258: * If uri is null jaroslav@1258: */ jaroslav@1258: public URI resolve(URI uri) { jaroslav@1258: return resolve(this, uri); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a new URI by parsing the given string and then resolving it jaroslav@1258: * against this URI. jaroslav@1258: * jaroslav@1258: *

This convenience method works as if invoking it were equivalent to jaroslav@1258: * evaluating the expression {@link #resolve(java.net.URI) jaroslav@1258: * resolve}(URI.{@link #create(String) create}(str)).

jaroslav@1258: * jaroslav@1258: * @param str The string to be parsed into a URI jaroslav@1258: * @return The resulting URI jaroslav@1258: * jaroslav@1258: * @throws NullPointerException jaroslav@1258: * If str is null jaroslav@1258: * jaroslav@1258: * @throws IllegalArgumentException jaroslav@1258: * If the given string violates RFC 2396 jaroslav@1258: */ jaroslav@1258: public URI resolve(String str) { jaroslav@1258: return resolve(URI.create(str)); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Relativizes the given URI against this URI. jaroslav@1258: * jaroslav@1258: *

The relativization of the given URI against this URI is computed as jaroslav@1258: * follows:

jaroslav@1258: * jaroslav@1258: *
    jaroslav@1258: * jaroslav@1258: *
  1. If either this URI or the given URI are opaque, or if the jaroslav@1258: * scheme and authority components of the two URIs are not identical, or jaroslav@1258: * if the path of this URI is not a prefix of the path of the given URI, jaroslav@1258: * then the given URI is returned.

  2. jaroslav@1258: * jaroslav@1258: *
  3. Otherwise a new relative hierarchical URI is constructed with jaroslav@1258: * query and fragment components taken from the given URI and with a path jaroslav@1258: * component computed by removing this URI's path from the beginning of jaroslav@1258: * the given URI's path.

  4. jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * jaroslav@1258: * @param uri The URI to be relativized against this URI jaroslav@1258: * @return The resulting URI jaroslav@1258: * jaroslav@1258: * @throws NullPointerException jaroslav@1258: * If uri is null jaroslav@1258: */ jaroslav@1258: public URI relativize(URI uri) { jaroslav@1258: return relativize(this, uri); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Constructs a URL from this URI. jaroslav@1258: * jaroslav@1258: *

This convenience method works as if invoking it were equivalent to jaroslav@1258: * evaluating the expression new URL(this.toString()) after jaroslav@1258: * first checking that this URI is absolute.

jaroslav@1258: * jaroslav@1258: * @return A URL constructed from this URI jaroslav@1258: * jaroslav@1258: * @throws IllegalArgumentException jaroslav@1258: * If this URL is not absolute jaroslav@1258: * jaroslav@1258: * @throws MalformedURLException jaroslav@1258: * If a protocol handler for the URL could not be found, jaroslav@1258: * or if some other error occurred while constructing the URL jaroslav@1258: */ jaroslav@1258: public URL toURL() jaroslav@1258: throws MalformedURLException { jaroslav@1258: if (!isAbsolute()) jaroslav@1258: throw new IllegalArgumentException("URI is not absolute"); jaroslav@1258: return new URL(toString()); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // -- Component access methods -- jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the scheme component of this URI. jaroslav@1258: * jaroslav@1258: *

The scheme component of a URI, if defined, only contains characters jaroslav@1258: * in the alphanum category and in the string "-.+". A jaroslav@1258: * scheme always starts with an alpha character.

jaroslav@1258: * jaroslav@1258: * The scheme component of a URI cannot contain escaped octets, hence this jaroslav@1258: * method does not perform any decoding. jaroslav@1258: * jaroslav@1258: * @return The scheme component of this URI, jaroslav@1258: * or null if the scheme is undefined jaroslav@1258: */ jaroslav@1258: public String getScheme() { jaroslav@1258: return scheme; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Tells whether or not this URI is absolute. jaroslav@1258: * jaroslav@1258: *

A URI is absolute if, and only if, it has a scheme component.

jaroslav@1258: * jaroslav@1258: * @return true if, and only if, this URI is absolute jaroslav@1258: */ jaroslav@1258: public boolean isAbsolute() { jaroslav@1258: return scheme != null; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Tells whether or not this URI is opaque. jaroslav@1258: * jaroslav@1258: *

A URI is opaque if, and only if, it is absolute and its jaroslav@1258: * scheme-specific part does not begin with a slash character ('/'). jaroslav@1258: * An opaque URI has a scheme, a scheme-specific part, and possibly jaroslav@1258: * a fragment; all other components are undefined.

jaroslav@1258: * jaroslav@1258: * @return true if, and only if, this URI is opaque jaroslav@1258: */ jaroslav@1258: public boolean isOpaque() { jaroslav@1258: return path == null; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw scheme-specific part of this URI. The scheme-specific jaroslav@1258: * part is never undefined, though it may be empty. jaroslav@1258: * jaroslav@1258: *

The scheme-specific part of a URI only contains legal URI jaroslav@1258: * characters.

jaroslav@1258: * jaroslav@1258: * @return The raw scheme-specific part of this URI jaroslav@1258: * (never null) jaroslav@1258: */ jaroslav@1258: public String getRawSchemeSpecificPart() { jaroslav@1258: defineSchemeSpecificPart(); jaroslav@1258: return schemeSpecificPart; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded scheme-specific part of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawSchemeSpecificPart() getRawSchemeSpecificPart} method jaroslav@1258: * except that all sequences of escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded scheme-specific part of this URI jaroslav@1258: * (never null) jaroslav@1258: */ jaroslav@1258: public String getSchemeSpecificPart() { jaroslav@1258: if (decodedSchemeSpecificPart == null) jaroslav@1258: decodedSchemeSpecificPart = decode(getRawSchemeSpecificPart()); jaroslav@1258: return decodedSchemeSpecificPart; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw authority component of this URI. jaroslav@1258: * jaroslav@1258: *

The authority component of a URI, if defined, only contains the jaroslav@1258: * commercial-at character ('@') and characters in the jaroslav@1258: * unreserved, punct, escaped, and other jaroslav@1258: * categories. If the authority is server-based then it is further jaroslav@1258: * constrained to have valid user-information, host, and port jaroslav@1258: * components.

jaroslav@1258: * jaroslav@1258: * @return The raw authority component of this URI, jaroslav@1258: * or null if the authority is undefined jaroslav@1258: */ jaroslav@1258: public String getRawAuthority() { jaroslav@1258: return authority; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded authority component of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawAuthority() getRawAuthority} method except that all jaroslav@1258: * sequences of escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded authority component of this URI, jaroslav@1258: * or null if the authority is undefined jaroslav@1258: */ jaroslav@1258: public String getAuthority() { jaroslav@1258: if (decodedAuthority == null) jaroslav@1258: decodedAuthority = decode(authority); jaroslav@1258: return decodedAuthority; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw user-information component of this URI. jaroslav@1258: * jaroslav@1258: *

The user-information component of a URI, if defined, only contains jaroslav@1258: * characters in the unreserved, punct, escaped, and jaroslav@1258: * other categories.

jaroslav@1258: * jaroslav@1258: * @return The raw user-information component of this URI, jaroslav@1258: * or null if the user information is undefined jaroslav@1258: */ jaroslav@1258: public String getRawUserInfo() { jaroslav@1258: return userInfo; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded user-information component of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawUserInfo() getRawUserInfo} method except that all jaroslav@1258: * sequences of escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded user-information component of this URI, jaroslav@1258: * or null if the user information is undefined jaroslav@1258: */ jaroslav@1258: public String getUserInfo() { jaroslav@1258: if ((decodedUserInfo == null) && (userInfo != null)) jaroslav@1258: decodedUserInfo = decode(userInfo); jaroslav@1258: return decodedUserInfo; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the host component of this URI. jaroslav@1258: * jaroslav@1258: *

The host component of a URI, if defined, will have one of the jaroslav@1258: * following forms:

jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * The host component of a URI cannot contain escaped octets, hence this jaroslav@1258: * method does not perform any decoding. jaroslav@1258: * jaroslav@1258: * @return The host component of this URI, jaroslav@1258: * or null if the host is undefined jaroslav@1258: */ jaroslav@1258: public String getHost() { jaroslav@1258: return host; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the port number of this URI. jaroslav@1258: * jaroslav@1258: *

The port component of a URI, if defined, is a non-negative jaroslav@1258: * integer.

jaroslav@1258: * jaroslav@1258: * @return The port component of this URI, jaroslav@1258: * or -1 if the port is undefined jaroslav@1258: */ jaroslav@1258: public int getPort() { jaroslav@1258: return port; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw path component of this URI. jaroslav@1258: * jaroslav@1258: *

The path component of a URI, if defined, only contains the slash jaroslav@1258: * character ('/'), the commercial-at character ('@'), jaroslav@1258: * and characters in the unreserved, punct, escaped, jaroslav@1258: * and other categories.

jaroslav@1258: * jaroslav@1258: * @return The path component of this URI, jaroslav@1258: * or null if the path is undefined jaroslav@1258: */ jaroslav@1258: public String getRawPath() { jaroslav@1258: return path; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded path component of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawPath() getRawPath} method except that all sequences of jaroslav@1258: * escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded path component of this URI, jaroslav@1258: * or null if the path is undefined jaroslav@1258: */ jaroslav@1258: public String getPath() { jaroslav@1258: if ((decodedPath == null) && (path != null)) jaroslav@1258: decodedPath = decode(path); jaroslav@1258: return decodedPath; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw query component of this URI. jaroslav@1258: * jaroslav@1258: *

The query component of a URI, if defined, only contains legal URI jaroslav@1258: * characters.

jaroslav@1258: * jaroslav@1258: * @return The raw query component of this URI, jaroslav@1258: * or null if the query is undefined jaroslav@1258: */ jaroslav@1258: public String getRawQuery() { jaroslav@1258: return query; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded query component of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawQuery() getRawQuery} method except that all sequences of jaroslav@1258: * escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded query component of this URI, jaroslav@1258: * or null if the query is undefined jaroslav@1258: */ jaroslav@1258: public String getQuery() { jaroslav@1258: if ((decodedQuery == null) && (query != null)) jaroslav@1258: decodedQuery = decode(query); jaroslav@1258: return decodedQuery; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the raw fragment component of this URI. jaroslav@1258: * jaroslav@1258: *

The fragment component of a URI, if defined, only contains legal URI jaroslav@1258: * characters.

jaroslav@1258: * jaroslav@1258: * @return The raw fragment component of this URI, jaroslav@1258: * or null if the fragment is undefined jaroslav@1258: */ jaroslav@1258: public String getRawFragment() { jaroslav@1258: return fragment; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the decoded fragment component of this URI. jaroslav@1258: * jaroslav@1258: *

The string returned by this method is equal to that returned by the jaroslav@1258: * {@link #getRawFragment() getRawFragment} method except that all jaroslav@1258: * sequences of escaped octets are decoded.

jaroslav@1258: * jaroslav@1258: * @return The decoded fragment component of this URI, jaroslav@1258: * or null if the fragment is undefined jaroslav@1258: */ jaroslav@1258: public String getFragment() { jaroslav@1258: if ((decodedFragment == null) && (fragment != null)) jaroslav@1258: decodedFragment = decode(fragment); jaroslav@1258: return decodedFragment; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Equality, comparison, hash code, toString, and serialization -- jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Tests this URI for equality with another object. jaroslav@1258: * jaroslav@1258: *

If the given object is not a URI then this method immediately jaroslav@1258: * returns false. jaroslav@1258: * jaroslav@1258: *

For two URIs to be considered equal requires that either both are jaroslav@1258: * opaque or both are hierarchical. Their schemes must either both be jaroslav@1258: * undefined or else be equal without regard to case. Their fragments jaroslav@1258: * must either both be undefined or else be equal. jaroslav@1258: * jaroslav@1258: *

For two opaque URIs to be considered equal, their scheme-specific jaroslav@1258: * parts must be equal. jaroslav@1258: * jaroslav@1258: *

For two hierarchical URIs to be considered equal, their paths must jaroslav@1258: * be equal and their queries must either both be undefined or else be jaroslav@1258: * equal. Their authorities must either both be undefined, or both be jaroslav@1258: * registry-based, or both be server-based. If their authorities are jaroslav@1258: * defined and are registry-based, then they must be equal. If their jaroslav@1258: * authorities are defined and are server-based, then their hosts must be jaroslav@1258: * equal without regard to case, their port numbers must be equal, and jaroslav@1258: * their user-information components must be equal. jaroslav@1258: * jaroslav@1258: *

When testing the user-information, path, query, fragment, authority, jaroslav@1258: * or scheme-specific parts of two URIs for equality, the raw forms rather jaroslav@1258: * than the encoded forms of these components are compared and the jaroslav@1258: * hexadecimal digits of escaped octets are compared without regard to jaroslav@1258: * case. jaroslav@1258: * jaroslav@1258: *

This method satisfies the general contract of the {@link jaroslav@1258: * java.lang.Object#equals(Object) Object.equals} method.

jaroslav@1258: * jaroslav@1258: * @param ob The object to which this object is to be compared jaroslav@1258: * jaroslav@1258: * @return true if, and only if, the given object is a URI that jaroslav@1258: * is identical to this URI jaroslav@1258: */ jaroslav@1258: public boolean equals(Object ob) { jaroslav@1258: if (ob == this) jaroslav@1258: return true; jaroslav@1258: if (!(ob instanceof URI)) jaroslav@1258: return false; jaroslav@1258: URI that = (URI)ob; jaroslav@1258: if (this.isOpaque() != that.isOpaque()) return false; jaroslav@1258: if (!equalIgnoringCase(this.scheme, that.scheme)) return false; jaroslav@1258: if (!equal(this.fragment, that.fragment)) return false; jaroslav@1258: jaroslav@1258: // Opaque jaroslav@1258: if (this.isOpaque()) jaroslav@1258: return equal(this.schemeSpecificPart, that.schemeSpecificPart); jaroslav@1258: jaroslav@1258: // Hierarchical jaroslav@1258: if (!equal(this.path, that.path)) return false; jaroslav@1258: if (!equal(this.query, that.query)) return false; jaroslav@1258: jaroslav@1258: // Authorities jaroslav@1258: if (this.authority == that.authority) return true; jaroslav@1258: if (this.host != null) { jaroslav@1258: // Server-based jaroslav@1258: if (!equal(this.userInfo, that.userInfo)) return false; jaroslav@1258: if (!equalIgnoringCase(this.host, that.host)) return false; jaroslav@1258: if (this.port != that.port) return false; jaroslav@1258: } else if (this.authority != null) { jaroslav@1258: // Registry-based jaroslav@1258: if (!equal(this.authority, that.authority)) return false; jaroslav@1258: } else if (this.authority != that.authority) { jaroslav@1258: return false; jaroslav@1258: } jaroslav@1258: jaroslav@1258: return true; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns a hash-code value for this URI. The hash code is based upon all jaroslav@1258: * of the URI's components, and satisfies the general contract of the jaroslav@1258: * {@link java.lang.Object#hashCode() Object.hashCode} method. jaroslav@1258: * jaroslav@1258: * @return A hash-code value for this URI jaroslav@1258: */ jaroslav@1258: public int hashCode() { jaroslav@1258: if (hash != 0) jaroslav@1258: return hash; jaroslav@1258: int h = hashIgnoringCase(0, scheme); jaroslav@1258: h = hash(h, fragment); jaroslav@1258: if (isOpaque()) { jaroslav@1258: h = hash(h, schemeSpecificPart); jaroslav@1258: } else { jaroslav@1258: h = hash(h, path); jaroslav@1258: h = hash(h, query); jaroslav@1258: if (host != null) { jaroslav@1258: h = hash(h, userInfo); jaroslav@1258: h = hashIgnoringCase(h, host); jaroslav@1258: h += 1949 * port; jaroslav@1258: } else { jaroslav@1258: h = hash(h, authority); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: hash = h; jaroslav@1258: return h; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Compares this URI to another object, which must be a URI. jaroslav@1258: * jaroslav@1258: *

When comparing corresponding components of two URIs, if one jaroslav@1258: * component is undefined but the other is defined then the first is jaroslav@1258: * considered to be less than the second. Unless otherwise noted, string jaroslav@1258: * components are ordered according to their natural, case-sensitive jaroslav@1258: * ordering as defined by the {@link java.lang.String#compareTo(Object) jaroslav@1258: * String.compareTo} method. String components that are subject to jaroslav@1258: * encoding are compared by comparing their raw forms rather than their jaroslav@1258: * encoded forms. jaroslav@1258: * jaroslav@1258: *

The ordering of URIs is defined as follows:

jaroslav@1258: * jaroslav@1258: * jaroslav@1258: * jaroslav@1258: *

This method satisfies the general contract of the {@link jaroslav@1258: * java.lang.Comparable#compareTo(Object) Comparable.compareTo} jaroslav@1258: * method.

jaroslav@1258: * jaroslav@1258: * @param that jaroslav@1258: * The object to which this URI is to be compared jaroslav@1258: * jaroslav@1258: * @return A negative integer, zero, or a positive integer as this URI is jaroslav@1258: * less than, equal to, or greater than the given URI jaroslav@1258: * jaroslav@1258: * @throws ClassCastException jaroslav@1258: * If the given object is not a URI jaroslav@1258: */ jaroslav@1258: public int compareTo(URI that) { jaroslav@1258: int c; jaroslav@1258: jaroslav@1258: if ((c = compareIgnoringCase(this.scheme, that.scheme)) != 0) jaroslav@1258: return c; jaroslav@1258: jaroslav@1258: if (this.isOpaque()) { jaroslav@1258: if (that.isOpaque()) { jaroslav@1258: // Both opaque jaroslav@1258: if ((c = compare(this.schemeSpecificPart, jaroslav@1258: that.schemeSpecificPart)) != 0) jaroslav@1258: return c; jaroslav@1258: return compare(this.fragment, that.fragment); jaroslav@1258: } jaroslav@1258: return +1; // Opaque > hierarchical jaroslav@1258: } else if (that.isOpaque()) { jaroslav@1258: return -1; // Hierarchical < opaque jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Hierarchical jaroslav@1258: if ((this.host != null) && (that.host != null)) { jaroslav@1258: // Both server-based jaroslav@1258: if ((c = compare(this.userInfo, that.userInfo)) != 0) jaroslav@1258: return c; jaroslav@1258: if ((c = compareIgnoringCase(this.host, that.host)) != 0) jaroslav@1258: return c; jaroslav@1258: if ((c = this.port - that.port) != 0) jaroslav@1258: return c; jaroslav@1258: } else { jaroslav@1258: // If one or both authorities are registry-based then we simply jaroslav@1258: // compare them in the usual, case-sensitive way. If one is jaroslav@1258: // registry-based and one is server-based then the strings are jaroslav@1258: // guaranteed to be unequal, hence the comparison will never return jaroslav@1258: // zero and the compareTo and equals methods will remain jaroslav@1258: // consistent. jaroslav@1258: if ((c = compare(this.authority, that.authority)) != 0) return c; jaroslav@1258: } jaroslav@1258: jaroslav@1258: if ((c = compare(this.path, that.path)) != 0) return c; jaroslav@1258: if ((c = compare(this.query, that.query)) != 0) return c; jaroslav@1258: return compare(this.fragment, that.fragment); jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the content of this URI as a string. jaroslav@1258: * jaroslav@1258: *

If this URI was created by invoking one of the constructors in this jaroslav@1258: * class then a string equivalent to the original input string, or to the jaroslav@1258: * string computed from the originally-given components, as appropriate, is jaroslav@1258: * returned. Otherwise this URI was created by normalization, resolution, jaroslav@1258: * or relativization, and so a string is constructed from this URI's jaroslav@1258: * components according to the rules specified in RFC 2396, jaroslav@1258: * section 5.2, step 7.

jaroslav@1258: * jaroslav@1258: * @return The string form of this URI jaroslav@1258: */ jaroslav@1258: public String toString() { jaroslav@1258: defineString(); jaroslav@1258: return string; jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Returns the content of this URI as a US-ASCII string. jaroslav@1258: * jaroslav@1258: *

If this URI does not contain any characters in the other jaroslav@1258: * category then an invocation of this method will return the same value as jaroslav@1258: * an invocation of the {@link #toString() toString} method. Otherwise jaroslav@1258: * this method works as if by invoking that method and then encoding the result.

jaroslav@1258: * jaroslav@1258: * @return The string form of this URI, encoded as needed jaroslav@1258: * so that it only contains characters in the US-ASCII jaroslav@1258: * charset jaroslav@1258: */ jaroslav@1258: public String toASCIIString() { jaroslav@1258: defineString(); jaroslav@1258: return encode(string); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Serialization support -- jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Saves the content of this URI to the given serial stream. jaroslav@1258: * jaroslav@1258: *

The only serializable field of a URI instance is its string jaroslav@1258: * field. That field is given a value, if it does not have one already, jaroslav@1258: * and then the {@link java.io.ObjectOutputStream#defaultWriteObject()} jaroslav@1258: * method of the given object-output stream is invoked.

jaroslav@1258: * jaroslav@1258: * @param os The object-output stream to which this object jaroslav@1258: * is to be written jaroslav@1258: */ jaroslav@1258: private void writeObject(ObjectOutputStream os) jaroslav@1258: throws IOException jaroslav@1258: { jaroslav@1258: defineString(); jaroslav@1258: os.defaultWriteObject(); // Writes the string field only jaroslav@1258: } jaroslav@1258: jaroslav@1258: /** jaroslav@1258: * Reconstitutes a URI from the given serial stream. jaroslav@1258: * jaroslav@1258: *

The {@link java.io.ObjectInputStream#defaultReadObject()} method is jaroslav@1258: * invoked to read the value of the string field. The result is jaroslav@1258: * then parsed in the usual way. jaroslav@1258: * jaroslav@1258: * @param is The object-input stream from which this object jaroslav@1258: * is being read jaroslav@1258: */ jaroslav@1258: private void readObject(ObjectInputStream is) jaroslav@1258: throws ClassNotFoundException, IOException jaroslav@1258: { jaroslav@1258: port = -1; // Argh jaroslav@1258: is.defaultReadObject(); jaroslav@1258: try { jaroslav@1258: new Parser(string).parse(false); jaroslav@1258: } catch (URISyntaxException x) { jaroslav@1258: IOException y = new InvalidObjectException("Invalid URI"); jaroslav@1258: y.initCause(x); jaroslav@1258: throw y; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- End of public methods -- jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Utility methods for string-field comparison and hashing -- jaroslav@1258: jaroslav@1258: // These methods return appropriate values for null string arguments, jaroslav@1258: // thereby simplifying the equals, hashCode, and compareTo methods. jaroslav@1258: // jaroslav@1258: // The case-ignoring methods should only be applied to strings whose jaroslav@1258: // characters are all known to be US-ASCII. Because of this restriction, jaroslav@1258: // these methods are faster than the similar methods in the String class. jaroslav@1258: jaroslav@1258: // US-ASCII only jaroslav@1258: private static int toLower(char c) { jaroslav@1258: if ((c >= 'A') && (c <= 'Z')) jaroslav@1258: return c + ('a' - 'A'); jaroslav@1258: return c; jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static boolean equal(String s, String t) { jaroslav@1258: if (s == t) return true; jaroslav@1258: if ((s != null) && (t != null)) { jaroslav@1258: if (s.length() != t.length()) jaroslav@1258: return false; jaroslav@1258: if (s.indexOf('%') < 0) jaroslav@1258: return s.equals(t); jaroslav@1258: int n = s.length(); jaroslav@1258: for (int i = 0; i < n;) { jaroslav@1258: char c = s.charAt(i); jaroslav@1258: char d = t.charAt(i); jaroslav@1258: if (c != '%') { jaroslav@1258: if (c != d) jaroslav@1258: return false; jaroslav@1258: i++; jaroslav@1258: continue; jaroslav@1258: } jaroslav@1258: i++; jaroslav@1258: if (toLower(s.charAt(i)) != toLower(t.charAt(i))) jaroslav@1258: return false; jaroslav@1258: i++; jaroslav@1258: if (toLower(s.charAt(i)) != toLower(t.charAt(i))) jaroslav@1258: return false; jaroslav@1258: i++; jaroslav@1258: } jaroslav@1258: return true; jaroslav@1258: } jaroslav@1258: return false; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // US-ASCII only jaroslav@1258: private static boolean equalIgnoringCase(String s, String t) { jaroslav@1258: if (s == t) return true; jaroslav@1258: if ((s != null) && (t != null)) { jaroslav@1258: int n = s.length(); jaroslav@1258: if (t.length() != n) jaroslav@1258: return false; jaroslav@1258: for (int i = 0; i < n; i++) { jaroslav@1258: if (toLower(s.charAt(i)) != toLower(t.charAt(i))) jaroslav@1258: return false; jaroslav@1258: } jaroslav@1258: return true; jaroslav@1258: } jaroslav@1258: return false; jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static int hash(int hash, String s) { jaroslav@1258: if (s == null) return hash; jaroslav@1258: return hash * 127 + s.hashCode(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // US-ASCII only jaroslav@1258: private static int hashIgnoringCase(int hash, String s) { jaroslav@1258: if (s == null) return hash; jaroslav@1258: int h = hash; jaroslav@1258: int n = s.length(); jaroslav@1258: for (int i = 0; i < n; i++) jaroslav@1258: h = 31 * h + toLower(s.charAt(i)); jaroslav@1258: return h; jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static int compare(String s, String t) { jaroslav@1258: if (s == t) return 0; jaroslav@1258: if (s != null) { jaroslav@1258: if (t != null) jaroslav@1258: return s.compareTo(t); jaroslav@1258: else jaroslav@1258: return +1; jaroslav@1258: } else { jaroslav@1258: return -1; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: // US-ASCII only jaroslav@1258: private static int compareIgnoringCase(String s, String t) { jaroslav@1258: if (s == t) return 0; jaroslav@1258: if (s != null) { jaroslav@1258: if (t != null) { jaroslav@1258: int sn = s.length(); jaroslav@1258: int tn = t.length(); jaroslav@1258: int n = sn < tn ? sn : tn; jaroslav@1258: for (int i = 0; i < n; i++) { jaroslav@1258: int c = toLower(s.charAt(i)) - toLower(t.charAt(i)); jaroslav@1258: if (c != 0) jaroslav@1258: return c; jaroslav@1258: } jaroslav@1258: return sn - tn; jaroslav@1258: } jaroslav@1258: return +1; jaroslav@1258: } else { jaroslav@1258: return -1; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- String construction -- jaroslav@1258: jaroslav@1258: // If a scheme is given then the path, if given, must be absolute jaroslav@1258: // jaroslav@1258: private static void checkPath(String s, String scheme, String path) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: if (scheme != null) { jaroslav@1258: if ((path != null) jaroslav@1258: && ((path.length() > 0) && (path.charAt(0) != '/'))) jaroslav@1258: throw new URISyntaxException(s, jaroslav@1258: "Relative path in absolute URI"); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void appendAuthority(StringBuffer sb, jaroslav@1258: String authority, jaroslav@1258: String userInfo, jaroslav@1258: String host, jaroslav@1258: int port) jaroslav@1258: { jaroslav@1258: if (host != null) { jaroslav@1258: sb.append("//"); jaroslav@1258: if (userInfo != null) { jaroslav@1258: sb.append(quote(userInfo, L_USERINFO, H_USERINFO)); jaroslav@1258: sb.append('@'); jaroslav@1258: } jaroslav@1258: boolean needBrackets = ((host.indexOf(':') >= 0) jaroslav@1258: && !host.startsWith("[") jaroslav@1258: && !host.endsWith("]")); jaroslav@1258: if (needBrackets) sb.append('['); jaroslav@1258: sb.append(host); jaroslav@1258: if (needBrackets) sb.append(']'); jaroslav@1258: if (port != -1) { jaroslav@1258: sb.append(':'); jaroslav@1258: sb.append(port); jaroslav@1258: } jaroslav@1258: } else if (authority != null) { jaroslav@1258: sb.append("//"); jaroslav@1258: if (authority.startsWith("[")) { jaroslav@1258: // authority should (but may not) contain an embedded IPv6 address jaroslav@1258: int end = authority.indexOf("]"); jaroslav@1258: String doquote = authority, dontquote = ""; jaroslav@1258: if (end != -1 && authority.indexOf(":") != -1) { jaroslav@1258: // the authority contains an IPv6 address jaroslav@1258: if (end == authority.length()) { jaroslav@1258: dontquote = authority; jaroslav@1258: doquote = ""; jaroslav@1258: } else { jaroslav@1258: dontquote = authority.substring(0 , end + 1); jaroslav@1258: doquote = authority.substring(end + 1); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: sb.append(dontquote); jaroslav@1258: sb.append(quote(doquote, jaroslav@1258: L_REG_NAME | L_SERVER, jaroslav@1258: H_REG_NAME | H_SERVER)); jaroslav@1258: } else { jaroslav@1258: sb.append(quote(authority, jaroslav@1258: L_REG_NAME | L_SERVER, jaroslav@1258: H_REG_NAME | H_SERVER)); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void appendSchemeSpecificPart(StringBuffer sb, jaroslav@1258: String opaquePart, jaroslav@1258: String authority, jaroslav@1258: String userInfo, jaroslav@1258: String host, jaroslav@1258: int port, jaroslav@1258: String path, jaroslav@1258: String query) jaroslav@1258: { jaroslav@1258: if (opaquePart != null) { jaroslav@1258: /* check if SSP begins with an IPv6 address jaroslav@1258: * because we must not quote a literal IPv6 address jaroslav@1258: */ jaroslav@1258: if (opaquePart.startsWith("//[")) { jaroslav@1258: int end = opaquePart.indexOf("]"); jaroslav@1258: if (end != -1 && opaquePart.indexOf(":")!=-1) { jaroslav@1258: String doquote, dontquote; jaroslav@1258: if (end == opaquePart.length()) { jaroslav@1258: dontquote = opaquePart; jaroslav@1258: doquote = ""; jaroslav@1258: } else { jaroslav@1258: dontquote = opaquePart.substring(0,end+1); jaroslav@1258: doquote = opaquePart.substring(end+1); jaroslav@1258: } jaroslav@1258: sb.append (dontquote); jaroslav@1258: sb.append(quote(doquote, L_URIC, H_URIC)); jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: sb.append(quote(opaquePart, L_URIC, H_URIC)); jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: appendAuthority(sb, authority, userInfo, host, port); jaroslav@1258: if (path != null) jaroslav@1258: sb.append(quote(path, L_PATH, H_PATH)); jaroslav@1258: if (query != null) { jaroslav@1258: sb.append('?'); jaroslav@1258: sb.append(quote(query, L_URIC, H_URIC)); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void appendFragment(StringBuffer sb, String fragment) { jaroslav@1258: if (fragment != null) { jaroslav@1258: sb.append('#'); jaroslav@1258: sb.append(quote(fragment, L_URIC, H_URIC)); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: private String toString(String scheme, jaroslav@1258: String opaquePart, jaroslav@1258: String authority, jaroslav@1258: String userInfo, jaroslav@1258: String host, jaroslav@1258: int port, jaroslav@1258: String path, jaroslav@1258: String query, jaroslav@1258: String fragment) jaroslav@1258: { jaroslav@1258: StringBuffer sb = new StringBuffer(); jaroslav@1258: if (scheme != null) { jaroslav@1258: sb.append(scheme); jaroslav@1258: sb.append(':'); jaroslav@1258: } jaroslav@1258: appendSchemeSpecificPart(sb, opaquePart, jaroslav@1258: authority, userInfo, host, port, jaroslav@1258: path, query); jaroslav@1258: appendFragment(sb, fragment); jaroslav@1258: return sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void defineSchemeSpecificPart() { jaroslav@1258: if (schemeSpecificPart != null) return; jaroslav@1258: StringBuffer sb = new StringBuffer(); jaroslav@1258: appendSchemeSpecificPart(sb, null, getAuthority(), getUserInfo(), jaroslav@1258: host, port, getPath(), getQuery()); jaroslav@1258: if (sb.length() == 0) return; jaroslav@1258: schemeSpecificPart = sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void defineString() { jaroslav@1258: if (string != null) return; jaroslav@1258: jaroslav@1258: StringBuffer sb = new StringBuffer(); jaroslav@1258: if (scheme != null) { jaroslav@1258: sb.append(scheme); jaroslav@1258: sb.append(':'); jaroslav@1258: } jaroslav@1258: if (isOpaque()) { jaroslav@1258: sb.append(schemeSpecificPart); jaroslav@1258: } else { jaroslav@1258: if (host != null) { jaroslav@1258: sb.append("//"); jaroslav@1258: if (userInfo != null) { jaroslav@1258: sb.append(userInfo); jaroslav@1258: sb.append('@'); jaroslav@1258: } jaroslav@1258: boolean needBrackets = ((host.indexOf(':') >= 0) jaroslav@1258: && !host.startsWith("[") jaroslav@1258: && !host.endsWith("]")); jaroslav@1258: if (needBrackets) sb.append('['); jaroslav@1258: sb.append(host); jaroslav@1258: if (needBrackets) sb.append(']'); jaroslav@1258: if (port != -1) { jaroslav@1258: sb.append(':'); jaroslav@1258: sb.append(port); jaroslav@1258: } jaroslav@1258: } else if (authority != null) { jaroslav@1258: sb.append("//"); jaroslav@1258: sb.append(authority); jaroslav@1258: } jaroslav@1258: if (path != null) jaroslav@1258: sb.append(path); jaroslav@1258: if (query != null) { jaroslav@1258: sb.append('?'); jaroslav@1258: sb.append(query); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: if (fragment != null) { jaroslav@1258: sb.append('#'); jaroslav@1258: sb.append(fragment); jaroslav@1258: } jaroslav@1258: string = sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Normalization, resolution, and relativization -- jaroslav@1258: jaroslav@1258: // RFC2396 5.2 (6) jaroslav@1258: private static String resolvePath(String base, String child, jaroslav@1258: boolean absolute) jaroslav@1258: { jaroslav@1258: int i = base.lastIndexOf('/'); jaroslav@1258: int cn = child.length(); jaroslav@1258: String path = ""; jaroslav@1258: jaroslav@1258: if (cn == 0) { jaroslav@1258: // 5.2 (6a) jaroslav@1258: if (i >= 0) jaroslav@1258: path = base.substring(0, i + 1); jaroslav@1258: } else { jaroslav@1258: StringBuffer sb = new StringBuffer(base.length() + cn); jaroslav@1258: // 5.2 (6a) jaroslav@1258: if (i >= 0) jaroslav@1258: sb.append(base.substring(0, i + 1)); jaroslav@1258: // 5.2 (6b) jaroslav@1258: sb.append(child); jaroslav@1258: path = sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // 5.2 (6c-f) jaroslav@1258: String np = normalize(path); jaroslav@1258: jaroslav@1258: // 5.2 (6g): If the result is absolute but the path begins with "../", jaroslav@1258: // then we simply leave the path as-is jaroslav@1258: jaroslav@1258: return np; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // RFC2396 5.2 jaroslav@1258: private static URI resolve(URI base, URI child) { jaroslav@1258: // check if child if opaque first so that NPE is thrown jaroslav@1258: // if child is null. jaroslav@1258: if (child.isOpaque() || base.isOpaque()) jaroslav@1258: return child; jaroslav@1258: jaroslav@1258: // 5.2 (2): Reference to current document (lone fragment) jaroslav@1258: if ((child.scheme == null) && (child.authority == null) jaroslav@1258: && child.path.equals("") && (child.fragment != null) jaroslav@1258: && (child.query == null)) { jaroslav@1258: if ((base.fragment != null) jaroslav@1258: && child.fragment.equals(base.fragment)) { jaroslav@1258: return base; jaroslav@1258: } jaroslav@1258: URI ru = new URI(); jaroslav@1258: ru.scheme = base.scheme; jaroslav@1258: ru.authority = base.authority; jaroslav@1258: ru.userInfo = base.userInfo; jaroslav@1258: ru.host = base.host; jaroslav@1258: ru.port = base.port; jaroslav@1258: ru.path = base.path; jaroslav@1258: ru.fragment = child.fragment; jaroslav@1258: ru.query = base.query; jaroslav@1258: return ru; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // 5.2 (3): Child is absolute jaroslav@1258: if (child.scheme != null) jaroslav@1258: return child; jaroslav@1258: jaroslav@1258: URI ru = new URI(); // Resolved URI jaroslav@1258: ru.scheme = base.scheme; jaroslav@1258: ru.query = child.query; jaroslav@1258: ru.fragment = child.fragment; jaroslav@1258: jaroslav@1258: // 5.2 (4): Authority jaroslav@1258: if (child.authority == null) { jaroslav@1258: ru.authority = base.authority; jaroslav@1258: ru.host = base.host; jaroslav@1258: ru.userInfo = base.userInfo; jaroslav@1258: ru.port = base.port; jaroslav@1258: jaroslav@1258: String cp = (child.path == null) ? "" : child.path; jaroslav@1258: if ((cp.length() > 0) && (cp.charAt(0) == '/')) { jaroslav@1258: // 5.2 (5): Child path is absolute jaroslav@1258: ru.path = child.path; jaroslav@1258: } else { jaroslav@1258: // 5.2 (6): Resolve relative path jaroslav@1258: ru.path = resolvePath(base.path, cp, base.isAbsolute()); jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: ru.authority = child.authority; jaroslav@1258: ru.host = child.host; jaroslav@1258: ru.userInfo = child.userInfo; jaroslav@1258: ru.host = child.host; jaroslav@1258: ru.port = child.port; jaroslav@1258: ru.path = child.path; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // 5.2 (7): Recombine (nothing to do here) jaroslav@1258: return ru; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // If the given URI's path is normal then return the URI; jaroslav@1258: // o.w., return a new URI containing the normalized path. jaroslav@1258: // jaroslav@1258: private static URI normalize(URI u) { jaroslav@1258: if (u.isOpaque() || (u.path == null) || (u.path.length() == 0)) jaroslav@1258: return u; jaroslav@1258: jaroslav@1258: String np = normalize(u.path); jaroslav@1258: if (np == u.path) jaroslav@1258: return u; jaroslav@1258: jaroslav@1258: URI v = new URI(); jaroslav@1258: v.scheme = u.scheme; jaroslav@1258: v.fragment = u.fragment; jaroslav@1258: v.authority = u.authority; jaroslav@1258: v.userInfo = u.userInfo; jaroslav@1258: v.host = u.host; jaroslav@1258: v.port = u.port; jaroslav@1258: v.path = np; jaroslav@1258: v.query = u.query; jaroslav@1258: return v; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // If both URIs are hierarchical, their scheme and authority components are jaroslav@1258: // identical, and the base path is a prefix of the child's path, then jaroslav@1258: // return a relative URI that, when resolved against the base, yields the jaroslav@1258: // child; otherwise, return the child. jaroslav@1258: // jaroslav@1258: private static URI relativize(URI base, URI child) { jaroslav@1258: // check if child if opaque first so that NPE is thrown jaroslav@1258: // if child is null. jaroslav@1258: if (child.isOpaque() || base.isOpaque()) jaroslav@1258: return child; jaroslav@1258: if (!equalIgnoringCase(base.scheme, child.scheme) jaroslav@1258: || !equal(base.authority, child.authority)) jaroslav@1258: return child; jaroslav@1258: jaroslav@1258: String bp = normalize(base.path); jaroslav@1258: String cp = normalize(child.path); jaroslav@1258: if (!bp.equals(cp)) { jaroslav@1258: if (!bp.endsWith("/")) jaroslav@1258: bp = bp + "/"; jaroslav@1258: if (!cp.startsWith(bp)) jaroslav@1258: return child; jaroslav@1258: } jaroslav@1258: jaroslav@1258: URI v = new URI(); jaroslav@1258: v.path = cp.substring(bp.length()); jaroslav@1258: v.query = child.query; jaroslav@1258: v.fragment = child.fragment; jaroslav@1258: return v; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Path normalization -- jaroslav@1258: jaroslav@1258: // The following algorithm for path normalization avoids the creation of a jaroslav@1258: // string object for each segment, as well as the use of a string buffer to jaroslav@1258: // compute the final result, by using a single char array and editing it in jaroslav@1258: // place. The array is first split into segments, replacing each slash jaroslav@1258: // with '\0' and creating a segment-index array, each element of which is jaroslav@1258: // the index of the first char in the corresponding segment. We then walk jaroslav@1258: // through both arrays, removing ".", "..", and other segments as necessary jaroslav@1258: // by setting their entries in the index array to -1. Finally, the two jaroslav@1258: // arrays are used to rejoin the segments and compute the final result. jaroslav@1258: // jaroslav@1258: // This code is based upon src/solaris/native/java/io/canonicalize_md.c jaroslav@1258: jaroslav@1258: jaroslav@1258: // Check the given path to see if it might need normalization. A path jaroslav@1258: // might need normalization if it contains duplicate slashes, a "." jaroslav@1258: // segment, or a ".." segment. Return -1 if no further normalization is jaroslav@1258: // possible, otherwise return the number of segments found. jaroslav@1258: // jaroslav@1258: // This method takes a string argument rather than a char array so that jaroslav@1258: // this test can be performed without invoking path.toCharArray(). jaroslav@1258: // jaroslav@1258: static private int needsNormalization(String path) { jaroslav@1258: boolean normal = true; jaroslav@1258: int ns = 0; // Number of segments jaroslav@1258: int end = path.length() - 1; // Index of last char in path jaroslav@1258: int p = 0; // Index of next char in path jaroslav@1258: jaroslav@1258: // Skip initial slashes jaroslav@1258: while (p <= end) { jaroslav@1258: if (path.charAt(p) != '/') break; jaroslav@1258: p++; jaroslav@1258: } jaroslav@1258: if (p > 1) normal = false; jaroslav@1258: jaroslav@1258: // Scan segments jaroslav@1258: while (p <= end) { jaroslav@1258: jaroslav@1258: // Looking at "." or ".." ? jaroslav@1258: if ((path.charAt(p) == '.') jaroslav@1258: && ((p == end) jaroslav@1258: || ((path.charAt(p + 1) == '/') jaroslav@1258: || ((path.charAt(p + 1) == '.') jaroslav@1258: && ((p + 1 == end) jaroslav@1258: || (path.charAt(p + 2) == '/')))))) { jaroslav@1258: normal = false; jaroslav@1258: } jaroslav@1258: ns++; jaroslav@1258: jaroslav@1258: // Find beginning of next segment jaroslav@1258: while (p <= end) { jaroslav@1258: if (path.charAt(p++) != '/') jaroslav@1258: continue; jaroslav@1258: jaroslav@1258: // Skip redundant slashes jaroslav@1258: while (p <= end) { jaroslav@1258: if (path.charAt(p) != '/') break; jaroslav@1258: normal = false; jaroslav@1258: p++; jaroslav@1258: } jaroslav@1258: jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: return normal ? -1 : ns; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // Split the given path into segments, replacing slashes with nulls and jaroslav@1258: // filling in the given segment-index array. jaroslav@1258: // jaroslav@1258: // Preconditions: jaroslav@1258: // segs.length == Number of segments in path jaroslav@1258: // jaroslav@1258: // Postconditions: jaroslav@1258: // All slashes in path replaced by '\0' jaroslav@1258: // segs[i] == Index of first char in segment i (0 <= i < segs.length) jaroslav@1258: // jaroslav@1258: static private void split(char[] path, int[] segs) { jaroslav@1258: int end = path.length - 1; // Index of last char in path jaroslav@1258: int p = 0; // Index of next char in path jaroslav@1258: int i = 0; // Index of current segment jaroslav@1258: jaroslav@1258: // Skip initial slashes jaroslav@1258: while (p <= end) { jaroslav@1258: if (path[p] != '/') break; jaroslav@1258: path[p] = '\0'; jaroslav@1258: p++; jaroslav@1258: } jaroslav@1258: jaroslav@1258: while (p <= end) { jaroslav@1258: jaroslav@1258: // Note start of segment jaroslav@1258: segs[i++] = p++; jaroslav@1258: jaroslav@1258: // Find beginning of next segment jaroslav@1258: while (p <= end) { jaroslav@1258: if (path[p++] != '/') jaroslav@1258: continue; jaroslav@1258: path[p - 1] = '\0'; jaroslav@1258: jaroslav@1258: // Skip redundant slashes jaroslav@1258: while (p <= end) { jaroslav@1258: if (path[p] != '/') break; jaroslav@1258: path[p++] = '\0'; jaroslav@1258: } jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: if (i != segs.length) jaroslav@1258: throw new InternalError(); // ASSERT jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // Join the segments in the given path according to the given segment-index jaroslav@1258: // array, ignoring those segments whose index entries have been set to -1, jaroslav@1258: // and inserting slashes as needed. Return the length of the resulting jaroslav@1258: // path. jaroslav@1258: // jaroslav@1258: // Preconditions: jaroslav@1258: // segs[i] == -1 implies segment i is to be ignored jaroslav@1258: // path computed by split, as above, with '\0' having replaced '/' jaroslav@1258: // jaroslav@1258: // Postconditions: jaroslav@1258: // path[0] .. path[return value] == Resulting path jaroslav@1258: // jaroslav@1258: static private int join(char[] path, int[] segs) { jaroslav@1258: int ns = segs.length; // Number of segments jaroslav@1258: int end = path.length - 1; // Index of last char in path jaroslav@1258: int p = 0; // Index of next path char to write jaroslav@1258: jaroslav@1258: if (path[p] == '\0') { jaroslav@1258: // Restore initial slash for absolute paths jaroslav@1258: path[p++] = '/'; jaroslav@1258: } jaroslav@1258: jaroslav@1258: for (int i = 0; i < ns; i++) { jaroslav@1258: int q = segs[i]; // Current segment jaroslav@1258: if (q == -1) jaroslav@1258: // Ignore this segment jaroslav@1258: continue; jaroslav@1258: jaroslav@1258: if (p == q) { jaroslav@1258: // We're already at this segment, so just skip to its end jaroslav@1258: while ((p <= end) && (path[p] != '\0')) jaroslav@1258: p++; jaroslav@1258: if (p <= end) { jaroslav@1258: // Preserve trailing slash jaroslav@1258: path[p++] = '/'; jaroslav@1258: } jaroslav@1258: } else if (p < q) { jaroslav@1258: // Copy q down to p jaroslav@1258: while ((q <= end) && (path[q] != '\0')) jaroslav@1258: path[p++] = path[q++]; jaroslav@1258: if (q <= end) { jaroslav@1258: // Preserve trailing slash jaroslav@1258: path[p++] = '/'; jaroslav@1258: } jaroslav@1258: } else jaroslav@1258: throw new InternalError(); // ASSERT false jaroslav@1258: } jaroslav@1258: jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // Remove "." segments from the given path, and remove segment pairs jaroslav@1258: // consisting of a non-".." segment followed by a ".." segment. jaroslav@1258: // jaroslav@1258: private static void removeDots(char[] path, int[] segs) { jaroslav@1258: int ns = segs.length; jaroslav@1258: int end = path.length - 1; jaroslav@1258: jaroslav@1258: for (int i = 0; i < ns; i++) { jaroslav@1258: int dots = 0; // Number of dots found (0, 1, or 2) jaroslav@1258: jaroslav@1258: // Find next occurrence of "." or ".." jaroslav@1258: do { jaroslav@1258: int p = segs[i]; jaroslav@1258: if (path[p] == '.') { jaroslav@1258: if (p == end) { jaroslav@1258: dots = 1; jaroslav@1258: break; jaroslav@1258: } else if (path[p + 1] == '\0') { jaroslav@1258: dots = 1; jaroslav@1258: break; jaroslav@1258: } else if ((path[p + 1] == '.') jaroslav@1258: && ((p + 1 == end) jaroslav@1258: || (path[p + 2] == '\0'))) { jaroslav@1258: dots = 2; jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: i++; jaroslav@1258: } while (i < ns); jaroslav@1258: if ((i > ns) || (dots == 0)) jaroslav@1258: break; jaroslav@1258: jaroslav@1258: if (dots == 1) { jaroslav@1258: // Remove this occurrence of "." jaroslav@1258: segs[i] = -1; jaroslav@1258: } else { jaroslav@1258: // If there is a preceding non-".." segment, remove both that jaroslav@1258: // segment and this occurrence of ".."; otherwise, leave this jaroslav@1258: // ".." segment as-is. jaroslav@1258: int j; jaroslav@1258: for (j = i - 1; j >= 0; j--) { jaroslav@1258: if (segs[j] != -1) break; jaroslav@1258: } jaroslav@1258: if (j >= 0) { jaroslav@1258: int q = segs[j]; jaroslav@1258: if (!((path[q] == '.') jaroslav@1258: && (path[q + 1] == '.') jaroslav@1258: && (path[q + 2] == '\0'))) { jaroslav@1258: segs[i] = -1; jaroslav@1258: segs[j] = -1; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // DEVIATION: If the normalized path is relative, and if the first jaroslav@1258: // segment could be parsed as a scheme name, then prepend a "." segment jaroslav@1258: // jaroslav@1258: private static void maybeAddLeadingDot(char[] path, int[] segs) { jaroslav@1258: jaroslav@1258: if (path[0] == '\0') jaroslav@1258: // The path is absolute jaroslav@1258: return; jaroslav@1258: jaroslav@1258: int ns = segs.length; jaroslav@1258: int f = 0; // Index of first segment jaroslav@1258: while (f < ns) { jaroslav@1258: if (segs[f] >= 0) jaroslav@1258: break; jaroslav@1258: f++; jaroslav@1258: } jaroslav@1258: if ((f >= ns) || (f == 0)) jaroslav@1258: // The path is empty, or else the original first segment survived, jaroslav@1258: // in which case we already know that no leading "." is needed jaroslav@1258: return; jaroslav@1258: jaroslav@1258: int p = segs[f]; jaroslav@1258: while ((p < path.length) && (path[p] != ':') && (path[p] != '\0')) p++; jaroslav@1258: if (p >= path.length || path[p] == '\0') jaroslav@1258: // No colon in first segment, so no "." needed jaroslav@1258: return; jaroslav@1258: jaroslav@1258: // At this point we know that the first segment is unused, jaroslav@1258: // hence we can insert a "." segment at that position jaroslav@1258: path[0] = '.'; jaroslav@1258: path[1] = '\0'; jaroslav@1258: segs[0] = 0; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // Normalize the given path string. A normal path string has no empty jaroslav@1258: // segments (i.e., occurrences of "//"), no segments equal to ".", and no jaroslav@1258: // segments equal to ".." that are preceded by a segment not equal to "..". jaroslav@1258: // In contrast to Unix-style pathname normalization, for URI paths we jaroslav@1258: // always retain trailing slashes. jaroslav@1258: // jaroslav@1258: private static String normalize(String ps) { jaroslav@1258: jaroslav@1258: // Does this path need normalization? jaroslav@1258: int ns = needsNormalization(ps); // Number of segments jaroslav@1258: if (ns < 0) jaroslav@1258: // Nope -- just return it jaroslav@1258: return ps; jaroslav@1258: jaroslav@1258: char[] path = ps.toCharArray(); // Path in char-array form jaroslav@1258: jaroslav@1258: // Split path into segments jaroslav@1258: int[] segs = new int[ns]; // Segment-index array jaroslav@1258: split(path, segs); jaroslav@1258: jaroslav@1258: // Remove dots jaroslav@1258: removeDots(path, segs); jaroslav@1258: jaroslav@1258: // Prevent scheme-name confusion jaroslav@1258: maybeAddLeadingDot(path, segs); jaroslav@1258: jaroslav@1258: // Join the remaining segments and return the result jaroslav@1258: String s = new String(path, 0, join(path, segs)); jaroslav@1258: if (s.equals(ps)) { jaroslav@1258: // string was already normalized jaroslav@1258: return ps; jaroslav@1258: } jaroslav@1258: return s; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Character classes for parsing -- jaroslav@1258: jaroslav@1258: // RFC2396 precisely specifies which characters in the US-ASCII charset are jaroslav@1258: // permissible in the various components of a URI reference. We here jaroslav@1258: // define a set of mask pairs to aid in enforcing these restrictions. Each jaroslav@1258: // mask pair consists of two longs, a low mask and a high mask. Taken jaroslav@1258: // together they represent a 128-bit mask, where bit i is set iff the jaroslav@1258: // character with value i is permitted. jaroslav@1258: // jaroslav@1258: // This approach is more efficient than sequentially searching arrays of jaroslav@1258: // permitted characters. It could be made still more efficient by jaroslav@1258: // precompiling the mask information so that a character's presence in a jaroslav@1258: // given mask could be determined by a single table lookup. jaroslav@1258: jaroslav@1258: // Compute the low-order mask for the characters in the given string jaroslav@1258: private static long lowMask(String chars) { jaroslav@1258: int n = chars.length(); jaroslav@1258: long m = 0; jaroslav@1258: for (int i = 0; i < n; i++) { jaroslav@1258: char c = chars.charAt(i); jaroslav@1258: if (c < 64) jaroslav@1258: m |= (1L << c); jaroslav@1258: } jaroslav@1258: return m; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Compute the high-order mask for the characters in the given string jaroslav@1258: private static long highMask(String chars) { jaroslav@1258: int n = chars.length(); jaroslav@1258: long m = 0; jaroslav@1258: for (int i = 0; i < n; i++) { jaroslav@1258: char c = chars.charAt(i); jaroslav@1258: if ((c >= 64) && (c < 128)) jaroslav@1258: m |= (1L << (c - 64)); jaroslav@1258: } jaroslav@1258: return m; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Compute a low-order mask for the characters jaroslav@1258: // between first and last, inclusive jaroslav@1258: private static long lowMask(char first, char last) { jaroslav@1258: long m = 0; jaroslav@1258: int f = Math.max(Math.min(first, 63), 0); jaroslav@1258: int l = Math.max(Math.min(last, 63), 0); jaroslav@1258: for (int i = f; i <= l; i++) jaroslav@1258: m |= 1L << i; jaroslav@1258: return m; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Compute a high-order mask for the characters jaroslav@1258: // between first and last, inclusive jaroslav@1258: private static long highMask(char first, char last) { jaroslav@1258: long m = 0; jaroslav@1258: int f = Math.max(Math.min(first, 127), 64) - 64; jaroslav@1258: int l = Math.max(Math.min(last, 127), 64) - 64; jaroslav@1258: for (int i = f; i <= l; i++) jaroslav@1258: m |= 1L << i; jaroslav@1258: return m; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Tell whether the given character is permitted by the given mask pair jaroslav@1258: private static boolean match(char c, long lowMask, long highMask) { jaroslav@1258: if (c == 0) // 0 doesn't have a slot in the mask. So, it never matches. jaroslav@1258: return false; jaroslav@1258: if (c < 64) jaroslav@1258: return ((1L << c) & lowMask) != 0; jaroslav@1258: if (c < 128) jaroslav@1258: return ((1L << (c - 64)) & highMask) != 0; jaroslav@1258: return false; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Character-class masks, in reverse order from RFC2396 because jaroslav@1258: // initializers for static fields cannot make forward references. jaroslav@1258: jaroslav@1258: // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | jaroslav@1258: // "8" | "9" jaroslav@1258: private static final long L_DIGIT = lowMask('0', '9'); jaroslav@1258: private static final long H_DIGIT = 0L; jaroslav@1258: jaroslav@1258: // upalpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | jaroslav@1258: // "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | jaroslav@1258: // "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" jaroslav@1258: private static final long L_UPALPHA = 0L; jaroslav@1258: private static final long H_UPALPHA = highMask('A', 'Z'); jaroslav@1258: jaroslav@1258: // lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | jaroslav@1258: // "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | jaroslav@1258: // "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" jaroslav@1258: private static final long L_LOWALPHA = 0L; jaroslav@1258: private static final long H_LOWALPHA = highMask('a', 'z'); jaroslav@1258: jaroslav@1258: // alpha = lowalpha | upalpha jaroslav@1258: private static final long L_ALPHA = L_LOWALPHA | L_UPALPHA; jaroslav@1258: private static final long H_ALPHA = H_LOWALPHA | H_UPALPHA; jaroslav@1258: jaroslav@1258: // alphanum = alpha | digit jaroslav@1258: private static final long L_ALPHANUM = L_DIGIT | L_ALPHA; jaroslav@1258: private static final long H_ALPHANUM = H_DIGIT | H_ALPHA; jaroslav@1258: jaroslav@1258: // hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | jaroslav@1258: // "a" | "b" | "c" | "d" | "e" | "f" jaroslav@1258: private static final long L_HEX = L_DIGIT; jaroslav@1258: private static final long H_HEX = highMask('A', 'F') | highMask('a', 'f'); jaroslav@1258: jaroslav@1258: // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | jaroslav@1258: // "(" | ")" jaroslav@1258: private static final long L_MARK = lowMask("-_.!~*'()"); jaroslav@1258: private static final long H_MARK = highMask("-_.!~*'()"); jaroslav@1258: jaroslav@1258: // unreserved = alphanum | mark jaroslav@1258: private static final long L_UNRESERVED = L_ALPHANUM | L_MARK; jaroslav@1258: private static final long H_UNRESERVED = H_ALPHANUM | H_MARK; jaroslav@1258: jaroslav@1258: // reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | jaroslav@1258: // "$" | "," | "[" | "]" jaroslav@1258: // Added per RFC2732: "[", "]" jaroslav@1258: private static final long L_RESERVED = lowMask(";/?:@&=+$,[]"); jaroslav@1258: private static final long H_RESERVED = highMask(";/?:@&=+$,[]"); jaroslav@1258: jaroslav@1258: // The zero'th bit is used to indicate that escape pairs and non-US-ASCII jaroslav@1258: // characters are allowed; this is handled by the scanEscape method below. jaroslav@1258: private static final long L_ESCAPED = 1L; jaroslav@1258: private static final long H_ESCAPED = 0L; jaroslav@1258: jaroslav@1258: // uric = reserved | unreserved | escaped jaroslav@1258: private static final long L_URIC = L_RESERVED | L_UNRESERVED | L_ESCAPED; jaroslav@1258: private static final long H_URIC = H_RESERVED | H_UNRESERVED | H_ESCAPED; jaroslav@1258: jaroslav@1258: // pchar = unreserved | escaped | jaroslav@1258: // ":" | "@" | "&" | "=" | "+" | "$" | "," jaroslav@1258: private static final long L_PCHAR jaroslav@1258: = L_UNRESERVED | L_ESCAPED | lowMask(":@&=+$,"); jaroslav@1258: private static final long H_PCHAR jaroslav@1258: = H_UNRESERVED | H_ESCAPED | highMask(":@&=+$,"); jaroslav@1258: jaroslav@1258: // All valid path characters jaroslav@1258: private static final long L_PATH = L_PCHAR | lowMask(";/"); jaroslav@1258: private static final long H_PATH = H_PCHAR | highMask(";/"); jaroslav@1258: jaroslav@1258: // Dash, for use in domainlabel and toplabel jaroslav@1258: private static final long L_DASH = lowMask("-"); jaroslav@1258: private static final long H_DASH = highMask("-"); jaroslav@1258: jaroslav@1258: // Dot, for use in hostnames jaroslav@1258: private static final long L_DOT = lowMask("."); jaroslav@1258: private static final long H_DOT = highMask("."); jaroslav@1258: jaroslav@1258: // userinfo = *( unreserved | escaped | jaroslav@1258: // ";" | ":" | "&" | "=" | "+" | "$" | "," ) jaroslav@1258: private static final long L_USERINFO jaroslav@1258: = L_UNRESERVED | L_ESCAPED | lowMask(";:&=+$,"); jaroslav@1258: private static final long H_USERINFO jaroslav@1258: = H_UNRESERVED | H_ESCAPED | highMask(";:&=+$,"); jaroslav@1258: jaroslav@1258: // reg_name = 1*( unreserved | escaped | "$" | "," | jaroslav@1258: // ";" | ":" | "@" | "&" | "=" | "+" ) jaroslav@1258: private static final long L_REG_NAME jaroslav@1258: = L_UNRESERVED | L_ESCAPED | lowMask("$,;:@&=+"); jaroslav@1258: private static final long H_REG_NAME jaroslav@1258: = H_UNRESERVED | H_ESCAPED | highMask("$,;:@&=+"); jaroslav@1258: jaroslav@1258: // All valid characters for server-based authorities jaroslav@1258: private static final long L_SERVER jaroslav@1258: = L_USERINFO | L_ALPHANUM | L_DASH | lowMask(".:@[]"); jaroslav@1258: private static final long H_SERVER jaroslav@1258: = H_USERINFO | H_ALPHANUM | H_DASH | highMask(".:@[]"); jaroslav@1258: jaroslav@1258: // Special case of server authority that represents an IPv6 address jaroslav@1258: // In this case, a % does not signify an escape sequence jaroslav@1258: private static final long L_SERVER_PERCENT jaroslav@1258: = L_SERVER | lowMask("%"); jaroslav@1258: private static final long H_SERVER_PERCENT jaroslav@1258: = H_SERVER | highMask("%"); jaroslav@1258: private static final long L_LEFT_BRACKET = lowMask("["); jaroslav@1258: private static final long H_LEFT_BRACKET = highMask("["); jaroslav@1258: jaroslav@1258: // scheme = alpha *( alpha | digit | "+" | "-" | "." ) jaroslav@1258: private static final long L_SCHEME = L_ALPHA | L_DIGIT | lowMask("+-."); jaroslav@1258: private static final long H_SCHEME = H_ALPHA | H_DIGIT | highMask("+-."); jaroslav@1258: jaroslav@1258: // uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | jaroslav@1258: // "&" | "=" | "+" | "$" | "," jaroslav@1258: private static final long L_URIC_NO_SLASH jaroslav@1258: = L_UNRESERVED | L_ESCAPED | lowMask(";?:@&=+$,"); jaroslav@1258: private static final long H_URIC_NO_SLASH jaroslav@1258: = H_UNRESERVED | H_ESCAPED | highMask(";?:@&=+$,"); jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Escaping and encoding -- jaroslav@1258: jaroslav@1258: private final static char[] hexDigits = { jaroslav@1258: '0', '1', '2', '3', '4', '5', '6', '7', jaroslav@1258: '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' jaroslav@1258: }; jaroslav@1258: jaroslav@1258: private static void appendEscape(StringBuffer sb, byte b) { jaroslav@1258: sb.append('%'); jaroslav@1258: sb.append(hexDigits[(b >> 4) & 0x0f]); jaroslav@1258: sb.append(hexDigits[(b >> 0) & 0x0f]); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static void appendEncoded(StringBuffer sb, char c) { jaroslav@1258: ByteBuffer bb = null; jaroslav@1258: try { jaroslav@1258: bb = ThreadLocalCoders.encoderFor("UTF-8") jaroslav@1258: .encode(CharBuffer.wrap("" + c)); jaroslav@1258: } catch (CharacterCodingException x) { jaroslav@1258: assert false; jaroslav@1258: } jaroslav@1258: while (bb.hasRemaining()) { jaroslav@1258: int b = bb.get() & 0xff; jaroslav@1258: if (b >= 0x80) jaroslav@1258: appendEscape(sb, (byte)b); jaroslav@1258: else jaroslav@1258: sb.append((char)b); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Quote any characters in s that are not permitted jaroslav@1258: // by the given mask pair jaroslav@1258: // jaroslav@1258: private static String quote(String s, long lowMask, long highMask) { jaroslav@1258: int n = s.length(); jaroslav@1258: StringBuffer sb = null; jaroslav@1258: boolean allowNonASCII = ((lowMask & L_ESCAPED) != 0); jaroslav@1258: for (int i = 0; i < s.length(); i++) { jaroslav@1258: char c = s.charAt(i); jaroslav@1258: if (c < '\u0080') { jaroslav@1258: if (!match(c, lowMask, highMask)) { jaroslav@1258: if (sb == null) { jaroslav@1258: sb = new StringBuffer(); jaroslav@1258: sb.append(s.substring(0, i)); jaroslav@1258: } jaroslav@1258: appendEscape(sb, (byte)c); jaroslav@1258: } else { jaroslav@1258: if (sb != null) jaroslav@1258: sb.append(c); jaroslav@1258: } jaroslav@1258: } else if (allowNonASCII jaroslav@1258: && (Character.isSpaceChar(c) jaroslav@1258: || Character.isISOControl(c))) { jaroslav@1258: if (sb == null) { jaroslav@1258: sb = new StringBuffer(); jaroslav@1258: sb.append(s.substring(0, i)); jaroslav@1258: } jaroslav@1258: appendEncoded(sb, c); jaroslav@1258: } else { jaroslav@1258: if (sb != null) jaroslav@1258: sb.append(c); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: return (sb == null) ? s : sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Encodes all characters >= \u0080 into escaped, normalized UTF-8 octets, jaroslav@1258: // assuming that s is otherwise legal jaroslav@1258: // jaroslav@1258: private static String encode(String s) { jaroslav@1258: int n = s.length(); jaroslav@1258: if (n == 0) jaroslav@1258: return s; jaroslav@1258: jaroslav@1258: // First check whether we actually need to encode jaroslav@1258: for (int i = 0;;) { jaroslav@1258: if (s.charAt(i) >= '\u0080') jaroslav@1258: break; jaroslav@1258: if (++i >= n) jaroslav@1258: return s; jaroslav@1258: } jaroslav@1258: jaroslav@1258: String ns = Normalizer.normalize(s, Normalizer.Form.NFC); jaroslav@1258: ByteBuffer bb = null; jaroslav@1258: try { jaroslav@1258: bb = ThreadLocalCoders.encoderFor("UTF-8") jaroslav@1258: .encode(CharBuffer.wrap(ns)); jaroslav@1258: } catch (CharacterCodingException x) { jaroslav@1258: assert false; jaroslav@1258: } jaroslav@1258: jaroslav@1258: StringBuffer sb = new StringBuffer(); jaroslav@1258: while (bb.hasRemaining()) { jaroslav@1258: int b = bb.get() & 0xff; jaroslav@1258: if (b >= 0x80) jaroslav@1258: appendEscape(sb, (byte)b); jaroslav@1258: else jaroslav@1258: sb.append((char)b); jaroslav@1258: } jaroslav@1258: return sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static int decode(char c) { jaroslav@1258: if ((c >= '0') && (c <= '9')) jaroslav@1258: return c - '0'; jaroslav@1258: if ((c >= 'a') && (c <= 'f')) jaroslav@1258: return c - 'a' + 10; jaroslav@1258: if ((c >= 'A') && (c <= 'F')) jaroslav@1258: return c - 'A' + 10; jaroslav@1258: assert false; jaroslav@1258: return -1; jaroslav@1258: } jaroslav@1258: jaroslav@1258: private static byte decode(char c1, char c2) { jaroslav@1258: return (byte)( ((decode(c1) & 0xf) << 4) jaroslav@1258: | ((decode(c2) & 0xf) << 0)); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Evaluates all escapes in s, applying UTF-8 decoding if needed. Assumes jaroslav@1258: // that escapes are well-formed syntactically, i.e., of the form %XX. If a jaroslav@1258: // sequence of escaped octets is not valid UTF-8 then the erroneous octets jaroslav@1258: // are replaced with '\uFFFD'. jaroslav@1258: // Exception: any "%" found between "[]" is left alone. It is an IPv6 literal jaroslav@1258: // with a scope_id jaroslav@1258: // jaroslav@1258: private static String decode(String s) { jaroslav@1258: if (s == null) jaroslav@1258: return s; jaroslav@1258: int n = s.length(); jaroslav@1258: if (n == 0) jaroslav@1258: return s; jaroslav@1258: if (s.indexOf('%') < 0) jaroslav@1258: return s; jaroslav@1258: jaroslav@1258: StringBuffer sb = new StringBuffer(n); jaroslav@1258: ByteBuffer bb = ByteBuffer.allocate(n); jaroslav@1258: CharBuffer cb = CharBuffer.allocate(n); jaroslav@1258: CharsetDecoder dec = ThreadLocalCoders.decoderFor("UTF-8") jaroslav@1258: .onMalformedInput(CodingErrorAction.REPLACE) jaroslav@1258: .onUnmappableCharacter(CodingErrorAction.REPLACE); jaroslav@1258: jaroslav@1258: // This is not horribly efficient, but it will do for now jaroslav@1258: char c = s.charAt(0); jaroslav@1258: boolean betweenBrackets = false; jaroslav@1258: jaroslav@1258: for (int i = 0; i < n;) { jaroslav@1258: assert c == s.charAt(i); // Loop invariant jaroslav@1258: if (c == '[') { jaroslav@1258: betweenBrackets = true; jaroslav@1258: } else if (betweenBrackets && c == ']') { jaroslav@1258: betweenBrackets = false; jaroslav@1258: } jaroslav@1258: if (c != '%' || betweenBrackets) { jaroslav@1258: sb.append(c); jaroslav@1258: if (++i >= n) jaroslav@1258: break; jaroslav@1258: c = s.charAt(i); jaroslav@1258: continue; jaroslav@1258: } jaroslav@1258: bb.clear(); jaroslav@1258: int ui = i; jaroslav@1258: for (;;) { jaroslav@1258: assert (n - i >= 2); jaroslav@1258: bb.put(decode(s.charAt(++i), s.charAt(++i))); jaroslav@1258: if (++i >= n) jaroslav@1258: break; jaroslav@1258: c = s.charAt(i); jaroslav@1258: if (c != '%') jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: bb.flip(); jaroslav@1258: cb.clear(); jaroslav@1258: dec.reset(); jaroslav@1258: CoderResult cr = dec.decode(bb, cb, true); jaroslav@1258: assert cr.isUnderflow(); jaroslav@1258: cr = dec.flush(cb); jaroslav@1258: assert cr.isUnderflow(); jaroslav@1258: sb.append(cb.flip().toString()); jaroslav@1258: } jaroslav@1258: jaroslav@1258: return sb.toString(); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Parsing -- jaroslav@1258: jaroslav@1258: // For convenience we wrap the input URI string in a new instance of the jaroslav@1258: // following internal class. This saves always having to pass the input jaroslav@1258: // string as an argument to each internal scan/parse method. jaroslav@1258: jaroslav@1258: private class Parser { jaroslav@1258: jaroslav@1258: private String input; // URI input string jaroslav@1258: private boolean requireServerAuthority = false; jaroslav@1258: jaroslav@1258: Parser(String s) { jaroslav@1258: input = s; jaroslav@1258: string = s; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // -- Methods for throwing URISyntaxException in various ways -- jaroslav@1258: jaroslav@1258: private void fail(String reason) throws URISyntaxException { jaroslav@1258: throw new URISyntaxException(input, reason); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void fail(String reason, int p) throws URISyntaxException { jaroslav@1258: throw new URISyntaxException(input, reason, p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void failExpecting(String expected, int p) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: fail("Expected " + expected, p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: private void failExpecting(String expected, String prior, int p) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: fail("Expected " + expected + " following " + prior, p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Simple access to the input string -- jaroslav@1258: jaroslav@1258: // Return a substring of the input string jaroslav@1258: // jaroslav@1258: private String substring(int start, int end) { jaroslav@1258: return input.substring(start, end); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Return the char at position p, jaroslav@1258: // assuming that p < input.length() jaroslav@1258: // jaroslav@1258: private char charAt(int p) { jaroslav@1258: return input.charAt(p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Tells whether start < end and, if so, whether charAt(start) == c jaroslav@1258: // jaroslav@1258: private boolean at(int start, int end, char c) { jaroslav@1258: return (start < end) && (charAt(start) == c); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Tells whether start + s.length() < end and, if so, jaroslav@1258: // whether the chars at the start position match s exactly jaroslav@1258: // jaroslav@1258: private boolean at(int start, int end, String s) { jaroslav@1258: int p = start; jaroslav@1258: int sn = s.length(); jaroslav@1258: if (sn > end - p) jaroslav@1258: return false; jaroslav@1258: int i = 0; jaroslav@1258: while (i < sn) { jaroslav@1258: if (charAt(p++) != s.charAt(i)) { jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: i++; jaroslav@1258: } jaroslav@1258: return (i == sn); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Scanning -- jaroslav@1258: jaroslav@1258: // The various scan and parse methods that follow use a uniform jaroslav@1258: // convention of taking the current start position and end index as jaroslav@1258: // their first two arguments. The start is inclusive while the end is jaroslav@1258: // exclusive, just as in the String class, i.e., a start/end pair jaroslav@1258: // denotes the left-open interval [start, end) of the input string. jaroslav@1258: // jaroslav@1258: // These methods never proceed past the end position. They may return jaroslav@1258: // -1 to indicate outright failure, but more often they simply return jaroslav@1258: // the position of the first char after the last char scanned. Thus jaroslav@1258: // a typical idiom is jaroslav@1258: // jaroslav@1258: // int p = start; jaroslav@1258: // int q = scan(p, end, ...); jaroslav@1258: // if (q > p) jaroslav@1258: // // We scanned something jaroslav@1258: // ...; jaroslav@1258: // else if (q == p) jaroslav@1258: // // We scanned nothing jaroslav@1258: // ...; jaroslav@1258: // else if (q == -1) jaroslav@1258: // // Something went wrong jaroslav@1258: // ...; jaroslav@1258: jaroslav@1258: jaroslav@1258: // Scan a specific char: If the char at the given start position is jaroslav@1258: // equal to c, return the index of the next char; otherwise, return the jaroslav@1258: // start position. jaroslav@1258: // jaroslav@1258: private int scan(int start, int end, char c) { jaroslav@1258: if ((start < end) && (charAt(start) == c)) jaroslav@1258: return start + 1; jaroslav@1258: return start; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan forward from the given start position. Stop at the first char jaroslav@1258: // in the err string (in which case -1 is returned), or the first char jaroslav@1258: // in the stop string (in which case the index of the preceding char is jaroslav@1258: // returned), or the end of the input string (in which case the length jaroslav@1258: // of the input string is returned). May return the start position if jaroslav@1258: // nothing matches. jaroslav@1258: // jaroslav@1258: private int scan(int start, int end, String err, String stop) { jaroslav@1258: int p = start; jaroslav@1258: while (p < end) { jaroslav@1258: char c = charAt(p); jaroslav@1258: if (err.indexOf(c) >= 0) jaroslav@1258: return -1; jaroslav@1258: if (stop.indexOf(c) >= 0) jaroslav@1258: break; jaroslav@1258: p++; jaroslav@1258: } jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan a potential escape sequence, starting at the given position, jaroslav@1258: // with the given first char (i.e., charAt(start) == c). jaroslav@1258: // jaroslav@1258: // This method assumes that if escapes are allowed then visible jaroslav@1258: // non-US-ASCII chars are also allowed. jaroslav@1258: // jaroslav@1258: private int scanEscape(int start, int n, char first) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: char c = first; jaroslav@1258: if (c == '%') { jaroslav@1258: // Process escape pair jaroslav@1258: if ((p + 3 <= n) jaroslav@1258: && match(charAt(p + 1), L_HEX, H_HEX) jaroslav@1258: && match(charAt(p + 2), L_HEX, H_HEX)) { jaroslav@1258: return p + 3; jaroslav@1258: } jaroslav@1258: fail("Malformed escape pair", p); jaroslav@1258: } else if ((c > 128) jaroslav@1258: && !Character.isSpaceChar(c) jaroslav@1258: && !Character.isISOControl(c)) { jaroslav@1258: // Allow unescaped but visible non-US-ASCII chars jaroslav@1258: return p + 1; jaroslav@1258: } jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan chars that match the given mask pair jaroslav@1258: // jaroslav@1258: private int scan(int start, int n, long lowMask, long highMask) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: while (p < n) { jaroslav@1258: char c = charAt(p); jaroslav@1258: if (match(c, lowMask, highMask)) { jaroslav@1258: p++; jaroslav@1258: continue; jaroslav@1258: } jaroslav@1258: if ((lowMask & L_ESCAPED) != 0) { jaroslav@1258: int q = scanEscape(p, n, c); jaroslav@1258: if (q > p) { jaroslav@1258: p = q; jaroslav@1258: continue; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Check that each of the chars in [start, end) matches the given mask jaroslav@1258: // jaroslav@1258: private void checkChars(int start, int end, jaroslav@1258: long lowMask, long highMask, jaroslav@1258: String what) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = scan(start, end, lowMask, highMask); jaroslav@1258: if (p < end) jaroslav@1258: fail("Illegal character in " + what, p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Check that the char at position p matches the given mask jaroslav@1258: // jaroslav@1258: private void checkChar(int p, jaroslav@1258: long lowMask, long highMask, jaroslav@1258: String what) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: checkChars(p, p + 1, lowMask, highMask, what); jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // -- Parsing -- jaroslav@1258: jaroslav@1258: // [:][#] jaroslav@1258: // jaroslav@1258: void parse(boolean rsa) throws URISyntaxException { jaroslav@1258: requireServerAuthority = rsa; jaroslav@1258: int ssp; // Start of scheme-specific part jaroslav@1258: int n = input.length(); jaroslav@1258: int p = scan(0, n, "/?#", ":"); jaroslav@1258: if ((p >= 0) && at(p, n, ':')) { jaroslav@1258: if (p == 0) jaroslav@1258: failExpecting("scheme name", 0); jaroslav@1258: checkChar(0, L_ALPHA, H_ALPHA, "scheme name"); jaroslav@1258: checkChars(1, p, L_SCHEME, H_SCHEME, "scheme name"); jaroslav@1258: scheme = substring(0, p); jaroslav@1258: p++; // Skip ':' jaroslav@1258: ssp = p; jaroslav@1258: if (at(p, n, '/')) { jaroslav@1258: p = parseHierarchical(p, n); jaroslav@1258: } else { jaroslav@1258: int q = scan(p, n, "", "#"); jaroslav@1258: if (q <= p) jaroslav@1258: failExpecting("scheme-specific part", p); jaroslav@1258: checkChars(p, q, L_URIC, H_URIC, "opaque part"); jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: ssp = 0; jaroslav@1258: p = parseHierarchical(0, n); jaroslav@1258: } jaroslav@1258: schemeSpecificPart = substring(ssp, p); jaroslav@1258: if (at(p, n, '#')) { jaroslav@1258: checkChars(p + 1, n, L_URIC, H_URIC, "fragment"); jaroslav@1258: fragment = substring(p + 1, n); jaroslav@1258: p = n; jaroslav@1258: } jaroslav@1258: if (p < n) jaroslav@1258: fail("end of URI", p); jaroslav@1258: } jaroslav@1258: jaroslav@1258: // [//authority][?] jaroslav@1258: // jaroslav@1258: // DEVIATION from RFC2396: We allow an empty authority component as jaroslav@1258: // long as it's followed by a non-empty path, query component, or jaroslav@1258: // fragment component. This is so that URIs such as "file:///foo/bar" jaroslav@1258: // will parse. This seems to be the intent of RFC2396, though the jaroslav@1258: // grammar does not permit it. If the authority is empty then the jaroslav@1258: // userInfo, host, and port components are undefined. jaroslav@1258: // jaroslav@1258: // DEVIATION from RFC2396: We allow empty relative paths. This seems jaroslav@1258: // to be the intent of RFC2396, but the grammar does not permit it. jaroslav@1258: // The primary consequence of this deviation is that "#f" parses as a jaroslav@1258: // relative URI with an empty path. jaroslav@1258: // jaroslav@1258: private int parseHierarchical(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: if (at(p, n, '/') && at(p + 1, n, '/')) { jaroslav@1258: p += 2; jaroslav@1258: int q = scan(p, n, "", "/?#"); jaroslav@1258: if (q > p) { jaroslav@1258: p = parseAuthority(p, q); jaroslav@1258: } else if (q < n) { jaroslav@1258: // DEVIATION: Allow empty authority prior to non-empty jaroslav@1258: // path, query component or fragment identifier jaroslav@1258: } else jaroslav@1258: failExpecting("authority", p); jaroslav@1258: } jaroslav@1258: int q = scan(p, n, "", "?#"); // DEVIATION: May be empty jaroslav@1258: checkChars(p, q, L_PATH, H_PATH, "path"); jaroslav@1258: path = substring(p, q); jaroslav@1258: p = q; jaroslav@1258: if (at(p, n, '?')) { jaroslav@1258: p++; jaroslav@1258: q = scan(p, n, "", "#"); jaroslav@1258: checkChars(p, q, L_URIC, H_URIC, "query"); jaroslav@1258: query = substring(p, q); jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // authority = server | reg_name jaroslav@1258: // jaroslav@1258: // Ambiguity: An authority that is a registry name rather than a server jaroslav@1258: // might have a prefix that parses as a server. We use the fact that jaroslav@1258: // the authority component is always followed by '/' or the end of the jaroslav@1258: // input string to resolve this: If the complete authority did not jaroslav@1258: // parse as a server then we try to parse it as a registry name. jaroslav@1258: // jaroslav@1258: private int parseAuthority(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q = p; jaroslav@1258: URISyntaxException ex = null; jaroslav@1258: jaroslav@1258: boolean serverChars; jaroslav@1258: boolean regChars; jaroslav@1258: jaroslav@1258: if (scan(p, n, "", "]") > p) { jaroslav@1258: // contains a literal IPv6 address, therefore % is allowed jaroslav@1258: serverChars = (scan(p, n, L_SERVER_PERCENT, H_SERVER_PERCENT) == n); jaroslav@1258: } else { jaroslav@1258: serverChars = (scan(p, n, L_SERVER, H_SERVER) == n); jaroslav@1258: } jaroslav@1258: regChars = (scan(p, n, L_REG_NAME, H_REG_NAME) == n); jaroslav@1258: jaroslav@1258: if (regChars && !serverChars) { jaroslav@1258: // Must be a registry-based authority jaroslav@1258: authority = substring(p, n); jaroslav@1258: return n; jaroslav@1258: } jaroslav@1258: jaroslav@1258: if (serverChars) { jaroslav@1258: // Might be (probably is) a server-based authority, so attempt jaroslav@1258: // to parse it as such. If the attempt fails, try to treat it jaroslav@1258: // as a registry-based authority. jaroslav@1258: try { jaroslav@1258: q = parseServer(p, n); jaroslav@1258: if (q < n) jaroslav@1258: failExpecting("end of authority", q); jaroslav@1258: authority = substring(p, n); jaroslav@1258: } catch (URISyntaxException x) { jaroslav@1258: // Undo results of failed parse jaroslav@1258: userInfo = null; jaroslav@1258: host = null; jaroslav@1258: port = -1; jaroslav@1258: if (requireServerAuthority) { jaroslav@1258: // If we're insisting upon a server-based authority, jaroslav@1258: // then just re-throw the exception jaroslav@1258: throw x; jaroslav@1258: } else { jaroslav@1258: // Save the exception in case it doesn't parse as a jaroslav@1258: // registry either jaroslav@1258: ex = x; jaroslav@1258: q = p; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: if (q < n) { jaroslav@1258: if (regChars) { jaroslav@1258: // Registry-based authority jaroslav@1258: authority = substring(p, n); jaroslav@1258: } else if (ex != null) { jaroslav@1258: // Re-throw exception; it was probably due to jaroslav@1258: // a malformed IPv6 address jaroslav@1258: throw ex; jaroslav@1258: } else { jaroslav@1258: fail("Illegal character in authority", q); jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: return n; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // [@][:] jaroslav@1258: // jaroslav@1258: private int parseServer(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: jaroslav@1258: // userinfo jaroslav@1258: q = scan(p, n, "/?#", "@"); jaroslav@1258: if ((q >= p) && at(q, n, '@')) { jaroslav@1258: checkChars(p, q, L_USERINFO, H_USERINFO, "user info"); jaroslav@1258: userInfo = substring(p, q); jaroslav@1258: p = q + 1; // Skip '@' jaroslav@1258: } jaroslav@1258: jaroslav@1258: // hostname, IPv4 address, or IPv6 address jaroslav@1258: if (at(p, n, '[')) { jaroslav@1258: // DEVIATION from RFC2396: Support IPv6 addresses, per RFC2732 jaroslav@1258: p++; jaroslav@1258: q = scan(p, n, "/?#", "]"); jaroslav@1258: if ((q > p) && at(q, n, ']')) { jaroslav@1258: // look for a "%" scope id jaroslav@1258: int r = scan (p, q, "", "%"); jaroslav@1258: if (r > p) { jaroslav@1258: parseIPv6Reference(p, r); jaroslav@1258: if (r+1 == q) { jaroslav@1258: fail ("scope id expected"); jaroslav@1258: } jaroslav@1258: checkChars (r+1, q, L_ALPHANUM, H_ALPHANUM, jaroslav@1258: "scope id"); jaroslav@1258: } else { jaroslav@1258: parseIPv6Reference(p, q); jaroslav@1258: } jaroslav@1258: host = substring(p-1, q+1); jaroslav@1258: p = q + 1; jaroslav@1258: } else { jaroslav@1258: failExpecting("closing bracket for IPv6 address", q); jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: q = parseIPv4Address(p, n); jaroslav@1258: if (q <= p) jaroslav@1258: q = parseHostname(p, n); jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // port jaroslav@1258: if (at(p, n, ':')) { jaroslav@1258: p++; jaroslav@1258: q = scan(p, n, "", "/"); jaroslav@1258: if (q > p) { jaroslav@1258: checkChars(p, q, L_DIGIT, H_DIGIT, "port number"); jaroslav@1258: try { jaroslav@1258: port = Integer.parseInt(substring(p, q)); jaroslav@1258: } catch (NumberFormatException x) { jaroslav@1258: fail("Malformed port number", p); jaroslav@1258: } jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: if (p < n) jaroslav@1258: failExpecting("port number", p); jaroslav@1258: jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan a string of decimal digits whose value fits in a byte jaroslav@1258: // jaroslav@1258: private int scanByte(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q = scan(p, n, L_DIGIT, H_DIGIT); jaroslav@1258: if (q <= p) return q; jaroslav@1258: if (Integer.parseInt(substring(p, q)) > 255) return p; jaroslav@1258: return q; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan an IPv4 address. jaroslav@1258: // jaroslav@1258: // If the strict argument is true then we require that the given jaroslav@1258: // interval contain nothing besides an IPv4 address; if it is false jaroslav@1258: // then we only require that it start with an IPv4 address. jaroslav@1258: // jaroslav@1258: // If the interval does not contain or start with (depending upon the jaroslav@1258: // strict argument) a legal IPv4 address characters then we return -1 jaroslav@1258: // immediately; otherwise we insist that these characters parse as a jaroslav@1258: // legal IPv4 address and throw an exception on failure. jaroslav@1258: // jaroslav@1258: // We assume that any string of decimal digits and dots must be an IPv4 jaroslav@1258: // address. It won't parse as a hostname anyway, so making that jaroslav@1258: // assumption here allows more meaningful exceptions to be thrown. jaroslav@1258: // jaroslav@1258: private int scanIPv4Address(int start, int n, boolean strict) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: int m = scan(p, n, L_DIGIT | L_DOT, H_DIGIT | H_DOT); jaroslav@1258: if ((m <= p) || (strict && (m != n))) jaroslav@1258: return -1; jaroslav@1258: for (;;) { jaroslav@1258: // Per RFC2732: At most three digits per byte jaroslav@1258: // Further constraint: Each element fits in a byte jaroslav@1258: if ((q = scanByte(p, m)) <= p) break; p = q; jaroslav@1258: if ((q = scan(p, m, '.')) <= p) break; p = q; jaroslav@1258: if ((q = scanByte(p, m)) <= p) break; p = q; jaroslav@1258: if ((q = scan(p, m, '.')) <= p) break; p = q; jaroslav@1258: if ((q = scanByte(p, m)) <= p) break; p = q; jaroslav@1258: if ((q = scan(p, m, '.')) <= p) break; p = q; jaroslav@1258: if ((q = scanByte(p, m)) <= p) break; p = q; jaroslav@1258: if (q < m) break; jaroslav@1258: return q; jaroslav@1258: } jaroslav@1258: fail("Malformed IPv4 address", q); jaroslav@1258: return -1; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Take an IPv4 address: Throw an exception if the given interval jaroslav@1258: // contains anything except an IPv4 address jaroslav@1258: // jaroslav@1258: private int takeIPv4Address(int start, int n, String expected) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = scanIPv4Address(start, n, true); jaroslav@1258: if (p <= start) jaroslav@1258: failExpecting(expected, start); jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Attempt to parse an IPv4 address, returning -1 on failure but jaroslav@1258: // allowing the given interval to contain [:] after jaroslav@1258: // the IPv4 address. jaroslav@1258: // jaroslav@1258: private int parseIPv4Address(int start, int n) { jaroslav@1258: int p; jaroslav@1258: jaroslav@1258: try { jaroslav@1258: p = scanIPv4Address(start, n, false); jaroslav@1258: } catch (URISyntaxException x) { jaroslav@1258: return -1; jaroslav@1258: } catch (NumberFormatException nfe) { jaroslav@1258: return -1; jaroslav@1258: } jaroslav@1258: jaroslav@1258: if (p > start && p < n) { jaroslav@1258: // IPv4 address is followed by something - check that jaroslav@1258: // it's a ":" as this is the only valid character to jaroslav@1258: // follow an address. jaroslav@1258: if (charAt(p) != ':') { jaroslav@1258: p = -1; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: jaroslav@1258: if (p > start) jaroslav@1258: host = substring(start, p); jaroslav@1258: jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // hostname = domainlabel [ "." ] | 1*( domainlabel "." ) toplabel [ "." ] jaroslav@1258: // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum jaroslav@1258: // toplabel = alpha | alpha *( alphanum | "-" ) alphanum jaroslav@1258: // jaroslav@1258: private int parseHostname(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: int l = -1; // Start of last parsed label jaroslav@1258: jaroslav@1258: do { jaroslav@1258: // domainlabel = alphanum [ *( alphanum | "-" ) alphanum ] jaroslav@1258: q = scan(p, n, L_ALPHANUM, H_ALPHANUM); jaroslav@1258: if (q <= p) jaroslav@1258: break; jaroslav@1258: l = p; jaroslav@1258: if (q > p) { jaroslav@1258: p = q; jaroslav@1258: q = scan(p, n, L_ALPHANUM | L_DASH, H_ALPHANUM | H_DASH); jaroslav@1258: if (q > p) { jaroslav@1258: if (charAt(q - 1) == '-') jaroslav@1258: fail("Illegal character in hostname", q - 1); jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: } jaroslav@1258: q = scan(p, n, '.'); jaroslav@1258: if (q <= p) jaroslav@1258: break; jaroslav@1258: p = q; jaroslav@1258: } while (p < n); jaroslav@1258: jaroslav@1258: if ((p < n) && !at(p, n, ':')) jaroslav@1258: fail("Illegal character in hostname", p); jaroslav@1258: jaroslav@1258: if (l < 0) jaroslav@1258: failExpecting("hostname", start); jaroslav@1258: jaroslav@1258: // for a fully qualified hostname check that the rightmost jaroslav@1258: // label starts with an alpha character. jaroslav@1258: if (l > start && !match(charAt(l), L_ALPHA, H_ALPHA)) { jaroslav@1258: fail("Illegal character in hostname", l); jaroslav@1258: } jaroslav@1258: jaroslav@1258: host = substring(start, p); jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: jaroslav@1258: // IPv6 address parsing, from RFC2373: IPv6 Addressing Architecture jaroslav@1258: // jaroslav@1258: // Bug: The grammar in RFC2373 Appendix B does not allow addresses of jaroslav@1258: // the form ::12.34.56.78, which are clearly shown in the examples jaroslav@1258: // earlier in the document. Here is the original grammar: jaroslav@1258: // jaroslav@1258: // IPv6address = hexpart [ ":" IPv4address ] jaroslav@1258: // hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ] jaroslav@1258: // hexseq = hex4 *( ":" hex4) jaroslav@1258: // hex4 = 1*4HEXDIG jaroslav@1258: // jaroslav@1258: // We therefore use the following revised grammar: jaroslav@1258: // jaroslav@1258: // IPv6address = hexseq [ ":" IPv4address ] jaroslav@1258: // | hexseq [ "::" [ hexpost ] ] jaroslav@1258: // | "::" [ hexpost ] jaroslav@1258: // hexpost = hexseq | hexseq ":" IPv4address | IPv4address jaroslav@1258: // hexseq = hex4 *( ":" hex4) jaroslav@1258: // hex4 = 1*4HEXDIG jaroslav@1258: // jaroslav@1258: // This covers all and only the following cases: jaroslav@1258: // jaroslav@1258: // hexseq jaroslav@1258: // hexseq : IPv4address jaroslav@1258: // hexseq :: jaroslav@1258: // hexseq :: hexseq jaroslav@1258: // hexseq :: hexseq : IPv4address jaroslav@1258: // hexseq :: IPv4address jaroslav@1258: // :: hexseq jaroslav@1258: // :: hexseq : IPv4address jaroslav@1258: // :: IPv4address jaroslav@1258: // :: jaroslav@1258: // jaroslav@1258: // Additionally we constrain the IPv6 address as follows :- jaroslav@1258: // jaroslav@1258: // i. IPv6 addresses without compressed zeros should contain jaroslav@1258: // exactly 16 bytes. jaroslav@1258: // jaroslav@1258: // ii. IPv6 addresses with compressed zeros should contain jaroslav@1258: // less than 16 bytes. jaroslav@1258: jaroslav@1258: private int ipv6byteCount = 0; jaroslav@1258: jaroslav@1258: private int parseIPv6Reference(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: boolean compressedZeros = false; jaroslav@1258: jaroslav@1258: q = scanHexSeq(p, n); jaroslav@1258: jaroslav@1258: if (q > p) { jaroslav@1258: p = q; jaroslav@1258: if (at(p, n, "::")) { jaroslav@1258: compressedZeros = true; jaroslav@1258: p = scanHexPost(p + 2, n); jaroslav@1258: } else if (at(p, n, ':')) { jaroslav@1258: p = takeIPv4Address(p + 1, n, "IPv4 address"); jaroslav@1258: ipv6byteCount += 4; jaroslav@1258: } jaroslav@1258: } else if (at(p, n, "::")) { jaroslav@1258: compressedZeros = true; jaroslav@1258: p = scanHexPost(p + 2, n); jaroslav@1258: } jaroslav@1258: if (p < n) jaroslav@1258: fail("Malformed IPv6 address", start); jaroslav@1258: if (ipv6byteCount > 16) jaroslav@1258: fail("IPv6 address too long", start); jaroslav@1258: if (!compressedZeros && ipv6byteCount < 16) jaroslav@1258: fail("IPv6 address too short", start); jaroslav@1258: if (compressedZeros && ipv6byteCount == 16) jaroslav@1258: fail("Malformed IPv6 address", start); jaroslav@1258: jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: private int scanHexPost(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: jaroslav@1258: if (p == n) jaroslav@1258: return p; jaroslav@1258: jaroslav@1258: q = scanHexSeq(p, n); jaroslav@1258: if (q > p) { jaroslav@1258: p = q; jaroslav@1258: if (at(p, n, ':')) { jaroslav@1258: p++; jaroslav@1258: p = takeIPv4Address(p, n, "hex digits or IPv4 address"); jaroslav@1258: ipv6byteCount += 4; jaroslav@1258: } jaroslav@1258: } else { jaroslav@1258: p = takeIPv4Address(p, n, "hex digits or IPv4 address"); jaroslav@1258: ipv6byteCount += 4; jaroslav@1258: } jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: // Scan a hex sequence; return -1 if one could not be scanned jaroslav@1258: // jaroslav@1258: private int scanHexSeq(int start, int n) jaroslav@1258: throws URISyntaxException jaroslav@1258: { jaroslav@1258: int p = start; jaroslav@1258: int q; jaroslav@1258: jaroslav@1258: q = scan(p, n, L_HEX, H_HEX); jaroslav@1258: if (q <= p) jaroslav@1258: return -1; jaroslav@1258: if (at(q, n, '.')) // Beginning of IPv4 address jaroslav@1258: return -1; jaroslav@1258: if (q > p + 4) jaroslav@1258: fail("IPv6 hexadecimal digit sequence too long", p); jaroslav@1258: ipv6byteCount += 2; jaroslav@1258: p = q; jaroslav@1258: while (p < n) { jaroslav@1258: if (!at(p, n, ':')) jaroslav@1258: break; jaroslav@1258: if (at(p + 1, n, ':')) jaroslav@1258: break; // "::" jaroslav@1258: p++; jaroslav@1258: q = scan(p, n, L_HEX, H_HEX); jaroslav@1258: if (q <= p) jaroslav@1258: failExpecting("digits for an IPv6 address", p); jaroslav@1258: if (at(q, n, '.')) { // Beginning of IPv4 address jaroslav@1258: p--; jaroslav@1258: break; jaroslav@1258: } jaroslav@1258: if (q > p + 4) jaroslav@1258: fail("IPv6 hexadecimal digit sequence too long", p); jaroslav@1258: ipv6byteCount += 2; jaroslav@1258: p = q; jaroslav@1258: } jaroslav@1258: jaroslav@1258: return p; jaroslav@1258: } jaroslav@1258: jaroslav@1258: } jaroslav@1258: jaroslav@1258: }