Top Description Fields Constructors Methods
org.eclipse.jetty.util

public final Class URIUtil

extends Object
Class Inheritance
Imports
java.io.File, .IOException, java.net.URI, .URL, .URLClassLoader, java.nio.charset.StandardCharsets, java.nio.file.Files, .Path, .Paths, java.util.ArrayList, .Arrays, .Comparator, .List, .Objects, .StringTokenizer, java.util.function.Supplier, java.util.stream.Stream, org.eclipse.jetty.util.resource.ResourceFactory, org.slf4j.Logger, .LoggerFactory

URI Utility methods.

This class assists with the decoding and encoding or HTTP URI's. It differs from the java.net.URL class as it does not provide communications ability, but it does assist with query string formatting.

See Also
UrlEncoded

Field Summary

Modifier and TypeField and Description
private static final boolean[]
private static final Logger
private static final String
private static final boolean[]
private static final String
private static final String
private static final boolean[]
URI_SUPPORTED_CHARACTERS

The characters that are supported by the URI class and that can be decoded by canonicalPath(String)

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static String

Returns:

Legally combined path segments.
addEncodedPaths
(String
URI path segment (should be encoded)
p1
,
String
URI path segment (should be encoded)
p2
)

Add two encoded URI path segments.

public static URI

Returns:

URI with path added.
addPath
(URI
A URI to add the path to
uri
,
String
A safe path element
path
)

Add a sub path to an existing URI.

public static String

Returns:

The path with any non-blank query added after a '?' or '&' as appropriate.
addPathQuery
(String
The path which may already contain a query
path
,
String
The query string to add (if blank, no query is added)
query
)

Add a path and a query string

public static String

Returns:

Legally combined path segments.
addPaths
(String
URI path segment (should be decoded)
p1
,
String
URI path segment (should be decoded)
p2
)

Add two Decoded URI path segments.

public static String

Returns:

the combination of the two query strings.
addQueries
(String
the first query string.
query1
,
String
the second query string.
query2
)

Combine two query strings into one.

private static void
appendHexValue(Utf8StringBuilder builder, byte value)

public static void
appendSchemeHostPort(StringBuilder
StringBuilder to append to
url
,
String
the URI scheme
scheme
,
String
the URI server
server
,
int
the URI port
port
)

Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports

public static void
appendSchemeHostPort(StringBuffer
StringBuffer to append to
url
,
String
the URI scheme
scheme
,
String
the URI server
server
,
int
the URI port
port
)

Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports

public static String

Returns:

the canonical path or null if it is non-normal
canonicalPath
(String
An encoded URI path
encodedPath
)

Canonicalize a URI path to a form that is unambiguous and safe to use with the JVM URI class.

public static <X extends Throwable> String

Returns:

the canonical path or null if it is non-normal
canonicalPath
(String
An encoded URI path
encodedPath
,
Supplier<X>
A supplier of exceptions if bad UTF8 is encountered, or null for no exception thrown.
onBadUtf8
)

Canonicalize a URI path to a form that is unambiguous and safe to use with the JVM URI class.

public static String

Returns:

the compacted path
compactPath
(String
the path to compact
path
)

Convert a path to a compact form.

public static URI

Returns:

the new URI with the file:/ substring corrected, or the original URI.
correctFileURI
(URI
the URI to (possibly) correct
uri
)

Corrects any bad file based URIs (even within a jar:file: based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably: java.io.File creates with it's File#toURL() and File#toURI(), along with the side effects of using URL#toURI())

This correction is limited to only the file:/ substring in the URI.

public static String
decodePath(String
The URI path to decode
path
)

Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.

public static String
decodePath(String
A String holding the URI path to decode
path
,
int
The start of the URI within the path string
offset
,
int
The length of the URI within the path string
length
)

Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.

public static String

Returns:

output with specified characters decoded.
decodeSpecific
(String
input raw string
str
,
String
the list of raw characters that need to be decoded (if encountered), leaving all the other encoded sequences alone.
charsToDecode
)

Decode a raw String and convert any specific URI encoded sequences into characters.

private static boolean
doDots(StringBuilder canonical, int dots)

private static boolean
doDotsSlash(StringBuilder canonical, int dots)

private static void
public static String

Returns:

The encoded path
encodePath
(String
The path to encode
path
)

Encode a URI path.

private static String
public static String

Returns:

the returned path with only safe encodings
encodePathSafeEncoding
(String
the path to encode
path
)

Encode characters in a path to ensure they only contain safe encodings suitable for both URI and Paths#get(URI) usage.

private static String
public static String

Returns:

output with specified characters encoded.
encodeSpecific
(String
input raw string
str
,
String
the list of raw characters that need to be encoded (if encountered)
charsToEncode
)

Encode a raw String and convert any specific characters to their URI encoded equivalent.

public static StringBuilder

Returns:

The StringBuilder or null if no substitutions required.
encodeString
(StringBuilder
StringBuilder to encode path into (or null)
buf
,
String
The path to encode
path
,
String
String of characters to encode. '%' is always encoded.
encode
)

Encode a URI path.

public static String

Returns:

the last segment.
getUriLastPathSegment
(URI
the URI to look in
uri
)

Given a URI, attempt to get the last segment.

public static boolean
hasScheme(String
URI
uri
)

Returns: True if the uri has a scheme

public static boolean

Returns:

True if the normal form of the path is within the root of the path.
isNotNormalWithinSelf
(String
The path to check
path
)

Check if a path would be normalized within itself.

public static boolean
isPathValid(String
The path to check for validity
path
)

Returns: True if the path does not contain any invalid path characters

private static boolean

Returns:

true if safe to decode, otherwise false;
isSafe
(int
the codepoint code to test
code
)

Test if codepoint is safe and unambiguous to pass as input to URI

private static boolean

Returns:

true if the decoded value is safe to pass as input to URI, otherwise false;
isSafeElseEncode
(int
the codepoint to check
code
,
Utf8StringBuilder
The builder to encode into
builder
)

If the codepoint is safe, do nothing, else add the UTF-8 URI encoded form of the codepoint.

public static boolean

Returns:

true if the token passes as a valid Host Registered Name
isValidHostRegisteredName
(String
the to test
token
)

True if token is a RFC3986 reg-name (Registered Name)

private static boolean

Returns:

true if the codepoint must be encoded, false otherwise
mustBeEncoded
(int
the codepoint to check
codepoint
)

Check codepoint for rules on URI encoding.

public static String

Returns:

A String URI
newURI
(String
the URI scheme
scheme
,
String
the URI server
server
,
int
the URI port
port
,
String
the URI path
path
,
String
the URI query
query
)

Create a new URI from the arguments, handling IPv6 host encoding and default ports

public static StringBuilder

Returns:

a StringBuilder containing URI prefix
newURIBuilder
(String
the URI scheme
scheme
,
String
the URI server
server
,
int
the URI port
port
)

Create a new URI StringBuilder from the arguments, handling IPv6 host encoding and default ports

public static String

Returns:

the normalized path, or null if path traversal above root.
normalizePath
(String
the decoded URI path to convert. Any special characters (e.g. ?, #) are assumed to be part of the path segments.
path
)

Normalize a URI path by factoring out all segments of .

public static String

Returns:

the normalized path, or null if path traversal above root.
normalizePathQuery
(String
the encoded URI from the path onwards, which may contain query strings and/or fragments
pathQuery
)

Normalize a URI path and query by factoring out all segments of '.

public static String

Returns:

the parent path of the URI
parentPath
(String
the path to return a parent reference to
p
)

Return the parent Path.

public static List<URI>
split(String
the input string of references
str
)

Split a string of references, that may be split with ',', or ';', or '|' into URIs.

public static Stream<URI>

Returns:

the Stream of URI
streamOf
(URLClassLoader
the classloader to load from
urlClassLoader
)

Stream the URLClassLoader#getURLs() as URIs

public static URI

Returns:

the jar:${uri_to_java_archive}!/${internal-reference} URI or the unchanged URI if not a Java Archive.
toJarFileUri
(URI
the URI to mutate to a jar:file:... URI.
uri
)

Take an arbitrary URI and provide a URI that is suitable for mounting the URI as a Java FileSystem.

public static URI

Returns:

The URI form of the resource.
toURI
(String
If the string starts with one of the ALLOWED_SCHEMES, then it is assumed to be a representation of a URI, otherwise it is treated as a Path.
resource
)

Convert a String into a URI suitable for use as a Resource.

public static URI

Returns:

the container String if a jar scheme, or just the URI untouched.
unwrapContainer
(URI
the input URI
uri
)

Unwrap a URI to expose its container path reference.

public static URI

Returns:

the jar:file: based URI with a deep reference
uriJarPrefix
(URI
the input URI (supporting jar or file based schemes
uri
,
String
the suffix to set. Must start with !/. Must be properly URI encoded.
encodedSuffix
)

Take a URI and add a deep reference jar:file://foo.jar!/suffix, replacing any existing deep reference on the input URI.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

ENCODE_PATH_NEEDS_ENCODINGback to summary
private static final boolean[] ENCODE_PATH_NEEDS_ENCODING
LOGback to summary
private static final Logger LOG
REGNAMEback to summary
private static final String REGNAME
REGNAME_ALLOWEDback to summary
private static final boolean[] REGNAME_ALLOWED
SUBDELIMSback to summary
private static final String SUBDELIMS
UNRESERVEDback to summary
private static final String UNRESERVED
URI_SUPPORTED_CHARACTERSback to summary
private static final boolean[] URI_SUPPORTED_CHARACTERS

The characters that are supported by the URI class and that can be decoded by canonicalPath(String)

Constructor Detail

URIUtilback to summary
private URIUtil()

Method Detail

addEncodedPathsback to summary
public static String addEncodedPaths(String p1, String p2)

Add two encoded URI path segments. Handles null and empty paths, path and query params (e.g. ?a=b or ;JSESSIONID=xxx) and avoids duplicate '/'

Parameters
p1:String

URI path segment (should be encoded)

p2:String

URI path segment (should be encoded)

Returns:String

Legally combined path segments.

addPathback to summary
public static URI addPath(URI uri, String path)

Add a sub path to an existing URI.

Parameters
uri:URI

A URI to add the path to

path:String

A safe path element

Returns:URI

URI with path added.

See Also
addPaths(String, String)
addPathQueryback to summary
public static String addPathQuery(String path, String query)

Add a path and a query string

Parameters
path:String

The path which may already contain a query

query:String

The query string to add (if blank, no query is added)

Returns:String

The path with any non-blank query added after a '?' or '&' as appropriate.

addPathsback to summary
public static String addPaths(String p1, String p2)

Add two Decoded URI path segments.

Handles null and empty paths. Path and query params (e.g. ?a=b or ;JSESSIONID=xxx) are not handled

Parameters
p1:String

URI path segment (should be decoded)

p2:String

URI path segment (should be decoded)

Returns:String

Legally combined path segments.

addQueriesback to summary
public static String addQueries(String query1, String query2)

Combine two query strings into one. Each query string should not contain the beginning '?' character, but may contain multiple parameters separated by the '&' character.

Parameters
query1:String

the first query string.

query2:String

the second query string.

Returns:String

the combination of the two query strings.

appendHexValueback to summary
private static void appendHexValue(Utf8StringBuilder builder, byte value)
appendSchemeHostPortback to summary
public static void appendSchemeHostPort(StringBuilder url, String scheme, String server, int port)

Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports

Parameters
url:StringBuilder

StringBuilder to append to

scheme:String

the URI scheme

server:String

the URI server

port:int

the URI port

appendSchemeHostPortback to summary
public static void appendSchemeHostPort(StringBuffer url, String scheme, String server, int port)

Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports

Parameters
url:StringBuffer

StringBuffer to append to

scheme:String

the URI scheme

server:String

the URI server

port:int

the URI port

canonicalPathback to summary
public static String canonicalPath(String encodedPath)

Canonicalize a URI path to a form that is unambiguous and safe to use with the JVM URI class.

Decode only the safe characters in a URI path and strip parameters of UTF-8 path. Safe characters are ones that are not special delimiters and that can be passed to the JVM URI class. Unsafe characters, other than '/' will be encoded. Encodings will be uppercase hex. Canonical paths are also normalized and may be used in string comparisons with other canonical paths.

For example the path /fo %2fo/b%61r will be normalized to /fo%20%2Fo/bar, whilst decodePath(String) would result in the ambiguous and URI illegal /fo /o/bar.

Parameters
encodedPath:String

An encoded URI path

Returns:String

the canonical path or null if it is non-normal

See Also
decodePath(String), normalizePath(String), URI
canonicalPathback to summary
public static <X extends Throwable> String canonicalPath(String encodedPath, Supplier<X> onBadUtf8) throws Supplier-:X

Canonicalize a URI path to a form that is unambiguous and safe to use with the JVM URI class.

Decode only the safe characters in a URI path and strip parameters of UTF-8 path. Safe characters are ones that are not special delimiters and that can be passed to the JVM URI class. Unsafe characters, other than '/' will be encoded. Encodings will be uppercase hex. Canonical paths are also normalized and may be used in string comparisons with other canonical paths.

For example the path /fo %2fo/b%61r will be normalized to /fo%20%2Fo/bar, whilst decodePath(String) would result in the ambiguous and URI illegal /fo /o/bar.

Parameters
encodedPath:String

An encoded URI path

onBadUtf8:Supplier<X>

A supplier of exceptions if bad UTF8 is encountered, or null for no exception thrown.

Returns:String

the canonical path or null if it is non-normal

See Also
decodePath(String), normalizePath(String), URI
compactPathback to summary
public static String compactPath(String path)

Convert a path to a compact form. All instances of // and /// etc. are factored out to single /

Parameters
path:String

the path to compact

Returns:String

the compacted path

correctFileURIback to summary
public static URI correctFileURI(URI uri)

Corrects any bad file based URIs (even within a jar:file: based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably: java.io.File creates with it's File#toURL() and File#toURI(), along with the side effects of using URL#toURI())

This correction is limited to only the file:/ substring in the URI. If there is a file:/<not-a-slash> detected, that substring is corrected to file:///<not-a-slash>, all other uses of file:, and URIs without a file: substring are left alone.

Note that Windows UNC based URIs are left alone, along with non-absolute URIs.

Parameters
uri:URI

the URI to (possibly) correct

Returns:URI

the new URI with the file:/ substring corrected, or the original URI.

decodePathback to summary
public static String decodePath(String path)

Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.

Parameters
path:String

The URI path to decode

See Also
canonicalPath(String), normalizePath(String)
decodePathback to summary
public static String decodePath(String path, int offset, int length)

Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.

Parameters
path:String

A String holding the URI path to decode

offset:int

The start of the URI within the path string

length:int

The length of the URI within the path string

See Also
canonicalPath(String), normalizePath(String)
decodeSpecificback to summary
public static String decodeSpecific(String str, String charsToDecode)

Decode a raw String and convert any specific URI encoded sequences into characters.

Parameters
str:String

input raw string

charsToDecode:String

the list of raw characters that need to be decoded (if encountered), leaving all the other encoded sequences alone.

Returns:String

output with specified characters decoded.

Annotations
@SuppressWarnings:Duplicates
doDotsback to summary
private static boolean doDots(StringBuilder canonical, int dots)
doDotsSlashback to summary
private static boolean doDotsSlash(StringBuilder canonical, int dots)
encodeCodepointback to summary
private static void encodeCodepoint(int code, Utf8StringBuilder builder)
encodePathback to summary
public static String encodePath(String path)

Encode a URI path. This is the same encoding offered by URLEncoder, except that the '/' character is not encoded.

Parameters
path:String

The path to encode

Returns:String

The encoded path

encodePathBytesback to summary
private static String encodePathBytes(String path)
encodePathSafeEncodingback to summary
public static String encodePathSafeEncoding(String path)

Encode characters in a path to ensure they only contain safe encodings suitable for both URI and Paths#get(URI) usage.

Parameters
path:String

the path to encode

Returns:String

the returned path with only safe encodings

encodePathStringback to summary
private static String encodePathString(String path)
encodeSpecificback to summary
public static String encodeSpecific(String str, String charsToEncode)

Encode a raw String and convert any specific characters to their URI encoded equivalent.

Parameters
str:String

input raw string

charsToEncode:String

the list of raw characters that need to be encoded (if encountered)

Returns:String

output with specified characters encoded.

Annotations
@SuppressWarnings:Duplicates
encodeStringback to summary
public static StringBuilder encodeString(StringBuilder buf, String path, String encode)

Encode a URI path.

Parameters
buf:StringBuilder

StringBuilder to encode path into (or null)

path:String

The path to encode

encode:String

String of characters to encode. '%' is always encoded.

Returns:StringBuilder

The StringBuilder or null if no substitutions required.

getUriLastPathSegmentback to summary
public static String getUriLastPathSegment(URI uri)

Given a URI, attempt to get the last segment.

If this is a jar:file:// style URI, then the JAR filename is returned (not the deep !/path location)

Parameters
uri:URI

the URI to look in

Returns:String

the last segment.

hasSchemeback to summary
public static boolean hasScheme(String uri)
Parameters
uri:String

URI

Returns:boolean

True if the uri has a scheme

isNotNormalWithinSelfback to summary
public static boolean isNotNormalWithinSelf(String path)

Check if a path would be normalized within itself. For example, /foo/../../bar is normalized above its root and would thus return false, whilst /foo/./bar/.. is normal within itself and would return true.

Parameters
path:String

The path to check

Returns:boolean

True if the normal form of the path is within the root of the path.

isPathValidback to summary
public static boolean isPathValid(String path)
Parameters
path:String

The path to check for validity

Returns:boolean

True if the path does not contain any invalid path characters

isSafeback to summary
private static boolean isSafe(int code)

Test if codepoint is safe and unambiguous to pass as input to URI

Parameters
code:int

the codepoint code to test

Returns:boolean

true if safe to decode, otherwise false;

isSafeElseEncodeback to summary
private static boolean isSafeElseEncode(int code, Utf8StringBuilder builder)

If the codepoint is safe, do nothing, else add the UTF-8 URI encoded form of the codepoint.

Parameters
code:int

the codepoint to check

builder:Utf8StringBuilder

The builder to encode into

Returns:boolean

true if the decoded value is safe to pass as input to URI, otherwise false;

isValidHostRegisteredNameback to summary
public static boolean isValidHostRegisteredName(String token)

True if token is a RFC3986 reg-name (Registered Name)

Parameters
token:String

the to test

Returns:boolean

true if the token passes as a valid Host Registered Name

mustBeEncodedback to summary
private static boolean mustBeEncoded(int codepoint)

Check codepoint for rules on URI encoding.

This does not allow 8-bit characters, unlike isSafe(int)

Parameters
codepoint:int

the codepoint to check

Returns:boolean

true if the codepoint must be encoded, false otherwise

newURIback to summary
public static String newURI(String scheme, String server, int port, String path, String query)

Create a new URI from the arguments, handling IPv6 host encoding and default ports

Parameters
scheme:String

the URI scheme

server:String

the URI server

port:int

the URI port

path:String

the URI path

query:String

the URI query

Returns:String

A String URI

newURIBuilderback to summary
public static StringBuilder newURIBuilder(String scheme, String server, int port)

Create a new URI StringBuilder from the arguments, handling IPv6 host encoding and default ports

Parameters
scheme:String

the URI scheme

server:String

the URI server

port:int

the URI port

Returns:StringBuilder

a StringBuilder containing URI prefix

normalizePathback to summary
public static String normalizePath(String path)

Normalize a URI path by factoring out all segments of . and ... Null is returned if the path is normalized above its root.

Parameters
path:String

the decoded URI path to convert. Any special characters (e.g. ?, #) are assumed to be part of the path segments.

Returns:String

the normalized path, or null if path traversal above root.

See Also
normalizePathQuery(String), canonicalPath(String), decodePath(String)
normalizePathQueryback to summary
public static String normalizePathQuery(String pathQuery)

Normalize a URI path and query by factoring out all segments of '.' and '..' up until any query or fragment. Null is returned if the path is normalized above its root.

Parameters
pathQuery:String

the encoded URI from the path onwards, which may contain query strings and/or fragments

Returns:String

the normalized path, or null if path traversal above root.

See Also
normalizePath(String)
parentPathback to summary
public static String parentPath(String p)

Return the parent Path.

Treat a URI like a directory path and return the parent directory.

Parameters
p:String

the path to return a parent reference to

Returns:String

the parent path of the URI

splitback to summary
public static List<URI> split(String str)

Split a string of references, that may be split with ',', or ';', or '|' into URIs.

Each part of the input string could be path references (unix or windows style), or string URI references.

If the result of processing the input segment is a java archive, then its resulting URI will be a mountable URI as jar:file:...!/

Parameters
str:String

the input string of references

See Also
toJarFileUri(URI)
streamOfback to summary
public static Stream<URI> streamOf(URLClassLoader urlClassLoader)

Stream the URLClassLoader#getURLs() as URIs

Parameters
urlClassLoader:URLClassLoader

the classloader to load from

Returns:Stream<URI>

the Stream of URI

toJarFileUriback to summary
public static URI toJarFileUri(URI uri)

Take an arbitrary URI and provide a URI that is suitable for mounting the URI as a Java FileSystem.

The resulting URI will point to the jar:file://foo.jar!/ said Java Archive (jar, war, or zip)

Parameters
uri:URI

the URI to mutate to a jar:file:... URI.

Returns:URI

the jar:${uri_to_java_archive}!/${internal-reference} URI or the unchanged URI if not a Java Archive.

See Also
FileID#isArchive(URI)
toURIback to summary
public static URI toURI(String resource)

Convert a String into a URI suitable for use as a Resource.

Parameters
resource:String

If the string starts with one of the ALLOWED_SCHEMES, then it is assumed to be a representation of a URI, otherwise it is treated as a Path.

Returns:URI

The URI form of the resource.

unwrapContainerback to summary
public static URI unwrapContainer(URI uri)

Unwrap a URI to expose its container path reference.

Take out the container archive name URI from a jar:file:${container-name}!/ URI.

Parameters
uri:URI

the input URI

Returns:URI

the container String if a jar scheme, or just the URI untouched.

uriJarPrefixback to summary
public static URI uriJarPrefix(URI uri, String encodedSuffix)

Take a URI and add a deep reference jar:file://foo.jar!/suffix, replacing any existing deep reference on the input URI.

Parameters
uri:URI

the input URI (supporting jar or file based schemes

encodedSuffix:String

the suffix to set. Must start with !/. Must be properly URI encoded.

Returns:URI

the jar:file: based URI with a deep reference