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
Modifier and TypeFieldDescriptionstatic final int
Port number indicating that the port is undefined. -
Method Summary
Modifier and TypeMethodDescriptionstatic String
addEncodedPaths
(String p1, String p2) Add two encoded URI path segments.static URI
Add a sub path to an existing URI.static String
addPathQuery
(String path, String query) Add a path and a query stringstatic String
Add two Decoded URI path segments.static String
addQueries
(String query1, String query2) Combine two query strings into one.static void
appendSchemeHostPort
(StringBuffer url, String scheme, String server, int port) Deprecated.static void
appendSchemeHostPort
(StringBuilder url, String scheme, String server, int port) Append scheme, host and port URI prefix, handling IPv6 address encoding and default portsstatic String
canonicalPath
(String encodedPath) Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURI
class.canonicalPath
(String encodedPath, Supplier<X> onBadUtf8) Canonicalize a URI path to a form that is unambiguous and safe to use with the JVMURI
class.static String
compactPath
(String path) Convert a path to a compact form.static URI
correctFileURI
(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 URI
correctURI
(URI uri) Corrects any badfile
based URIs (even within ajar:file:
based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:File
creates with it'sFile.toURL()
andFile.toURI()
, along with the side effects of usingURL.toURI()
)static String
decodePath
(String path) Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.static String
decodePath
(String path, int offset, int length) Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.static String
decodeSpecific
(String str, String charsToDecode) Decode a raw String and convert any specific URI encoded sequences into characters.static String
encodePath
(String path) Encode a URI path.static String
encodePathSafeEncoding
(String path) Encode characters in a path to ensure they only contain safe encodings suitable for bothURI
andPaths.get(URI)
usage.static String
encodeSpecific
(String str, String charsToEncode) Encode a raw String and convert any specific characters to their URI encoded equivalent.static StringBuilder
encodeString
(StringBuilder buf, String path, String encode) Encode a URI path.static int
getDefaultPortForScheme
(String scheme) Get the default port for some well known schemesstatic String
getUriLastPathSegment
(URI uri) Given a URI, attempt to get the last segment.static boolean
static boolean
isNotNormalWithinSelf
(String path) Check if a path would be normalized within itself.static boolean
isPathValid
(String path) static boolean
isRelative
(String uriOrPath) Test if a string is a relative path or a URIstatic boolean
isValidHostRegisteredName
(String token) True if token is a RFC3986reg-name
(Registered Name)static String
Create a new URI from the arguments, handling IPv6 host encoding and default portsstatic String
Create a new URI from the arguments, handling IPv6 host encoding and default portsstatic String
Create a new URI from the arguments, handling IPv6 host encoding and default portsstatic StringBuilder
newURIBuilder
(String scheme, String server, int port) Create a new URI StringBuilder from the arguments, handling IPv6 host encoding and default portsstatic String
normalizePath
(String path) Normalize a URI path by factoring out all segments of.
and..
.static String
normalizePathQuery
(String pathQuery) Normalize a URI path and query by factoring out all segments of '.
' and '..
' up until any query or fragment.static int
normalizePortForScheme
(String scheme, int port) Normalize a port for a given schemestatic String
normalizeScheme
(String scheme) Normalize the schemestatic String
parentPath
(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 URI
toJarFileUri
(URI uri) Take an arbitrary URI and provide a URI that is suitable for mounting the URI as a Java FileSystem.static URI
Deprecated.This method is currently resolving relative paths against the current directory, which is a mechanism that should be implemented by aResourceFactory
.static URI
unwrapContainer
(URI uri) Unwrap a URI to expose its container path reference.static URI
uriJarPrefix
(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
public static final int UNDEFINED_PORTPort number indicating that the port is undefined.- See Also:
-
-
Method Details
-
encodePath
Encode a URI path. This is the same encoding offered by URLEncoder, except that the '/
' character is not encoded.- Parameters:
path
- The path to encode- Returns:
- The encoded path
-
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:
path
- The path to encodebuf
- StringBuilder to encode path into (or null)encode
- String of characters to encode. '%
' is always encoded.- Returns:
- The StringBuilder or null if no substitutions required.
-
decodePath
Decodes a percent-encoded URI path (assuming UTF-8 characters) and strips path parameters.- Parameters:
path
- The URI path to decode- See Also:
-
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- 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 JVMURI
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
, 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 JVMURI
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
, 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 extends Throwable
- See Also:
-
addEncodedPaths
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
- 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=b
or;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
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
- the URI to look in- Returns:
- the last segment.
-
parentPath
Return the parent Path.Treat a URI like a directory path and return the parent directory.
- Parameters:
p
- the path to return a parent reference to- Returns:
- the parent path of the URI
-
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/../../bar
is 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
Convert a path to a compact form. All instances of//
and///
etc. are factored out to single/
- Parameters:
path
- the path to compact- Returns:
- the compacted path
-
hasScheme
- Parameters:
uri
- URI- Returns:
- True if the uri has a scheme
-
isValidHostRegisteredName
True if token is a RFC3986reg-name
(Registered Name)- Parameters:
token
- the to test- Returns:
- true if the token passes as a valid Host Registered Name
-
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 port- Returns:
- A String URI
-
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 bothURI
andPaths.get(URI)
usage.- Parameters:
path
- the path to encode- Returns:
- the returned path with only safe encodings
-
addPath
Add a sub path to an existing URI.- Parameters:
uri
- A URI to add the path topath
- A safe path element- Returns:
- URI with path added.
- See Also:
-
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
file
based URIs (even within ajar:file:
based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:File
creates 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
file
based URIs (even within ajar:file:
based URIs) from the bad out-of-spec format that various older Java APIs creates (most notably:File
creates 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
Deprecated.This method is currently resolving relative paths against the current directory, which is a mechanism that should be implemented by aResourceFactory
. All calls to this method need to be reviewed.Convert a String into a URI suitable for use as a Resource.
-
unwrapContainer
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
- the input URI- Returns:
- the container String if a
jar
scheme, or just the URI untouched.
-
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 (supportingjar
orfile
based 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
Normalize the scheme- Parameters:
scheme
- The scheme to normalize- Returns:
- The normalized version of the scheme
-
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)