Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly... Example: URL: http://search.barnesandnoble.com/booksearch/first book.pdf java.net.URLEncoder.encode(url.toString(), "ISO-8859-1"); returns me: http%3A%2F%2Fsearch.barnesandnoble.com...
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input: http://google.com/resource?key=value1 & value2 I expect the output: http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2 Neither java.net.URLEncoder nor java.net.URI will generate the right outp...
I have a HTTP GET request that I am attempting to send. I tried adding the parameters to this request by first creating a BasicHttpParams object and adding the parameters to that object, then calling setParams( basicHttpParms ) on my HttpGet object. This method fails. But if I manually add my parameters to my URL (i.e. append ?param1=value1&param2=value2) it succeeds. I know I'm missing so...
I need to generate a href to a URI. All easy with the exception when it comes to reserved characters which need percent-encoding, e.g. link to /some/path;element should appear as <a href="/some/path%3Belement"> (I know that path;element represents a single entity). Initially I was looking for a Java library that does this but I ended up writing something myself (look below for what fail...
Thanks for any help. I am trying to get a FileInputStream object on an image that the user selects from the picture gallery. This is the android URI returned by android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI content://media/external/images/media/3 When I try to construct a java URI object from this object, I get an IllegalArgumentException with the exception description Expect...
I have a very simple regex question. Suppose I have 2 conditions: url =http://www.abc.com/cde/def url =https://www.abc.com/sadfl/dsaf How can I extract the baseUrl using regex? Sample output: http://www.abc.com https://www.abc.com
Here's an example of a utility method: public static Long getFileSize(String fileString) { File file = new File(fileString); if (file == null || !file.isFile()) return null; return file.length(); } Is it a good practise to pass a String rather than a File to a method like this? In general what reasoning should be applied when making utility methods of this style?
Does anyone know of a good Scala or Java library that can fix common problems in malformed URIs, such as containing characters that should be escaped but aren't?
The equals()-method of the URL-class in the Java-class-library makes a DNS-request to get the IP for the hostname, to check the two IP's for equality. This happens even for URL's, that are created from the same String. Is there a way to avoid this internet-access?
While trying to zip an archive using the java.util.zip I ran into a lot of problems most of which I solved. Now that I finally get some output I struggle with getting the "right" output. I have an extracted ODT file (directory would be more fitting a description) to which I did some modifications. Now I want to compress that directory as to recreate the ODT file structure. Zipping the directory...
How can I encode dynamic String values in order to create URL instances. I need to replace spaces with %20, accents, non ascii caracters... ? I tried to use URLEncoder but it also encodes '/' caracter and if I give a string encoded with URLEncoder to the URL constructeur I get a MaformedURLException (no protocol).
URL normalization (or URL canonicalization) is the process by which URLs are modified and standardized in a consistent manner. The goal of the normalization process is to transform a URL into a normalized or canonical URL so it is possible to determine if two syntactically different URLs are equivalent. Strategies include adding trailing slashes, https => http, etc. The Wikipedia page lis...
I have to initialize file objects inside the constructor and for handling the exception, is it efficient using throws or should I go for try/catch?
I'd like to encourage our users of our RCP application to send the problem details to our support department. To this end, I've added a "Contact support" widget to our standard error dialogue. I've managed to use URI headers to send a stacktrace using Java 6's JDIC call: Desktop.getDesktop().mail(java.net.URI). This will fire up the user's mail client, ready for them to add their comments, and...
Are all primitive wrapper classes in Java immutable objects? String is immutable. What are the other immutable objects?
I used InetAddress to parse IP addresses, but now there is a need to store hostname if IP is unavailable. So I introduced a class Host. case class Host(name:String, ip:InetAddress) { import Host.{addressToBytes, compareSeqs} override def toString:String = if (ip!=null) {ip.getHostName} else {name} } object Host { implicit def stringToPattern(s:String): Pattern = Pattern.compile(s)...
Here's a simple problem - given two urls, is there some built-in method, or an Apache library that decides whether they are (logically) equal? For example, these two urls are equal: http://stackoverflow.com http://stackoverflow.com/
When I execute the following java program, sometimes I get an empty response, sometimes I get the real (redirected) content. ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL( "http://stackoverflow.com/questions/84629" ); IOUtils.copy( url.openStream(), output ); System.out.println( output.toString() ); The URL http://stackoverflow.com/questions/84629 is a redirec...
A quick Google didn't turn up a definitive answer. If URI does do this, is there a widespread third-party library that won't do this? I just need some parsing, and I can't have unpredictable delays while the constructor attempts to resolve a URI? Thanks.
I need to decode a URI that contains a query string; expected input/output behavior is something like the following: abstract class URIParser { /** example input: * something?alias=pos&FirstName=Foo+A%26B%3DC&LastName=Bar */ URIParser(String input) { ... } /** should return "something" for the example input */ public String getPath(); /** should retur...
I work with different servers and configurations. What is the best java code approach for getting the scheme://host:[port if it is not port 80]. Here is some code I have used, but don't know if this is the best approach. (this is pseudo code) HttpServletRequest == request String serverName = request.getServerName().toLowerCase(); String scheme = request.getScheme(); int port = request.getSe...
   /*
    * Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.net;
  
  
  import java.lang.Character;             // for javadoc
  import java.lang.NullPointerException;  // for javadoc
  

Represents a Uniform Resource Identifier (URI) reference.

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

URI syntax and components

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

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

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

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

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

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

A hierarchical URI is subject to further parsing according to the syntax

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

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

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

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

All told, then, a URI instance has the following nine components:

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

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

Operations on URI instances

The key operations supported by this class are those of normalization, resolution, and relativization.

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

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

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

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

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

Character categories

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

The set of all legal URI characters consists of the unreserved, reserved, escaped, and other characters.

Escaped octets, quotation, encoding, and decoding

RFC 2396 allows escaped octets to appear in the user-info, path, query, and fragment components. Escaping serves two purposes in URIs:
  • To encode non-US-ASCII characters when a URI is required to conform strictly to RFC 2396 by not containing any other characters.

  • To quote characters that are otherwise illegal in a component. The user-info, path, query, and fragment components differ slightly in terms of which characters are considered legal and illegal.

These purposes are served in this class by three related operations:
  • A character is encoded by replacing it with the sequence of escaped octets that represent that character in the UTF-8 character set. The Euro currency symbol ('\u20AC'), for example, is encoded as "%E2%82%AC". (Deviation from RFC 2396, which does not specify any particular character set.)

  • An illegal character is quoted simply by encoding it. The space character, for example, is quoted by replacing it with "%20". UTF-8 contains US-ASCII, hence for US-ASCII characters this transformation has exactly the effect required by RFC 2396.

  • A sequence of escaped octets is decoded by replacing it with the sequence of characters that it represents in the UTF-8 character set. UTF-8 contains US-ASCII, hence decoding has the effect of de-quoting any quoted US-ASCII characters as well as that of decoding any encoded non-US-ASCII characters. If a decoding error occurs when decoding the escaped octets then the erroneous octets are replaced by '\uFFFD', the Unicode replacement character.

These operations are exposed in the constructors and methods of this class as follows:
  • The single-argument constructor requires any illegal characters in its argument to be quoted and preserves any escaped octets and other characters that are present.

  • The URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

  • The getRawUserInfo, getRawPath, getRawQuery, getRawFragment, getRawAuthority, and getRawSchemeSpecificPart() methods return the values of their corresponding components in raw form, without interpreting any escaped octets. The strings returned by these methods may contain both escaped octets and other characters, and will not contain any illegal characters.

  • The getUserInfo, getPath, getQuery, getFragment, getAuthority, and getSchemeSpecificPart() methods decode any escaped octets in their corresponding components. The strings returned by these methods may contain both other characters and illegal characters, and will not contain any escaped octets.

  • The toString method returns a URI string with all necessary quotation but which may contain other characters.

  • The toASCIIString method returns a fully quoted and encoded URI string that does not contain any other characters.

Identities

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

URIs, URLs, and URNs

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

The conceptual distinction between URIs and URLs is reflected in the differences between this class and the URL class.

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

An instance of the URL class, by contrast, represents the syntactic components of a URL together with some of the information required to access the resource that it describes. A URL must be absolute, that is, it must always specify a scheme. A URL string is parsed according to its scheme. A stream handler is always established for a URL, and in fact it is impossible to create a URL instance for a scheme for which no handler is available. Equality and hashing depend upon both the scheme and the Internet address of the host, if any; comparison is not defined. In other words, a URL is a structured string that supports the syntactic operation of resolution as well as the network I/O operations of looking up the host and opening a connection to the specified resource.

Author(s):
Mark Reinhold
Since:
1.4
See also:
RFC 2279: UTF-8, a transformation format of ISO 10646,
RFC 2373: IPv6 Addressing Architecture,
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,
RFC 2732: Format for Literal IPv6 Addresses in URLs,
URISyntaxException
 
 
 public final class URI
     implements Comparable<URI>, Serializable
 {
 
     // Note: Comments containing the word "ASSERT" indicate places where a
     // throw of an InternalError should be replaced by an appropriate assertion
     // statement once asserts are enabled in the build.
 
     static final long serialVersionUID = -6052424284110960213L;
 
 
     // -- Properties and components of this instance --
 
     // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
     private transient String scheme;            // null ==> relative URI
     private transient String fragment;
 
     // Hierarchical URI components: [//<authority>]<path>[?<query>]
     private transient String authority;         // Registry or server
 
     // Server-based authority: [<userInfo>@]<host>[:<port>]
     private transient String userInfo;
     private transient String host;              // null ==> registry-based
     private transient int port = -1;            // -1 ==> undefined
 
     // Remaining components of hierarchical URIs
     private transient String path;              // null ==> opaque
     private transient String query;
 
     // The remaining fields may be computed on demand
 
     private volatile transient String schemeSpecificPart;
     private volatile transient int hash;        // Zero ==> undefined
 
     private volatile transient String decodedUserInfo = null;
     private volatile transient String decodedAuthority = null;
     private volatile transient String decodedPath = null;
     private volatile transient String decodedQuery = null;
     private volatile transient String decodedFragment = null;
     private volatile transient String decodedSchemeSpecificPart = null;

    
The string form of this URI.

Serial:
 
     private volatile String string;             // The only serializable field
 
 
 
     // -- Constructors and factories --
 
     private URI() { }                           // Used internally
 
    
Constructs a URI by parsing the given string.

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

  • An empty authority component is permitted as long as it is followed by a non-empty path, a query component, or a fragment component. This allows the parsing of URIs such as "file:///foo/bar", which seems to be the intent of RFC 2396 although the grammar does not permit it. If the authority component is empty then the user-information, host, and port components are undefined.

  • Empty relative paths are permitted; this seems to be the intent of RFC 2396 although the grammar does not permit it. The primary consequence of this deviation is that a standalone fragment such as "#foo" parses as a relative URI with an empty path and the given fragment, and can be usefully resolved against a base URI.

  • IPv4 addresses in host components are parsed rigorously, as specified by RFC 2732: Each element of a dotted-quad address must contain no more than three decimal digits. Each element is further constrained to have a value no greater than 255.

  • Hostnames in host components that comprise only a single domain label are permitted to start with an alphanum character. This seems to be the intent of RFC 2396 section 3.2.2 although the grammar does not permit it. The consequence of this deviation is that the authority component of a hierarchical URI such as s://123, will parse as a server-based authority.

  • IPv6 addresses are permitted for the host component. An IPv6 address must be enclosed in square brackets ('[' and ']') as specified by RFC 2732. The IPv6 address itself must parse according to RFC 2373. IPv6 addresses are further constrained to describe no more than sixteen bytes of address information, a constraint implicit in RFC 2373 but not expressible in the grammar.

  • Characters in the other category are permitted wherever RFC 2396 permits escaped octets, that is, in the user-information, path, query, and fragment components, as well as in the authority component if the authority is registry-based. This allows URIs to contain Unicode characters beyond those in the US-ASCII character set.

Parameters:
str The string to be parsed into a URI
Throws:
java.lang.NullPointerException If str is null
URISyntaxException If the given string violates RFC 2396, as augmented by the above deviations
 
     public URI(String strthrows URISyntaxException {
         new Parser(str).parse(false);
     }

    
Constructs a hierarchical URI from the given components.

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

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

  1. Initially, the result string is empty.

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

  3. If user information, a host, or a port are given then the string "//" is appended.

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

  5. If a host is given then it is appended. If the host is a literal IPv6 address but is not enclosed in square brackets ('[' and ']') then the square brackets are added.

  6. If a port number is given then a colon character (':') is appended, followed by the port number in decimal.

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

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

  9. Finally, if a fragment is given then a hash character ('#') is appended, followed by the fragment. Any character that is not a legal URI character is quoted.

The resulting URI string is then parsed as if by invoking the URI(java.lang.String) constructor and then invoking the parseServerAuthority() method upon the result; this may cause a URISyntaxException to be thrown.

Parameters:
scheme Scheme name
userInfo User name and authorization information
host Host name
port Port number
path Path
query Query
fragment Fragment
Throws:
URISyntaxException If both a scheme and a path are given but the path is relative, if the URI string constructed from the given components violates RFC 2396, or if the authority component of the string is present but cannot be parsed as a server-based authority
 
     public URI(String scheme,
                String userInfoString hostint port,
                String pathString queryString fragment)
         throws URISyntaxException
     {
         String s = toString(schemenull,
                             nulluserInfohostport,
                             pathqueryfragment);
         checkPath(sschemepath);
         new Parser(s).parse(true);
     }

    
Constructs a hierarchical URI from the given components.

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

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

  1. Initially, the result string is empty.

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

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

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

  5. If a query is given then a question-mark character ('?') is appended, followed by the query. Any character that is not a legal URI character is quoted.

  6. Finally, if a fragment is given then a hash character ('#') is appended, followed by the fragment. Any character that is not a legal URI character is quoted.

The resulting URI string is then parsed as if by invoking the URI(java.lang.String) constructor and then invoking the parseServerAuthority() method upon the result; this may cause a URISyntaxException to be thrown.

Parameters:
scheme Scheme name
authority Authority
path Path
query Query
fragment Fragment
Throws:
URISyntaxException If both a scheme and a path are given but the path is relative, if the URI string constructed from the given components violates RFC 2396, or if the authority component of the string is present but cannot be parsed as a server-based authority
 
     public URI(String scheme,
                String authority,
                String pathString queryString fragment)
         throws URISyntaxException
     {
         String s = toString(schemenull,
                             authoritynullnull, -1,
                             pathqueryfragment);
         checkPath(sschemepath);
         new Parser(s).parse(false);
     }

    
Constructs a hierarchical URI from the given components.

A component may be left undefined by passing null.

This convenience constructor works as if by invoking the seven-argument constructor as follows:

new  URI(scheme, null, host, -1, path, null, fragment);

Parameters:
scheme Scheme name
host Host name
path Path
fragment Fragment
Throws:
URISyntaxException If the URI string constructed from the given components violates RFC 2396
 
     public URI(String schemeString hostString pathString fragment)
         throws URISyntaxException
     {
         this(schemenullhost, -1, pathnullfragment);
     }

    
Constructs a URI from the given components.

A component may be left undefined by passing null.

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

  1. Initially, the result string is empty.

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

  3. If a scheme-specific part is given then it is appended. Any character that is not a legal URI character is quoted.

  4. Finally, if a fragment is given then a hash character ('#') is appended to the string, followed by the fragment. Any character that is not a legal URI character is quoted.

The resulting URI string is then parsed in order to create the new URI instance as if by invoking the URI(java.lang.String) constructor; this may cause a URISyntaxException to be thrown.

Parameters:
scheme Scheme name
ssp Scheme-specific part
fragment Fragment
Throws:
URISyntaxException If the URI string constructed from the given components violates RFC 2396
 
     public URI(String schemeString sspString fragment)
         throws URISyntaxException
     {
         new Parser(toString(schemessp,
                             nullnullnull, -1,
                             nullnullfragment))
             .parse(false);
     }

    
Creates a URI by parsing the given string.

This convenience factory method works as if by invoking the URI(java.lang.String) constructor; any URISyntaxException thrown by the constructor is caught and wrapped in a new java.lang.IllegalArgumentException object, which is then thrown.

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

Parameters:
str The string to be parsed into a URI
Returns:
The new URI
Throws:
java.lang.NullPointerException If str is null
java.lang.IllegalArgumentException If the given string violates RFC 2396
 
     public static URI create(String str) {
         try {
             return new URI(str);
         } catch (URISyntaxException x) {
             IllegalArgumentException y = new IllegalArgumentException();
             y.initCause(x);
             throw y;
         }
     }
 
 
     // -- Operations --
 
    
Attempts to parse this URI's authority component, if defined, into user-information, host, and port components.

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

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

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

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

URI u = new URI(str).parseServerAuthority();

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

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

    
Normalizes this URI's path.

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

  1. All "." segments are removed.

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

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

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

Returns:
A URI equivalent to this URI, but whose path is in normal form
 
     public URI normalize() {
         return normalize(this);
     }

    
Resolves the given URI against this URI.

If the given URI is already absolute, or if this URI is opaque, then the given URI is returned.

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

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

  1. A new URI is constructed with this URI's scheme and the given URI's query and fragment components.

  2. If the given URI has an authority component then the new URI's authority and path are taken from the given URI.

  3. Otherwise the new URI's authority component is copied from this URI, and its path is computed as follows:

    1. If the given URI's path is absolute then the new URI's path is taken from the given URI.

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

The result of this method is absolute if, and only if, either this URI is absolute or the given URI is absolute.

Parameters:
uri The URI to be resolved against this URI
Returns:
The resulting URI
Throws:
java.lang.NullPointerException If uri is null
    public URI resolve(URI uri) {
        return resolve(thisuri);
    }

    
Constructs a new URI by parsing the given string and then resolving it against this URI.

This convenience method works as if invoking it were equivalent to evaluating the expression resolve(URI.create(str)).

Parameters:
str The string to be parsed into a URI
Returns:
The resulting URI
Throws:
java.lang.NullPointerException If str is null
java.lang.IllegalArgumentException If the given string violates RFC 2396
    public URI resolve(String str) {
        return resolve(URI.create(str));
    }

    
Relativizes the given URI against this URI.

The relativization of the given URI against this URI is computed as follows:

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

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

Parameters:
uri The URI to be relativized against this URI
Returns:
The resulting URI
Throws:
java.lang.NullPointerException If uri is null
    public URI relativize(URI uri) {
        return relativize(thisuri);
    }

    
Constructs a URL from this URI.

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

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

    
Returns the scheme component of this URI.

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

The scheme component of a URI cannot contain escaped octets, hence this method does not perform any decoding.

Returns:
The scheme component of this URI, or null if the scheme is undefined
    public String getScheme() {
        return ;
    }

    
Tells whether or not this URI is absolute.

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

Returns:
true if, and only if, this URI is absolute
    public boolean isAbsolute() {
        return  != null;
    }

    
Tells whether or not this URI is opaque.

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

Returns:
true if, and only if, this URI is opaque
    public boolean isOpaque() {
        return  == null;
    }

    
Returns the raw scheme-specific part of this URI. The scheme-specific part is never undefined, though it may be empty.

The scheme-specific part of a URI only contains legal URI characters.

Returns:
The raw scheme-specific part of this URI (never null)
    public String getRawSchemeSpecificPart() {
        defineSchemeSpecificPart();
        return ;
    }

    
Returns the decoded scheme-specific part of this URI.

The string returned by this method is equal to that returned by the getRawSchemeSpecificPart method except that all sequences of escaped octets are decoded.

Returns:
The decoded scheme-specific part of this URI (never null)
    public String getSchemeSpecificPart() {
        if ( == null)
        return ;
    }

    
Returns the raw authority component of this URI.

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

Returns:
The raw authority component of this URI, or null if the authority is undefined
    public String getRawAuthority() {
        return ;
    }

    
Returns the decoded authority component of this URI.

The string returned by this method is equal to that returned by the getRawAuthority method except that all sequences of escaped octets are decoded.

Returns:
The decoded authority component of this URI, or null if the authority is undefined
    public String getAuthority() {
        if ( == null)
             = decode();
        return ;
    }

    
Returns the raw user-information component of this URI.

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

Returns:
The raw user-information component of this URI, or null if the user information is undefined
    public String getRawUserInfo() {
        return ;
    }

    
Returns the decoded user-information component of this URI.

The string returned by this method is equal to that returned by the getRawUserInfo method except that all sequences of escaped octets are decoded.

Returns:
The decoded user-information component of this URI, or null if the user information is undefined
    public String getUserInfo() {
        if (( == null) && ( != null))
             = decode();
        return ;
    }

    
Returns the host component of this URI.

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

  • A domain name consisting of one or more labels separated by period characters ('.'), optionally followed by a period character. Each label consists of alphanum characters as well as hyphen characters ('-'), though hyphens never occur as the first or last characters in a label. The rightmost label of a domain name consisting of two or more labels, begins with an alpha character.

  • A dotted-quad IPv4 address of the form digit+.digit+.digit+.digit+, where no digit sequence is longer than three characters and no sequence has a value larger than 255.

  • An IPv6 address enclosed in square brackets ('[' and ']') and consisting of hexadecimal digits, colon characters (':'), and possibly an embedded IPv4 address. The full syntax of IPv6 addresses is specified in RFC 2373: IPv6 Addressing Architecture.

The host component of a URI cannot contain escaped octets, hence this method does not perform any decoding.

Returns:
The host component of this URI, or null if the host is undefined
    public String getHost() {
        return ;
    }

    
Returns the port number of this URI.

The port component of a URI, if defined, is a non-negative integer.

Returns:
The port component of this URI, or -1 if the port is undefined
    public int getPort() {
        return ;
    }

    
Returns the raw path component of this URI.

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

Returns:
The path component of this URI, or null if the path is undefined
    public String getRawPath() {
        return ;
    }

    
Returns the decoded path component of this URI.

The string returned by this method is equal to that returned by the getRawPath method except that all sequences of escaped octets are decoded.

Returns:
The decoded path component of this URI, or null if the path is undefined
    public String getPath() {
        if (( == null) && ( != null))
             = decode();
        return ;
    }

    
Returns the raw query component of this URI.

The query component of a URI, if defined, only contains legal URI characters.

Returns:
The raw query component of this URI, or null if the query is undefined
    public String getRawQuery() {
        return ;
    }

    
Returns the decoded query component of this URI.

The string returned by this method is equal to that returned by the getRawQuery method except that all sequences of escaped octets are decoded.

Returns:
The decoded query component of this URI, or null if the query is undefined
    public String getQuery() {
        if (( == null) && ( != null))
             = decode();
        return ;
    }

    
Returns the raw fragment component of this URI.

The fragment component of a URI, if defined, only contains legal URI characters.

Returns:
The raw fragment component of this URI, or null if the fragment is undefined
    public String getRawFragment() {
        return ;
    }

    
Returns the decoded fragment component of this URI.

The string returned by this method is equal to that returned by the getRawFragment method except that all sequences of escaped octets are decoded.

Returns:
The decoded fragment component of this URI, or null if the fragment is undefined
    public String getFragment() {
        if (( == null) && ( != null))
             = decode();
        return ;
    }
    // -- Equality, comparison, hash code, toString, and serialization --

    
Tests this URI for equality with another object.

If the given object is not a URI then this method immediately returns false.

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

For two opaque URIs to be considered equal, their scheme-specific parts must be equal.

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

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

This method satisfies the general contract of the java.lang.Object.equals(java.lang.Object) method.

Parameters:
ob The object to which this object is to be compared
Returns:
true if, and only if, the given object is a URI that is identical to this URI
    public boolean equals(Object ob) {
        if (ob == this)
            return true;
        if (!(ob instanceof URI))
            return false;
        URI that = (URI)ob;
        if (this.isOpaque() != that.isOpaque()) return false;
        if (!equalIgnoringCase(this.that.scheme)) return false;
        if (!equal(this.that.fragment)) return false;
        // Opaque
        if (this.isOpaque())
            return equal(this.that.schemeSpecificPart);
        // Hierarchical
        if (!equal(this.that.path)) return false;
        if (!equal(this.that.query)) return false;
        // Authorities
        if (this. == that.authorityreturn true;
        if (this. != null) {
            // Server-based
            if (!equal(this.that.userInfo)) return false;
            if (!equalIgnoringCase(this.that.host)) return false;
            if (this. != that.portreturn false;
        } else if (this. != null) {
            // Registry-based
            if (!equal(this.that.authority)) return false;
        } else if (this. != that.authority) {
            return false;
        }
        return true;
    }

    
Returns a hash-code value for this URI. The hash code is based upon all of the URI's components, and satisfies the general contract of the Object.hashCode method.

Returns:
A hash-code value for this URI
    public int hashCode() {
        if ( != 0)
            return ;
        int h = hashIgnoringCase(0, );
        h = hash(h);
        if (isOpaque()) {
            h = hash(h);
        } else {
            h = hash(h);
            h = hash(h);
            if ( != null) {
                h = hash(h);
                h = hashIgnoringCase(h);
                h += 1949 * ;
            } else {
                h = hash(h);
            }
        }
         = h;
        return h;
    }

    
Compares this URI to another object, which must be a URI.

When comparing corresponding components of two URIs, if one component is undefined but the other is defined then the first is considered to be less than the second. Unless otherwise noted, string components are ordered according to their natural, case-sensitive ordering as defined by the String.compareTo method. String components that are subject to encoding are compared by comparing their raw forms rather than their encoded forms.

The ordering of URIs is defined as follows:

  • Two URIs with different schemes are ordered according the ordering of their schemes, without regard to case.

  • A hierarchical URI is considered to be less than an opaque URI with an identical scheme.

  • Two opaque URIs with identical schemes are ordered according to the ordering of their scheme-specific parts.

  • Two opaque URIs with identical schemes and scheme-specific parts are ordered according to the ordering of their fragments.

  • Two hierarchical URIs with identical schemes are ordered according to the ordering of their authority components:

    • If both authority components are server-based then the URIs are ordered according to their user-information components; if these components are identical then the URIs are ordered according to the ordering of their hosts, without regard to case; if the hosts are identical then the URIs are ordered according to the ordering of their ports.

    • If one or both authority components are registry-based then the URIs are ordered according to the ordering of their authority components.

  • Finally, two hierarchical URIs with identical schemes and authority components are ordered according to the ordering of their paths; if their paths are identical then they are ordered according to the ordering of their queries; if the queries are identical then they are ordered according to the order of their fragments.

This method satisfies the general contract of the java.lang.Comparable.compareTo(java.lang.Object) method.

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

    
Returns the content of this URI as a string.

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

Returns:
The string form of this URI
    public String toString() {
        defineString();
        return ;
    }

    
Returns the content of this URI as a US-ASCII string.

If this URI does not contain any characters in the other category then an invocation of this method will return the same value as an invocation of the toString method. Otherwise this method works as if by invoking that method and then encoding the result.

Returns:
The string form of this URI, encoded as needed so that it only contains characters in the US-ASCII charset
    public String toASCIIString() {
        defineString();
        return encode();
    }
    // -- Serialization support --

    
Saves the content of this URI to the given serial stream.

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

Parameters:
os The object-output stream to which this object is to be written
    private void writeObject(ObjectOutputStream os)
        throws IOException
    {
        defineString();
        os.defaultWriteObject();        // Writes the string field only
    }

    
Reconstitutes a URI from the given serial stream.

The java.io.ObjectInputStream.defaultReadObject() method is invoked to read the value of the string field. The result is then parsed in the usual way.

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