Class URIUtil
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:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intPort number indicating that the port is undefined. -
Method Summary
Modifier and TypeMethodDescriptionstatic StringaddEncodedPaths(String p1, String p2) Add two encoded URI path segments.static URIAdd a sub path to an existing URI.static StringaddPathQuery(String path, String query) Add a path and a query stringstatic StringAdd two Decoded URI path segments.static StringaddQueries(String query1, String query2) Combine two query strings into one.static voidappendSchemeHostPort(StringBuffer url, String scheme, String server, int port) Deprecated.static voidappendSchemeHostPort(StringBuilder url, String scheme, String server, int port) Append scheme, host and port URI prefix, handling IPv6 address encoding and default portsstatic StringcanonicalPath(String encodedPath) Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURIclass.canonicalPath(String encodedPath, Supplier<X> onBadUtf8) Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURIclass.static StringcompactPath(String path) Convert a path to a compact form.static URIcorrectFileURI(URI uri) Deprecated, for removal: This API element is subject to removal in a future version.usecorrectURI(URI)instead, will be removed in Jetty 12.1.0static URIcorrectURI(URI uri) Corrects any badfilebased URIs (even within ajar:file:based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:Filecreates with it'sFile.toURL()andFile.toURI(), along with the side effects of usingURL.toURI())static StringdecodePath(String path) Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.static StringdecodePath(String path, int offset, int length) Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.static StringdecodeSpecific(String str, String charsToDecode) Decode a raw String and convert any specific URI encoded sequences into characters.static StringencodePath(String path) Encode a URI path.static StringencodePathSafeEncoding(String path) Encode characters in a path to ensure they only contain safe encodings suitable for bothURIandPaths.get(URI)usage.static StringencodeSpecific(String str, String charsToEncode) Encode a raw String and convert any specific characters to their URI encoded equivalent.static StringBuilderencodeString(StringBuilder buf, String path, String encode) Encode a URI path.static intgetDefaultPortForScheme(String scheme) Get the default port for some well known schemesstatic StringgetUriLastPathSegment(URI uri) Given a URI, attempt to get the last segment.static booleanstatic booleanisNotNormalWithinSelf(String path) Check if a path would be normalized within itself.static booleanisPathValid(String path) static booleanisRelative(String uriOrPath) Test if a string is a relative path or a URIstatic booleanisValidHostRegisteredName(String token) True if token is a RFC3986reg-name(Registered Name)static StringCreate a new URI from the arguments, handling IPv6 host encoding and default portsstatic StringCreate a new URI from the arguments, handling IPv6 host encoding and default portsstatic StringCreate a new URI from the arguments, handling IPv6 host encoding and default portsstatic StringBuildernewURIBuilder(String scheme, String server, int port) Create a new URI StringBuilder from the arguments, handling IPv6 host encoding and default portsstatic StringnormalizePath(String path) Normalize a URI path by factoring out all segments of.and...static StringnormalizePathQuery(String pathQuery) Normalize a URI path and query by factoring out all segments of '.' and '..' up until any query or fragment.static intnormalizePortForScheme(String scheme, int port) Normalize a port for a given schemestatic StringnormalizeScheme(String scheme) Normalize the schemestatic StringparentPath(String p) Return the parent Path.Deprecated, for removal: This API element is subject to removal in a future version.streamOf(URLClassLoader urlClassLoader) Stream theURLClassLoader.getURLs()as URIsstatic URItoJarFileUri(URI uri) Take an arbitrary URI and provide a URI that is suitable for mounting the URI as a Java FileSystem.static URIConvert a String reference into an absolute URI.static URIunwrapContainer(URI uri) Unwrap a URI to expose its container path reference.static URIuriJarPrefix(URI uri, String encodedSuffix) Take a URI and add a deep referencejar:file://foo.jar!/suffix, replacing any existing deep reference on the input URI.
-
Field Details
-
UNDEFINED_PORT
-
-
Method Details
-
encodePath
-
encodeSpecific
Encode a raw String and convert any specific characters to their URI encoded equivalent.- Parameters:
str- input raw stringcharsToEncode- the list of raw characters that need to be encoded (if encountered)- Returns:
- output with specified characters encoded.
-
decodeSpecific
Decode a raw String and convert any specific URI encoded sequences into characters.- Parameters:
str- input raw stringcharsToDecode- the list of raw characters that need to be decoded (if encountered), leaving all the other encoded sequences alone.- Returns:
- output with specified characters decoded.
-
encodeString
Encode a URI path.- Parameters:
buf- StringBuilder to encode path into (or null)path- The path to encodeencode- String of characters to encode. '%' is always encoded.- Returns:
- The StringBuilder or null if no substitutions required.
-
decodePath
-
decodePath
Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.- Parameters:
path- A String holding the URI path to decodeoffset- The start of the URI within the path stringlength- The length of the URI within the path string- Returns:
- the decoded path (or null if input path is null)
- See Also:
-
isPathValid
- Parameters:
path- The path to check for validity- Returns:
- True if the path does not contain any invalid path characters
-
isRelative
Test if a string is a relative path or a URI- Parameters:
uriOrPath- A string that is either a path, a URI path segment or an absolute URI- Returns:
- True if the string does not start with any absolute URI or file characters sequences.
-
canonicalPath
Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURIclass.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
URIclass. 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%61rwill be normalized to/fo%20%2Fo/bar, whilstdecodePath(String)would result in the ambiguous and URI illegal/fo /o/bar.- Parameters:
encodedPath- An encoded URI path- Returns:
- the canonical path or null if it is non-normal
- See Also:
-
canonicalPath
public static <X extends Throwable> String canonicalPath(String encodedPath, Supplier<X> onBadUtf8) throws X Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURIclass.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
URIclass. 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%61rwill be normalized to/fo%20%2Fo/bar, whilstdecodePath(String)would result in the ambiguous and URI illegal/fo /o/bar.- Parameters:
encodedPath- An encoded URI pathonBadUtf8- A supplier of exceptions if bad UTF8 is encountered, or null for no exception thrown.- Returns:
- the canonical path or null if it is non-normal
- Throws:
X- See Also:
-
addEncodedPaths
Add two encoded URI path segments. Handles null and empty paths, path and query params (e.g.?a=bor;JSESSIONID=xxx) and avoids duplicate '/'- Parameters:
p1- URI path segment (should be encoded)p2- URI path segment (should be encoded)- Returns:
- Legally combined path segments.
-
addPaths
Add two Decoded URI path segments.Handles null and empty paths. Path and query params (e.g.
?a=bor;JSESSIONID=xxx) are not handled- Parameters:
p1- URI path segment (should be decoded)p2- URI path segment (should be decoded)- Returns:
- Legally combined path segments.
-
addPathQuery
Add a path and a query string- Parameters:
path- The path which may already contain a queryquery- The query string to add (if blank, no query is added)- Returns:
- The path with any non-blank query added after a '
?' or '&' as appropriate.
-
getUriLastPathSegment
-
parentPath
-
normalizePathQuery
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- the encoded URI from the path onwards, which may contain query strings and/or fragments- Returns:
- the normalized path, or null if path traversal above root.
- See Also:
-
isNotNormalWithinSelf
Check if a path would be normalized within itself. For example,
/foo/../../baris normalized above its root and would thus return false, whilst/foo/./bar/..is normal within itself and would return true.- Parameters:
path- The path to check- Returns:
- True if the normal form of the path is within the root of the path.
-
normalizePath
Normalize a URI path by factoring out all segments of
.and... Null is returned if the path is normalized above its root.- Parameters:
path- the decoded URI path to convert. Any special characters (e.g.?,#) are assumed to be part of the path segments.- Returns:
- the normalized path, or null if path traversal above root.
- See Also:
-
compactPath
-
hasScheme
- Parameters:
uri- URI- Returns:
- True if the uri has a scheme
-
isValidHostRegisteredName
-
newURI
-
newURI
Create a new URI from the arguments, handling IPv6 host encoding and default ports- Parameters:
scheme- the URI schemeserver- the URI serverport- the URI portpath- the URI pathquery- the URI query- Returns:
- A String URI
-
newURI
public static String newURI(String scheme, String server, int port, String path, String query, String fragment) Create a new URI from the arguments, handling IPv6 host encoding and default ports- Parameters:
scheme- the URI schemeserver- the URI serverport- the URI portpath- the URI pathquery- the URI queryfragment- the URI fragment- Returns:
- A String URI
-
newURIBuilder
Create a new URI StringBuilder from the arguments, handling IPv6 host encoding and default ports- Parameters:
scheme- the URI schemeserver- the URI serverport- the URI port- Returns:
- a StringBuilder containing URI prefix
-
appendSchemeHostPort
Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports- Parameters:
url- StringBuilder to append toscheme- the URI schemeserver- the URI serverport- the URI port
-
appendSchemeHostPort
@Deprecated public static void appendSchemeHostPort(StringBuffer url, String scheme, String server, int port) Deprecated.Append scheme, host and port URI prefix, handling IPv6 address encoding and default ports- Parameters:
url- StringBuffer to append toscheme- the URI schemeserver- the URI serverport- the URI port
-
encodePathSafeEncoding
Encode characters in a path to ensure they only contain safe encodings suitable for bothURIandPaths.get(URI)usage.- Parameters:
path- the path to encode- Returns:
- the returned path with only safe encodings
-
addPath
-
addQueries
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- the first query string.query2- the second query string.- Returns:
- the combination of the two query strings.
-
correctFileURI
Deprecated, for removal: This API element is subject to removal in a future version.usecorrectURI(URI)instead, will be removed in Jetty 12.1.0Corrects any bad
filebased URIs (even within ajar:file:based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:Filecreates with it'sFile.toURL()andFile.toURI(), along with the side effects of usingURL.toURI())This correction is limited to only the
file:/substring in the URI. If there is afile:/<not-a-slash>detected, that substring is corrected tofile:///<not-a-slash>, all other uses offile:, and URIs without afile:substring are left alone.Note that Windows UNC based URIs are left alone, along with non-absolute URIs.
- Parameters:
uri- the URI to (possibly) correct- Returns:
- the new URI with the
file:/substring corrected, or the original URI.
-
correctURI
Corrects any bad
filebased URIs (even within ajar:file:based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:Filecreates with it'sFile.toURL()andFile.toURI(), along with the side effects of usingURL.toURI())This correction is currently limited to only the
file:/substring in the URI. If there is afile:/<not-a-slash>detected, that substring is corrected tofile:///<not-a-slash>, all other uses offile:, and URIs without afile:substring are left alone.Note that Windows UNC based URIs are left alone, along with non-absolute URIs.
- Parameters:
uri- the URI to (possibly) correct- Returns:
- the new URI with the
file:scheme specific part corrected, or the original URI.
-
split
Deprecated, for removal: This API element is subject to removal in a future version.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- the input string of references- See Also:
-
toJarFileUri
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- the URI to mutate to ajar:file:...URI.- Returns:
- the
jar:${uri_to_java_archive}!/${internal-reference}URI or the unchanged URI if not a Java Archive. - See Also:
-
toURI
Convert a String reference into an absolute URI.
If given a relative reference string to a path, it will convert it to an absolute path using the same techniques present in the JVM itself (eg:
Path.of(reference).toAbsolutePath())Relative URI reference strings (eg:
"file:path/dir/"and"file:path/foo.jar!/") are not supported.- Parameters:
reference- the raw String input.- Returns:
- The absolute
URIform of the reference. - Throws:
IllegalArgumentException- if unable to convert the input string.
-
unwrapContainer
-
uriJarPrefix
Take a URI and add a deep referencejar:file://foo.jar!/suffix, replacing any existing deep reference on the input URI.- Parameters:
uri- the input URI (supportingjarorfilebased schemesencodedSuffix- the suffix to set. Must start with!/. Must be properly URI encoded.- Returns:
- the
jar:file:based URI with a deep reference
-
streamOf
Stream theURLClassLoader.getURLs()as URIs- Parameters:
urlClassLoader- the classloader to load from- Returns:
- the Stream of
URI
-
getDefaultPortForScheme
Get the default port for some well known schemes- Parameters:
scheme- The scheme- Returns:
- The default port or -1 if not known
-
normalizeScheme
-
normalizePortForScheme
Normalize a port for a given scheme- Parameters:
scheme- The schemeport- The port to normalize- Returns:
- The port number or 0 if provided port was less than 0 or was equal to the default port for the scheme
-
appendSchemeHostPort(StringBuilder, String, String, int)