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: *
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 jaroslav@1258: * news:comp.lang.java jaroslav@1258: * urn:isbn:096139210x
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: * jaroslav@1258: *
jaroslav@1258: * docs/guide/collections/designfaq.html#28
jaroslav@1258: * ../../../demo/jfc/SwingSet2/src/SwingSet2.java
jaroslav@1258: * file:///~/calendar 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: * 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: *jaroslav@1258: *
jaroslav@1258: * Component Type jaroslav@1258: * scheme String jaroslav@1258: * scheme-specific-part String jaroslav@1258: * authority String jaroslav@1258: * user-info String jaroslav@1258: * host String jaroslav@1258: * port int jaroslav@1258: * path String jaroslav@1258: * query String jaroslav@1258: * fragment String
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: *
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) andjaroslav@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: * u.resolve(u.relativize(v)).equals(v) .
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: *
jaroslav@1258: * jaroslav@1258: *jaroslav@1258: *
jaroslav@1258: * alpha jaroslav@1258: *The US-ASCII alphabetic characters, jaroslav@1258: * 'A' through 'Z' jaroslav@1258: * and 'a' through 'z' jaroslav@1258: * digit jaroslav@1258: *The US-ASCII decimal digit characters, jaroslav@1258: * '0' through '9' jaroslav@1258: * alphanum jaroslav@1258: *All alpha and digit characters jaroslav@1258: * unreserved jaroslav@1258: *All alphanum characters together with those in the string jaroslav@1258: * "_-!.~'()*" jaroslav@1258: * punct jaroslav@1258: *The characters in the string ",;:$&+=" jaroslav@1258: * reserved jaroslav@1258: *All punct characters together with those in the string jaroslav@1258: * "?/[]@" jaroslav@1258: * escaped jaroslav@1258: *Escaped 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') jaroslav@1258: * other jaroslav@1258: *The 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)
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: *
To encode non-US-ASCII characters when a URI is required to jaroslav@1258: * conform strictly to RFC 2396 by not containing any other jaroslav@1258: * characters.
To quote characters that are otherwise illegal in a jaroslav@1258: * component. The user-info, path, query, and fragment components differ jaroslav@1258: * slightly in terms of which characters are considered legal and illegal. jaroslav@1258: *
A character is encoded by replacing it jaroslav@1258: * with the sequence of escaped octets that represent that character in the jaroslav@1258: * UTF-8 character set. The Euro currency symbol ('\u20AC'), jaroslav@1258: * for example, is encoded as "%E2%82%AC". (Deviation from jaroslav@1258: * RFC 2396, which does not specify any particular character jaroslav@1258: * set.)
An illegal character is quoted simply by jaroslav@1258: * encoding it. The space character, for example, is quoted by replacing it jaroslav@1258: * with "%20". UTF-8 contains US-ASCII, hence for US-ASCII jaroslav@1258: * characters this transformation has exactly the effect required by jaroslav@1258: * RFC 2396.
jaroslav@1258: * A sequence of escaped octets is decoded by jaroslav@1258: * replacing it with the sequence of characters that it represents in the jaroslav@1258: * UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the jaroslav@1258: * effect of de-quoting any quoted US-ASCII characters as well as that of jaroslav@1258: * decoding any encoded non-US-ASCII characters. If a decoding error occurs jaroslav@1258: * when decoding the escaped octets then the erroneous octets are replaced by jaroslav@1258: * '\uFFFD', the Unicode replacement character.
The {@link #URI(java.lang.String) single-argument
jaroslav@1258: * constructor
} requires any illegal characters in its argument to be
jaroslav@1258: * quoted and preserves any escaped octets and other characters that
jaroslav@1258: * are present.
The {@link
jaroslav@1258: * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String)
jaroslav@1258: * multi-argument constructors
} quote illegal characters as
jaroslav@1258: * required by the components in which they appear. The percent character
jaroslav@1258: * ('%') is always quoted by these constructors. Any other
jaroslav@1258: * characters are preserved.
The {@link #getRawUserInfo() getRawUserInfo}, {@link #getRawPath() jaroslav@1258: * getRawPath}, {@link #getRawQuery() getRawQuery}, {@link #getRawFragment() jaroslav@1258: * getRawFragment}, {@link #getRawAuthority() getRawAuthority}, and {@link jaroslav@1258: * #getRawSchemeSpecificPart() getRawSchemeSpecificPart} methods return the jaroslav@1258: * values of their corresponding components in raw form, without interpreting jaroslav@1258: * any escaped octets. The strings returned by these methods may contain jaroslav@1258: * both escaped octets and other characters, and will not contain any jaroslav@1258: * illegal characters.
The {@link #getUserInfo() getUserInfo}, {@link #getPath() jaroslav@1258: * getPath}, {@link #getQuery() getQuery}, {@link #getFragment() jaroslav@1258: * getFragment}, {@link #getAuthority() getAuthority}, and {@link jaroslav@1258: * #getSchemeSpecificPart() getSchemeSpecificPart} methods decode any escaped jaroslav@1258: * octets in their corresponding components. The strings returned by these jaroslav@1258: * methods may contain both other characters and illegal characters, jaroslav@1258: * and will not contain any escaped octets.
The {@link #toString() toString} method returns a URI string with jaroslav@1258: * all necessary quotation but which may contain other characters. jaroslav@1258: *
The {@link #toASCIIString() toASCIIString} method returns a fully jaroslav@1258: * quoted and encoded URI string that does not contain any other jaroslav@1258: * characters.
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: * jaroslav@1258: * in all cases, jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * u.getSchemeSpecificPart(),
jaroslav@1258: * u.getFragment())
jaroslav@1258: * .equals(u) jaroslav@1258: *
jaroslav@1258: * new URI(u.getScheme(),jaroslav@1258: * jaroslav@1258: * if u is hierarchical, and jaroslav@1258: * jaroslav@1258: *
jaroslav@1258: * u.getUserInfo(), u.getAuthority(),
jaroslav@1258: * u.getPath(), u.getQuery(),
jaroslav@1258: * u.getFragment())
jaroslav@1258: * .equals(u) jaroslav@1258: *
jaroslav@1258: * new URI(u.getScheme(),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: *
jaroslav@1258: * u.getUserInfo(), u.getHost(), u.getPort(),
jaroslav@1258: * u.getPath(), u.getQuery(),
jaroslav@1258: * u.getFragment())
jaroslav@1258: * .equals(u) 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, 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: An empty authority component is permitted as long as it is
jaroslav@1258: * followed by a non-empty path, a query component, or a fragment
jaroslav@1258: * component. This allows the parsing of URIs such as
jaroslav@1258: * "file:///foo/bar", which seems to be the intent of
jaroslav@1258: * RFC 2396 although the grammar does not permit it. If the
jaroslav@1258: * authority component is empty then the user-information, host, and port
jaroslav@1258: * components are undefined. Empty relative paths are permitted; this seems to be the
jaroslav@1258: * intent of RFC 2396 although the grammar does not permit it. The
jaroslav@1258: * primary consequence of this deviation is that a standalone fragment
jaroslav@1258: * such as "#foo" parses as a relative URI with an empty path
jaroslav@1258: * and the given fragment, and can be usefully resolved against a base URI.
jaroslav@1258: *
jaroslav@1258: * IPv4 addresses in host components are parsed rigorously, as
jaroslav@1258: * specified by RFC 2732: Each
jaroslav@1258: * element of a dotted-quad address must contain no more than three
jaroslav@1258: * decimal digits. Each element is further constrained to have a value
jaroslav@1258: * no greater than 255. Hostnames in host components that comprise only a single
jaroslav@1258: * domain label are permitted to start with an alphanum
jaroslav@1258: * character. This seems to be the intent of RFC 2396
jaroslav@1258: * section 3.2.2 although the grammar does not permit it. The
jaroslav@1258: * consequence of this deviation is that the authority component of a
jaroslav@1258: * hierarchical URI such as s://123, will parse as a server-based
jaroslav@1258: * authority. IPv6 addresses are permitted for the host component. An IPv6
jaroslav@1258: * address must be enclosed in square brackets ('[' and
jaroslav@1258: * ']') as specified by RFC 2732. The
jaroslav@1258: * IPv6 address itself must parse according to RFC 2373. IPv6
jaroslav@1258: * addresses are further constrained to describe no more than sixteen
jaroslav@1258: * bytes of address information, a constraint implicit in RFC 2373
jaroslav@1258: * but not expressible in the grammar. Characters in the other category are permitted wherever
jaroslav@1258: * RFC 2396 permits escaped octets, that is, in the
jaroslav@1258: * user-information, path, query, and fragment components, as well as in
jaroslav@1258: * the authority component if the authority is registry-based. This
jaroslav@1258: * allows URIs to contain Unicode characters beyond those in the US-ASCII
jaroslav@1258: * character set. 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: Initially, the result string is empty. If a scheme is given then it is appended to the result,
jaroslav@1258: * followed by a colon character (':'). If user information, a host, or a port are given then the
jaroslav@1258: * string "//" is appended. 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. 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: * If a port number is given then a colon character
jaroslav@1258: * (':') is appended, followed by the port number in decimal.
jaroslav@1258: * 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. 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: * 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. 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. 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: Initially, the result string is empty. If a scheme is given then it is appended to the result,
jaroslav@1258: * followed by a colon character (':'). 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. 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. 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: * 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. 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. 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: * 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: Initially, the result string is empty. If a scheme is given then it is appended to the result,
jaroslav@1258: * followed by a colon character (':'). 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. 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. 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. 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. 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: * 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. 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: * All "." segments are removed. 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. 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) 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. 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: A new URI is constructed with this URI's scheme and the given
jaroslav@1258: * URI's query and fragment components. If the given URI has an authority component then the new URI's
jaroslav@1258: * authority and path are taken from the given URI. Otherwise the new URI's authority component is copied from
jaroslav@1258: * this URI, and its path is computed as follows: If the given URI's path is absolute then the new URI's path
jaroslav@1258: * is taken from the given URI. 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. The result of this method is absolute if, and only if, either this
jaroslav@1258: * URI is absolute or the given URI is absolute. 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)). The relativization of the given URI against this URI is computed as
jaroslav@1258: * follows: 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. 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. 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. 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. 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. The scheme-specific part of a URI only contains legal URI
jaroslav@1258: * characters. 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. 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. 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. The user-information component of a URI, if defined, only contains
jaroslav@1258: * characters in the unreserved, punct, escaped, and
jaroslav@1258: * other categories. 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. The host component of a URI, if defined, will have one of the
jaroslav@1258: * following forms: A domain name consisting of one or more labels
jaroslav@1258: * separated by period characters ('.'), optionally followed by
jaroslav@1258: * a period character. Each label consists of alphanum characters
jaroslav@1258: * as well as hyphen characters ('-'), though hyphens never
jaroslav@1258: * occur as the first or last characters in a label. The rightmost
jaroslav@1258: * label of a domain name consisting of two or more labels, begins
jaroslav@1258: * with an alpha character. A dotted-quad IPv4 address of the form
jaroslav@1258: * digit+.digit+.digit+.digit+,
jaroslav@1258: * where no digit sequence is longer than three characters and no
jaroslav@1258: * sequence has a value larger than 255. An IPv6 address enclosed in square brackets ('[' and
jaroslav@1258: * ']') and consisting of hexadecimal digits, colon characters
jaroslav@1258: * (':'), and possibly an embedded IPv4 address. The full
jaroslav@1258: * syntax of IPv6 addresses is specified in RFC 2373: IPv6
jaroslav@1258: * Addressing Architecture. The port component of a URI, if defined, is a non-negative
jaroslav@1258: * integer. 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. 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. The query component of a URI, if defined, only contains legal URI
jaroslav@1258: * characters. 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. The fragment component of a URI, if defined, only contains legal URI
jaroslav@1258: * characters. 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. 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. 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: Two URIs with different schemes are ordered according the
jaroslav@1258: * ordering of their schemes, without regard to case. A hierarchical URI is considered to be less than an opaque URI
jaroslav@1258: * with an identical scheme. Two opaque URIs with identical schemes are ordered according
jaroslav@1258: * to the ordering of their scheme-specific parts. Two opaque URIs with identical schemes and scheme-specific
jaroslav@1258: * parts are ordered according to the ordering of their
jaroslav@1258: * fragments. Two hierarchical URIs with identical schemes are ordered
jaroslav@1258: * according to the ordering of their authority components: If both authority components are server-based then the URIs
jaroslav@1258: * are ordered according to their user-information components; if these
jaroslav@1258: * components are identical then the URIs are ordered according to the
jaroslav@1258: * ordering of their hosts, without regard to case; if the hosts are
jaroslav@1258: * identical then the URIs are ordered according to the ordering of
jaroslav@1258: * their ports. If one or both authority components are registry-based then
jaroslav@1258: * the URIs are ordered according to the ordering of their authority
jaroslav@1258: * components. Finally, two hierarchical URIs with identical schemes and
jaroslav@1258: * authority components are ordered according to the ordering of their
jaroslav@1258: * paths; if their paths are identical then they are ordered according to
jaroslav@1258: * the ordering of their queries; if the queries are identical then they
jaroslav@1258: * are ordered according to the order of their fragments. This method satisfies the general contract of the {@link
jaroslav@1258: * java.lang.Comparable#compareTo(Object) Comparable.compareTo}
jaroslav@1258: * method. 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. 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. 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. 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: // [
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
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: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
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: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: * URI u = new URI(str).parseServerAuthority();
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: * @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: *
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: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *
jaroslav@1258: *