Class URLUtils
- java.lang.Object
-
- io.microsphere.net.URLUtils
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.StringDEFAULT_ENCODINGThe default encoding : "UTF-8"static java.lang.StringDEFAULT_HANDLER_PACKAGE_PREFIXThe prefix of package forHandlersstatic java.net.URL[]EMPTY_URL_ARRAYThe empty array ofURLstatic java.lang.StringFILE_URL_PREFIXThe prefix ofURLfor file protocol : "file:/"static java.lang.StringHANDLER_CONVENTION_CLASS_NAMEThe convention class name ofHandler.static java.lang.StringHANDLER_PACKAGES_PROPERTY_NAMEThe property which specifies the package prefix list to be scanned for protocol handlers.static charHANDLER_PACKAGES_SEPARATOR_CHARThe separator character ofHandlers'packages.static java.lang.StringSUB_PROTOCOL_MATRIX_NAMEThe matrix name for the URLs' sub-protocol
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidattachURLStreamHandlerFactory(java.net.URLStreamHandlerFactory factory)Attaches the specifiedURLStreamHandlerFactoryto the current JVM.static java.lang.StringbuildMatrixString(java.lang.String name, java.lang.String... values)Builds a matrix parameter string in the format ";name=value1;name=value2..." from the provided values.static java.lang.StringbuildMatrixString(java.util.Map<java.lang.String,java.util.List<java.lang.String>> matrixParameters)Builds a matrix string from the provided map of matrix parameters.protected static java.lang.StringbuildString(java.lang.String name, java.lang.String[] values, char separator, char joiner)static java.lang.StringbuildURI(java.lang.String... paths)Builds a normalized URI path by concatenating the provided path segments with slashes.protected static voidclearURLStreamHandlerFactory()static voidclose(java.net.URLConnection conn)Closes the specified URL connection gracefully.static java.lang.Stringdecode(java.lang.String value)Decodes aapplication/x-www-form-urlencodedstring using the default encoding.static java.lang.Stringdecode(java.lang.String value, java.lang.String encoding)Decodes aapplication/x-www-form-urlencodedstring using a specific encoding scheme.protected static java.lang.StringdoResolveArchiveEntryPath(java.lang.String path)protected static java.io.FiledoResolveArchiveFile(java.net.URL url)static java.lang.Stringencode(java.lang.String value)Encodes the provided string using URL encoding with the default encoding scheme.static java.lang.Stringencode(java.lang.String value, java.lang.String encoding)Translates a string intoapplication/x-www-form-urlencodedformat using a specific encoding scheme.protected static java.lang.StringgetFirst(java.util.Map<java.lang.String,java.util.List<java.lang.String>> parameters, java.lang.String name)protected static MutableURLStreamHandlerFactorygetMutableURLStreamHandlerFactory()protected static MutableURLStreamHandlerFactorygetMutableURLStreamHandlerFactory(boolean createIfAbsent)static java.lang.StringgetSubProtocol(java.lang.String url)Extracts the first sub-protocol value from the specified URL string.static java.net.URLStreamHandlerFactorygetURLStreamHandlerFactory()Retrieves the current system-wideURLStreamHandlerFactory.protected static intindexOfMatrixString(java.lang.String value)static booleanisArchiveURL(java.net.URL url)Determines if the provided URL refers to an archive.static booleanisDirectoryURL(java.net.URL url)Determines whether the specified URL refers to a directory.static booleanisJarURL(java.net.URL url)Determines if the provided URL refers to a JAR file.static java.lang.StringnormalizePath(java.lang.String path)Normalizes a given path by removing redundant slashes or backslashes and standardizing separators.static java.net.URLofURL(java.lang.String url)Converts the provided URL string into aURLobject.protected static java.lang.StringreformProtocol(java.lang.String protocol, java.lang.String spec)protected static java.lang.StringreformProtocol(java.lang.String protocol, java.util.List<java.lang.String> subProtocols)static voidregisterURLStreamHandler(ExtendableProtocolURLStreamHandler handler)Registers the specifiedExtendableProtocolURLStreamHandlerfor its protocol.static voidregisterURLStreamHandler(java.lang.String protocol, java.net.URLStreamHandler handler)Registers aURLStreamHandlerfor the specified protocol.protected static java.io.FileresolveArchiveDirectory(java.net.URL resourceURL)static java.lang.StringresolveArchiveEntryPath(java.net.URL archiveFileURL)Resolves the archive entry path from the given URL.static java.io.FileresolveArchiveFile(java.net.URL resourceURL)Resolves the archive file from the specified URL.static java.lang.StringresolveAuthority(java.lang.String authority)Resolves the authority part from the specified URL string by truncating any matrix parameters.static java.lang.StringresolveAuthority(java.net.URL url)Resolves and returns the authority component from the providedURL.static java.lang.StringresolveBasePath(java.net.URL url)Resolves the base path from the specified URL.static java.util.Map<java.lang.String,java.util.List<java.lang.String>>resolveMatrixParameters(java.lang.String url)Extracts and resolves matrix parameters from the provided URL string.protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>>resolveParameters(java.lang.String paramsString, char separatorChar)static java.lang.StringresolvePath(java.net.URL url)Resolves the path component from the specified URL, excluding any matrix parameters.static java.lang.StringresolveProtocol(java.lang.String url)Resolves the protocol from the specified URL string.static java.util.Map<java.lang.String,java.util.List<java.lang.String>>resolveQueryParameters(java.lang.String url)Resolve the query parametersMapfrom specified URL.static java.util.List<java.lang.String>resolveSubProtocols(java.lang.String url)Resolves the list of sub-protocols from the specified URL string.static java.util.List<java.lang.String>resolveSubProtocols(java.net.URL url)Resolves the list of sub-protocols from the specifiedURL.static java.lang.StringtoExternalForm(java.net.URL url)Converts the providedURLto its external form as a string, including all components such as protocol, authority, path, matrix parameters, query, and fragment.static java.util.jar.JarFiletoJarFile(java.net.URL url)Converts the provided URL to aJarFileinstance if it refers to a valid JAR file.protected static java.lang.StringtruncateMatrixString(java.lang.String value)
-
-
-
Field Detail
-
DEFAULT_ENCODING
public static final java.lang.String DEFAULT_ENCODING
The default encoding : "UTF-8"
-
EMPTY_URL_ARRAY
@Immutable public static final java.net.URL[] EMPTY_URL_ARRAY
The empty array ofURL
-
FILE_URL_PREFIX
public static final java.lang.String FILE_URL_PREFIX
The prefix ofURLfor file protocol : "file:/"- See Also:
- Constant Field Values
-
HANDLER_PACKAGES_PROPERTY_NAME
public static final java.lang.String HANDLER_PACKAGES_PROPERTY_NAME
The property which specifies the package prefix list to be scanned for protocol handlers. The value of this property (if any) should be a vertical bar delimited list of package names to search through for a protocol handler to load. The policy of this class is that all protocol handlers will be in a class called.Handler, and each package in the list is examined in turn for a matching handler. If none are found (or the property is not specified), the default package prefix, sun.net.www.protocol, is used. The search proceeds from the first package in the list to the last and stops when a match is found. - See Also:
- Constant Field Values
-
DEFAULT_HANDLER_PACKAGE_PREFIX
public static final java.lang.String DEFAULT_HANDLER_PACKAGE_PREFIX
The prefix of package forHandlers- See Also:
- Constant Field Values
-
HANDLER_PACKAGES_SEPARATOR_CHAR
public static final char HANDLER_PACKAGES_SEPARATOR_CHAR
The separator character ofHandlers'packages.- See Also:
- Constant Field Values
-
HANDLER_CONVENTION_CLASS_NAME
public static final java.lang.String HANDLER_CONVENTION_CLASS_NAME
The convention class name ofHandler.- See Also:
- Constant Field Values
-
SUB_PROTOCOL_MATRIX_NAME
public static final java.lang.String SUB_PROTOCOL_MATRIX_NAME
The matrix name for the URLs' sub-protocol- See Also:
- Constant Field Values
-
-
Method Detail
-
ofURL
@Nonnull public static java.net.URL ofURL(java.lang.String url)
Converts the provided URL string into aURLobject.This method attempts to create a valid
URLfrom the given string. If the string does not represent a valid URL, anIllegalArgumentExceptionis thrown.Example Usage
// Valid URL URL validUrl = URLUtils.ofURL("https://www.example.com"); // Invalid URL - will throw IllegalArgumentException try { URL invalidUrl = URLUtils.ofURL("htp:/invalid-url"); } catch (IllegalArgumentException e) { System.out.println("Invalid URL: " + e.getMessage()); }- Parameters:
url- The string representation of the URL.- Returns:
- A non-null
URLobject if the input string is a valid URL. - Throws:
java.lang.IllegalArgumentException- if the provided string is not a valid URL.
-
resolveArchiveEntryPath
@Nullable public static java.lang.String resolveArchiveEntryPath(java.net.URL archiveFileURL) throws java.lang.NullPointerException
Resolves the archive entry path from the given URL.This method extracts the part of the URL's path that comes after the archive entry separator. If the URL does not contain an archive entry separator, this method returns
null.Example Usage
// Example 1: URL with archive entry path URL jarURL = new URL("jar:file:/path/to/archive.jar!/entry/path"); String entryPath = URLUtils.resolveArchiveEntryPath(jarURL); System.out.println(entryPath); // Output: entry/path // Example 2: URL without archive entry path URL fileURL = new URL("file:/path/to/archive.jar"); entryPath = URLUtils.resolveArchiveEntryPath(fileURL); System.out.println(entryPath); // Output: null- Parameters:
archiveFileURL- the URL to resolve the archive entry path from- Returns:
- the resolved archive entry path if present, or
nullotherwise - Throws:
java.lang.NullPointerException- if the provided URL isnull
-
doResolveArchiveEntryPath
protected static java.lang.String doResolveArchiveEntryPath(java.lang.String path)
-
resolveBasePath
@Nonnull public static java.lang.String resolveBasePath(java.net.URL url) throws java.lang.NullPointerException
Resolves the base path from the specified URL.This method extracts the main path part of the URL, excluding any archive entry path if present.
Example Usage
// Example 1: File URL without archive entry path URL fileURL = new URL("file:/path/to/resource.txt"); String basePath = URLUtils.resolveBasePath(fileURL); System.out.println(basePath); // Output: /path/to/resource.txt // Example 2: JAR URL with archive entry path URL jarURL = new URL("jar:file:/path/to/archive.jar!/entry/path"); basePath = URLUtils.resolveBasePath(jarURL); System.out.println(basePath); // Output: /path/to/archive.jar- Parameters:
url- the specified URL- Returns:
- the resolved base path
- Throws:
java.lang.NullPointerException- if the provided URL isnull
-
resolveArchiveFile
@Nullable public static java.io.File resolveArchiveFile(java.net.URL resourceURL) throws java.lang.NullPointerException
Resolves the archive file from the specified URL.If the provided URL uses the "file" protocol, this method delegates to
resolveArchiveDirectory(URL)to resolve the archive directory. Otherwise, it callsdoResolveArchiveFile(URL)to handle other protocols like "jar".Example Usage
// Example 1: File URL pointing directly to a JAR file URL fileURL = new URL("file:/path/to/archive.jar"); File archiveFile = URLUtils.resolveArchiveFile(fileURL); System.out.println(archiveFile.exists()); // Output: true (if the file exists) // Example 2: JAR URL with an entry path URL jarURL = new URL("jar:file:/path/to/archive.jar!/entry/path"); archiveFile = URLUtils.resolveArchiveFile(jarURL); System.out.println(archiveFile.exists()); // Output: true (if the archive exists)- Parameters:
resourceURL- the URL to resolve the archive file from- Returns:
- the resolved archive file if found and exists; otherwise, returns null
- Throws:
java.lang.NullPointerException- if the provided URL isnull
-
doResolveArchiveFile
protected static java.io.File doResolveArchiveFile(java.net.URL url) throws java.lang.NullPointerException- Throws:
java.lang.NullPointerException
-
resolveArchiveDirectory
protected static java.io.File resolveArchiveDirectory(java.net.URL resourceURL)
-
resolveQueryParameters
@Nonnull @Immutable public static java.util.Map<java.lang.String,java.util.List<java.lang.String>> resolveQueryParameters(java.lang.String url)
Resolve the query parametersMapfrom specified URL. The parameter name is used as the key, and the list of parameter values is used as the value.Example Usage
// Example URL with query parameters String url = "https://www.example.com?param1=value1¶m2=value2¶m1=value3"; Map<String, List<String>> params = resolveQueryParameters(url); // Resulting map structure: // { // "param1" : ["value1", "value3"], // "param2" : ["value2"] // }- Parameters:
url- URL string containing optional query parameters- Returns:
- Non-null and Read-only
Mapwhere each key is a unique parameter name and the value is a list of values associated with that key.
-
resolveMatrixParameters
@Nonnull @Immutable public static java.util.Map<java.lang.String,java.util.List<java.lang.String>> resolveMatrixParameters(java.lang.String url)
Extracts and resolves matrix parameters from the provided URL string.Matrix parameters are typically represented in the URL path using semicolons (;) followed by key-value pairs. This method identifies the segment containing these parameters, parses them, and returns a map where each key is a unique parameter name and the corresponding value is a list of values associated with that key.
Example Usage
// Example 1: URL with matrix parameters String urlWithMatrix = "/path;key1=valueA;key2=valueB;key1=valueC"; Map<String, List<String>> matrixParams = URLUtils.resolveMatrixParameters(urlWithMatrix); // Resulting map structure: // { // "key1" : ["valueA", "valueC"], // "key2" : ["valueB"] // } // Example 2: URL without matrix parameters String urlWithoutMatrix = "/path/resource"; matrixParams = URLUtils.resolveMatrixParameters(urlWithoutMatrix); System.out.println(matrixParams.isEmpty()); // Output: true // Example 3: URL with matrix and query parameters String urlWithBoth = "/path;key=value?queryKey=queryValue"; matrixParams = URLUtils.resolveMatrixParameters(urlWithBoth); System.out.println(matrixParams); // Output: { "key" : ["value"] }- Parameters:
url- The URL string potentially containing matrix parameters.- Returns:
- A non-null and unmodifiable
Mapwhere each key is a unique parameter name and the value is a list of parameter values.
-
normalizePath
@Nullable public static java.lang.String normalizePath(java.lang.String path)
Normalizes a given path by removing redundant slashes or backslashes and standardizing separators.This method ensures that the resulting path uses forward slashes (
/) as separators, regardless of the operating system, and removes any duplicate separator sequences.Example Usage
normalizePath("C:\\Windows\\\\temp") // returns "C:/Windows/temp" normalizePath("C:\\\\Windows\\/temp") // returns "C:/Windows/temp" normalizePath("/home/////index.html") // returns "/home/index.html" normalizePath(null) // returns null normalizePath("") // returns "" normalizePath(" /a//b/c ") // returns "/a/b/c"- Parameters:
path- The input path to be normalized. Can be blank or contain mixed/escaped separators.- Returns:
- A newly resolved, normalized path with standardized separators and no redundant segments.
-
encode
@Nonnull public static java.lang.String encode(java.lang.String value)
Encodes the provided string using URL encoding with the default encoding scheme.This method delegates to
encode(String, String)using the default system encoding, typically "UTF-8". It is suitable for scenarios where uniform encoding behavior is desired without explicitly specifying it.Example Usage
// Encoding a simple string String input = "Hello World!"; String encoded = URLUtils.encode(input); System.out.println(encoded); // Output: Hello+World%21 (assuming UTF-8 as default) // Encoding a string with special characters input = "Español"; encoded = URLUtils.encode(input); System.out.println(encoded); // Output: Espa%F1ol (if default encoding is ISO-8859-1) // Empty input remains unchanged encoded = URLUtils.encode(""); System.out.println(encoded); // Output: "" // Null input will throw IllegalArgumentException try { encoded = URLUtils.encode(null); } catch (IllegalArgumentException e) { System.out.println("Caught expected null value exception"); }- Parameters:
value- The string to encode.- Returns:
- The URL-encoded string using the default encoding.
- Throws:
java.lang.IllegalArgumentException- if the provided value is null or the default encoding is not supported.
-
encode
@Nonnull public static java.lang.String encode(java.lang.String value, java.lang.String encoding) throws java.lang.IllegalArgumentException
Translates a string intoapplication/x-www-form-urlencodedformat using a specific encoding scheme. This method uses the supplied encoding to encode unsafe characters as hexadecimal values.If the provided value is empty or blank, this method returns it unchanged.
Example Usage
// Encoding with UTF-8 String input = "Hello World!"; String encoded = URLUtils.encode(input, "UTF-8"); System.out.println(encoded); // Output: Hello+World%21 // Encoding with ISO-8859-1 input = "Español"; encoded = URLUtils.encode(input, "ISO-8859-1"); System.out.println(encoded); // Output: Espa%F1ol // Empty input encoded = URLUtils.encode("", "UTF-8"); System.out.println(encoded); // Output: "" // Null input will throw IllegalArgumentException try { encoded = URLUtils.encode(null, "UTF-8"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); // Output: java.lang.IllegalArgumentException }- Parameters:
value- the string to encodeencoding- The name of a supported character encoding (e.g., "UTF-8", "ISO-8859-1")- Returns:
- the URL-encoded string
- Throws:
java.lang.IllegalArgumentException- if the value is null or the encoding is not supported- See Also:
URLEncoder.encode(String, String)
-
decode
@Nonnull public static java.lang.String decode(java.lang.String value)
Decodes aapplication/x-www-form-urlencodedstring using the default encoding.This method delegates to
decode(String, String)with the default encoding set for the environment, typically "UTF-8". It is useful for scenarios where uniform decoding behavior is desired without explicitly specifying it.Example Usage
// Decoding a simple URL-encoded string String encoded = "Hello+World%21"; String decoded = URLUtils.decode(encoded); System.out.println(decoded); // Output: Hello World! // Decoding a string encoded with ISO-8859-1 encoded = "Espa%F1ol"; decoded = URLUtils.decode(encoded); System.out.println(decoded); // Output: Español (if default encoding is "ISO-8859-1") // Empty input remains unchanged decoded = URLUtils.decode(""); System.out.println(decoded); // Output: "" // Null input throws an exception try { decoded = URLUtils.decode(null); } catch (IllegalArgumentException e) { System.out.println("Caught expected null value exception"); }- Parameters:
value- The string to decode.- Returns:
- The decoded string using the default encoding.
- Throws:
java.lang.IllegalArgumentException- if the provided value is null or if the default encoding is not supported.
-
decode
@Nonnull public static java.lang.String decode(java.lang.String value, java.lang.String encoding) throws java.lang.IllegalArgumentException
Decodes aapplication/x-www-form-urlencodedstring using a specific encoding scheme. The supplied encoding is used to determine what characters are represented by any consecutive sequences of the form "%xy".Example Usage
// Decoding with UTF-8 String encoded = "Hello%20World%21"; String decoded = URLUtils.decode(encoded, "UTF-8"); System.out.println(decoded); // Output: Hello World! // Decoding with ISO-8859-1 encoded = "Espa%F1ol"; decoded = URLUtils.decode(encoded, "ISO-8859-1"); System.out.println(decoded); // Output: Español // Empty input remains unchanged decoded = URLUtils.decode("", "UTF-8"); System.out.println(decoded); // Output: "" // Null input will throw IllegalArgumentException try { decoded = URLUtils.decode(null, "UTF-8"); } catch (IllegalArgumentException e) { System.out.println("Caught expected null value exception"); }- Parameters:
value- theStringto decodeencoding- The name of a supported character encoding (e.g., "UTF-8", "ISO-8859-1")- Returns:
- the newly decoded
String - Throws:
java.lang.IllegalArgumentException- If character encoding needs to be consulted, but named character encoding is not supported
-
isDirectoryURL
public static boolean isDirectoryURL(java.net.URL url)
Determines whether the specified URL refers to a directory.For "file" protocol URLs, it checks if the corresponding file system resource is a directory. For "jar" protocol URLs, it checks if the referenced archive entry exists and is marked as a directory.
Example Usage
// Example 1: File URL pointing to a directory URL fileDirURL = new URL("file:/path/to/directory/"); boolean isDirectory = URLUtils.isDirectoryURL(fileDirURL); System.out.println(isDirectory); // Output: true // Example 2: JAR URL pointing to a directory within the archive URL jarDirURL = new URL("jar:file:/path/to/archive.jar!/directory/"); isDirectory = URLUtils.isDirectoryURL(jarDirURL); System.out.println(isDirectory); // Output: true // Example 3: JAR URL pointing to a file inside the archive URL jarFileURL = new URL("jar:file:/path/to/archive.jar!/file.txt"); isDirectory = URLUtils.isDirectoryURL(jarFileURL); System.out.println(isDirectory); // Output: false- Parameters:
url- the URL to check- Returns:
trueif the URL refers to a directory; otherwise,false- Throws:
java.lang.NullPointerException- if the provided URL isnull
-
isJarURL
public static boolean isJarURL(java.net.URL url)
Determines if the provided URL refers to a JAR file.If the URL uses the "file" protocol, this method attempts to open the file as a JAR file to verify its validity. If the URL uses the "jar" protocol, it is inherently considered a valid JAR URL.
Example Usage
// Valid JAR URL using "file" protocol URL fileJarURL = new URL("file:/path/to/archive.jar"); boolean result = URLUtils.isJarURL(fileJarURL); System.out.println(result); // Output: true (if the file exists and is a valid JAR) // Valid JAR URL using "jar" protocol URL jarURL = new URL("jar:file:/path/to/archive.jar!/entry/path"); result = URLUtils.isJarURL(jarURL); System.out.println(result); // Output: true // Non-JAR URL URL httpURL = new URL("http://example.com"); result = URLUtils.isJarURL(httpURL); System.out.println(result); // Output: false- Parameters:
url- The URL to check.- Returns:
trueif the URL refers to a valid JAR file; otherwise, returnsfalse.- Throws:
java.lang.NullPointerException- if the provided URL isnull.
-
isArchiveURL
public static boolean isArchiveURL(java.net.URL url)
Determines if the provided URL refers to an archive.This method checks whether the URL's protocol corresponds to known archive types such as "jar", "war", or "ear". For URLs using the "file" protocol, it attempts to open the file as a JAR to verify its validity.
Example Usage
// Valid JAR file URL URL jarFileURL = new URL("file:/path/to/archive.jar"); boolean result = URLUtils.isArchiveURL(jarFileURL); System.out.println(result); // Output: true (if the file exists and is a valid JAR) // Valid WAR file URL URL warFileURL = new URL("war:file:/path/to/application.war!/WEB-INF/web.xml"); result = URLUtils.isArchiveURL(warFileURL); System.out.println(result); // Output: true // Non-archive URL URL httpURL = new URL("http://example.com"); result = URLUtils.isArchiveURL(httpURL); System.out.println(result); // Output: false // Invalid JAR file URL URL invalidJarURL = new URL("file:/path/to/invalid.jar"); result = URLUtils.isArchiveURL(invalidJarURL); System.out.println(result); // Output: false (if the file cannot be opened as a JAR)- Parameters:
url- The URL to check.- Returns:
trueif the URL refers to a valid archive; otherwise, returnsfalse.- Throws:
java.lang.NullPointerException- if the provided URL isnull.
-
toJarFile
@Nullable public static java.util.jar.JarFile toJarFile(java.net.URL url)
Converts the provided URL to aJarFileinstance if it refers to a valid JAR file.This method attempts to open the URL as a JAR file. If the URL uses the "file" protocol, it checks whether the corresponding file exists and is a valid JAR. For other protocols (e.g., "jar"), it tries to extract and open the underlying JAR file.
Example Usage
// Example 1: Valid JAR file URL URL jarURL = new URL("file:/path/to/archive.jar"); JarFile jarFile = URLUtils.toJarFile(jarURL); if (jarFile != null) { System.out.println("Successfully opened JAR file."); } else { System.out.println("Failed to open JAR file."); } // Example 2: Invalid JAR file URL URL invalidURL = new URL("file:/path/to/invalid.jar"); jarFile = URLUtils.toJarFile(invalidURL); System.out.println(jarFile == null); // Output: true // Example 3: URL with "jar" protocol URL urlWithJarProtocol = new URL("jar:file:/path/to/archive.jar!/entry/path"); jarFile = URLUtils.toJarFile(urlWithJarProtocol); System.out.println(jarFile != null); // Output: true- Parameters:
url- The URL to convert into a JAR file.- Returns:
- A non-null
JarFileif the URL refers to a valid JAR file; otherwise, returnsnull. - Throws:
java.lang.NullPointerException- if the provided URL isnull.
-
buildURI
@Nonnull public static java.lang.String buildURI(java.lang.String... paths)
Builds a normalized URI path by concatenating the provided path segments with slashes.This method constructs a URI path by joining all provided path segments using forward slashes ('/'). It ensures that the resulting path is normalized by removing any redundant slashes or backslashes, and standardizing separators to forward slashes regardless of the operating system.
Example Usage
// Example 1: Basic usage with multiple path segments String result = URLUtils.buildURI("users", "profile", "settings"); System.out.println(result); // Output: /users/profile/settings // Example 2: Path with mixed slashes result = URLUtils.buildURI("data\\local", "cache/temp"); System.out.println(result); // Output: /data/local/cache/temp // Example 3: Empty input returns a single slash result = URLUtils.buildURI(); System.out.println(result); // Output: / // Example 4: Null or blank path segments are skipped result = URLUtils.buildURI("home", null, "docs", "", "file.txt"); System.out.println(result); // Output: /home/docs/file.txt- Parameters:
paths- The variable-length array of path segments to be joined into a URI path.- Returns:
- A normalized URI path starting with a forward slash ('/') and containing no duplicate or unnecessary separators.
-
buildMatrixString
@Nullable public static java.lang.String buildMatrixString(java.util.Map<java.lang.String,java.util.List<java.lang.String>> matrixParameters)
Builds a matrix string from the provided map of matrix parameters.This method constructs a string representation of matrix parameters suitable for inclusion in a URL path. The resulting string starts with a semicolon (;) followed by key-value pairs separated by semicolons. The special parameter named
SUB_PROTOCOL_MATRIX_NAMEis excluded from the output.Example Usage
// Example 1: Basic usage with multiple parameters Map<String, List<String>> matrixParams = new LinkedHashMap<>(); matrixParams.put("key1", Arrays.asList("valueA", "valueB")); matrixParams.put("key2", Collections.singletonList("valueC")); matrixParams.put("_sp", Arrays.asList("subproto1", "subproto2")); // This will be skipped String matrixString = URLUtils.buildMatrixString(matrixParams); System.out.println(matrixString); // Output: ;key1=valueA;key1=valueB;key2=valueC// Example 2: Empty input returns null Map<String, List<String>> emptyMap = Collections.emptyMap(); String result = URLUtils.buildMatrixString(emptyMap); System.out.println(result == null); // Output: true- Parameters:
matrixParameters- A map containing matrix parameter names as keys and lists of values as map values. If this map is empty or null, the method returns null.- Returns:
- A string representing the matrix parameters, or null if no valid parameters are provided.
-
buildMatrixString
@Nonnull public static java.lang.String buildMatrixString(java.lang.String name, java.lang.String... values)
Builds a matrix parameter string in the format ";name=value1;name=value2..." from the provided values.This method constructs a string representation of matrix parameters suitable for inclusion in a URL path. Each value results in a separate key-value pair using the same parameter name.
Example Usage
// Example 1: Basic usage with multiple values String result = URLUtils.buildMatrixString("key", "valueA", "valueB"); System.out.println(result); // Output: ;key=valueA;key=valueB // Example 2: Single value result = URLUtils.buildMatrixString("color", "blue"); System.out.println(result); // Output: ;color=blue // Example 3: Null or empty input result = URLUtils.buildMatrixString("empty", null); System.out.println(result == null); // Output: true result = URLUtils.buildMatrixString("empty"); System.out.println(result == null); // Output: true- Parameters:
name- the name of the matrix parametervalues- an array of values to associate with the parameter- Returns:
- a string representing the matrix parameter, or null if no valid values are provided
-
toExternalForm
@Nonnull public static java.lang.String toExternalForm(java.net.URL url) throws java.lang.NullPointerException
Converts the providedURLto its external form as a string, including all components such as protocol, authority, path, matrix parameters, query, and fragment.This method reconstructs the URL in a standardized format, ensuring proper handling of special components like matrix parameters and sub-protocols. It ensures that the resulting string representation is consistent with the original URL structure.
Example Usage
// Example 1: Basic URL with no special components URL url = new URL("http://example.com/path/to/resource"); String externalForm = URLUtils.toExternalForm(url); System.out.println(externalForm); // Output: http://example.com/path/to/resource// Example 2: URL with matrix parameters URL url = new URL("http://example.com/path;key1=valueA;key1=valueB/to/resource"); String externalForm = URLUtils.toExternalForm(url); System.out.println(externalForm); // Output: http://example.com/path;key1=valueA;key1=valueB/to/resource// Example 3: URL with sub-protocol specified via matrix parameter "_sp" URL url = new URL("http://example.com/path;_sp=subproto1;_sp=subproto2/to/resource"); String externalForm = URLUtils.toExternalForm(url); System.out.println(externalForm); // Output: http://example.com/path;_sp=subproto1;_sp=subproto2/to/resource// Example 4: URL with query and fragment URL url = new URL("http://example.com/path?queryKey=queryValue#section1"); String externalForm = URLUtils.toExternalForm(url); System.out.println(externalForm); // Output: http://example.com/path?queryKey=queryValue#section1- Parameters:
url- The non-nullURLobject to convert to an external form string.- Returns:
- A non-null string representing the full external form of the URL, including all components.
- Throws:
java.lang.NullPointerException- if the provided URL is null.
-
getSubProtocol
@Nullable public static java.lang.String getSubProtocol(java.lang.String url)
Extracts the first sub-protocol value from the specified URL string.This method retrieves the list of values associated with the special matrix parameter named
SUB_PROTOCOL_MATRIX_NAMEand returns the first one if available. If no such parameter exists, it returns null.Example Usage
// Example 1: URL with a single sub-protocol String urlWithSingleSubProtocol = "/path;_sp=subproto1/resource"; String subProtocol = URLUtils.getSubProtocol(urlWithSingleSubProtocol); System.out.println(subProtocol); // Output: "subproto1" // Example 2: URL with multiple sub-protocols String urlWithMultipleSubProtocols = "/path;_sp=subproto1;_sp=subproto2/resource"; subProtocol = URLUtils.getSubProtocol(urlWithMultipleSubProtocols); System.out.println(subProtocol); // Output: "subproto1" (only the first one is returned) // Example 3: URL without any sub-protocol String urlWithoutSubProtocol = "/path/to/resource"; subProtocol = URLUtils.getSubProtocol(urlWithoutSubProtocol); System.out.println(subProtocol); // Output: null- Parameters:
url- The URL string potentially containing sub-protocol information.- Returns:
- The first sub-protocol value if present, or null if none is found.
-
resolveSubProtocols
@Nonnull @Immutable public static java.util.List<java.lang.String> resolveSubProtocols(java.net.URL url)
Resolves the list of sub-protocols from the specifiedURL.This method extracts sub-protocol information from the URL's path using matrix parameters. Sub-protocols are identified by the special matrix parameter name
SUB_PROTOCOL_MATRIX_NAME("_sp"). If no such parameter is present, an empty list is returned.Example Usage
// Example 1: URL with multiple sub-protocols URL urlWithMultipleSubProtocols = new URL("http://example.com/path;_sp=subproto1;_sp=subproto2/resource"); List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithMultipleSubProtocols); System.out.println(subProtocols); // Output: [subproto1, subproto2]// Example 2: URL with a single sub-protocol URL urlWithSingleSubProtocol = new URL("http://example.com/path;_sp=subproto1/resource"); List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithSingleSubProtocol); System.out.println(subProtocols); // Output: [subproto1]// Example 3: URL without any sub-protocols URL urlWithoutSubProtocols = new URL("http://example.com/path/to/resource"); List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithoutSubProtocols); System.out.println(subProtocols); // Output: []- Parameters:
url- The non-nullURLobject to extract sub-protocols from.- Returns:
- A non-null list of sub-protocol strings. If no sub-protocols are found, returns an empty list.
- Throws:
java.lang.NullPointerException- if the provided URL is null.
-
resolveSubProtocols
@Nonnull @Immutable public static java.util.List<java.lang.String> resolveSubProtocols(java.lang.String url)
Resolves the list of sub-protocols from the specified URL string.This method extracts sub-protocol information either from the special matrix parameter named
SUB_PROTOCOL_MATRIX_NAME("_sp") or directly from the protocol segment if it contains multiple protocols separated by colons. If no sub-protocols are found, an empty list is returned.Example Usage
// Example 1: URL with multiple sub-protocols via matrix parameters String urlWithMatrixSubProtocols = "/path;_sp=subproto1;_sp=subproto2/resource"; List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithMatrixSubProtocols); System.out.println(subProtocols); // Output: [subproto1, subproto2]// Example 2: URL with a single sub-protocol in the protocol segment String urlWithProtocolSubProtocol = "http:subproto1://example.com/path"; List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithProtocolSubProtocol); System.out.println(subProtocols); // Output: [subproto1]// Example 3: URL with multiple sub-protocols in the protocol segment String urlWithMultipleProtocolSubProtocols = "custom:subproto1:subproto2:path/to/resource"; List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithMultipleProtocolSubProtocols); System.out.println(subProtocols); // Output: [subproto1, s ```ubproto2]// Example 4: URL without any sub-protocols String urlWithoutSubProtocols = "http://example.com/path/to/resource"; List<String> subProtocols = URLUtils.resolveSubProtocols(urlWithoutSubProtocols); System.out.println(subProtocols); // Output: []- Parameters:
url- The URL string potentially containing sub-protocol information.- Returns:
- A non-null list of sub-protocol strings. If no sub-protocols are found, returns an empty list.
-
resolveProtocol
@Nullable public static java.lang.String resolveProtocol(java.lang.String url)
Resolves the protocol from the specified URL string.This method extracts the protocol component from a given URL string by identifying the portion before the first colon (':') character. It ensures that the protocol does not contain any whitespace characters, logging a trace message and returning
nullif such a condition is found.Example Usage
// Example 1: Basic usage with a standard HTTP URL String url = "http://example.com"; String protocol = URLUtils.resolveProtocol(url); System.out.println(protocol); // Output: http // Example 2: URL with sub-protocols in the protocol segment url = "custom:subproto1:subproto2://example.com"; protocol = URLUtils.resolveProtocol(url); System.out.println(protocol); // Output: custom // Example 3: URL with matrix parameters containing sub-protocols url = "/path;_sp=subproto1;_sp=subproto2/resource"; protocol = URLUtils.resolveProtocol(url); System.out.println(protocol); // Output: null (since no protocol exists before the colon) // Example 4: Invalid URL with whitespace in protocol name url = "ht tp://example.com"; protocol = URLUtils.resolveProtocol(url); System.out.println(protocol); // Output: null // Example 5: Blank input returns null protocol = URLUtils.resolveProtocol(" "); System.out.println(protocol); // Output: null- Parameters:
url- The URL string to extract the protocol from.- Returns:
- The resolved protocol if valid; otherwise, returns
null.
-
resolveAuthority
public static java.lang.String resolveAuthority(java.net.URL url)
Resolves and returns the authority component from the providedURL.The authority is defined as the part of the URL after the protocol (e.g., "http" or "ftp") and before the path, query, or fragment. It typically includes host and port information. This method delegates to
resolveAuthority(String)for processing the actual authority string.Example Usage
// Example 1: Basic usage with a simple URL URL url = new URL("http://example.com/path/to/resource"); String authority = URLUtils.resolveAuthority(url); System.out.println(authority); // Output: example.com// Example 2: URL with port number URL urlWithPort = new URL("http://example.com:8080/path/to/resource"); String authority = URLUtils.resolveAuthority(urlWithPort); System.out.println(authority); // Output: example.com:8080// Example 3: URL with user info and port URL urlWithUserInfo = new URL("http://user:[email protected]:9090/path"); authority = URLUtils.resolveAuthority(urlWithUserInfo); System.out.println(authority); // Output: user:[email protected]:9090- Parameters:
url- The non-nullURLobject to extract the authority from.- Returns:
- A non-null string representing the resolved authority part of the URL.
- Throws:
java.lang.NullPointerException- if the provided URL is null.
-
resolveAuthority
@Nullable public static java.lang.String resolveAuthority(java.lang.String authority)
Resolves the authority part from the specified URL string by truncating any matrix parameters.This method removes matrix parameters (identified by a semicolon '
SymbolConstants.SEMICOLON_CHAR') and returns the base authority. It is commonly used to clean up URLs before further processing or comparison.Example Usage
// Example 1: Authority with matrix parameters String authorityWithMatrix = "example.com;param=value"; String resolvedAuthority = URLUtils.resolveAuthority(authorityWithMatrix); System.out.println(resolvedAuthority); // Output: example.com // Example 2: Simple authority without matrix parameters String simpleAuthority = "localhost:8080"; resolvedAuthority = URLUtils.resolveAuthority(simpleAuthority); System.out.println(resolvedAuthority); // Output: localhost:8080 // Example 3: Null or empty input resolvedAuthority = URLUtils.resolveAuthority(""); System.out.println(resolvedAuthority); // Output: (empty string) resolvedAuthority = URLUtils.resolveAuthority(null); System.out.println(resolvedAuthority); // Output: null- Parameters:
authority- The URL authority string potentially containing matrix parameters.- Returns:
- the resolved authority string without matrix parameters, or
nullif the input is null or blank after processing
-
resolvePath
@Nonnull public static java.lang.String resolvePath(java.net.URL url)
Resolves the path component from the specified URL, excluding any matrix parameters.This method delegates to
resolvePath(URL, boolean)with the second argument set to true, ensuring that the returned path includes the archive entry path if present.Example Usage
// Example 1: File URL without matrix parameters URL fileURL = new URL("file:/path/to/resource.txt"); String path = URLUtils.resolvePath(fileURL); System.out.println(path); // Output: /path/to/resource.txt // Example 2: JAR URL with archive entry path URL jarURL = new URL("jar:file:/path/to/archive.jar!/entry/path"); path = URLUtils.resolvePath(jarURL); System.out.println(path); // Output: /path/to/archive.jar!/entry/path // Example 3: URL with matrix parameters (these will be ignored) URL urlWithMatrix = new URL("http://example.com/path;key=value"); path = URLUtils.resolvePath(urlWithMatrix); System.out.println(path); // Output: /path- Parameters:
url- the URL to extract and resolve the path from- Returns:
- the resolved path as a string, excluding matrix parameters
- Throws:
java.lang.NullPointerException- if the provided URL is null
-
attachURLStreamHandlerFactory
public static void attachURLStreamHandlerFactory(java.net.URLStreamHandlerFactory factory)
Attaches the specifiedURLStreamHandlerFactoryto the current JVM.This method ensures that the provided factory is integrated into the existing handler chain. If no global factory is currently set, this method directly sets it as the system-wide factory. If an existing factory is already present and it's not a
CompositeURLStreamHandlerFactory, a new composite factory will be created to encapsulate both the existing and new factories.Example Usage
{@code // Example 1: Setting up a custom URLStreamHandlerFactory for "myproto" protocol public class MyProtoURLStreamHandlerFactory implements URLStreamHandlerFactory {- Parameters:
factory- the URLStreamHandlerFactory to be attached; if null, this method has no effect
-
getURLStreamHandlerFactory
@Nullable public static java.net.URLStreamHandlerFactory getURLStreamHandlerFactory()
Retrieves the current system-wideURLStreamHandlerFactory.This method accesses the private static field "factory" in the
URLclass using reflection. It is useful for inspecting or modifying the existing handler factory chain, especially when integrating custom protocol handlers.Example Usage
// Example 1: Get the current global URLStreamHandlerFactory URLStreamHandlerFactory currentFactory = URLUtils.getURLStreamHandlerFactory(); if (currentFactory != null) { System.out.println("Current factory: " + currentFactory.getClass().getName()); } else { System.out.println("No global factory is currently set."); }// Example 2: Check if the current factory is a CompositeURLStreamHandlerFactory URLStreamHandlerFactory factory = URLUtils.getURLStreamHandlerFactory(); if (factory instanceof CompositeURLStreamHandlerFactory) { System.out.println("The current factory is a composite factory."); } else { System.out.println("The current factory is not a composite factory."); }- Returns:
- The current global
URLStreamHandlerFactory, or null if none is set. - See Also:
URLStreamHandlerFactory,CompositeURLStreamHandlerFactory
-
registerURLStreamHandler
public static void registerURLStreamHandler(ExtendableProtocolURLStreamHandler handler)
Registers the specifiedExtendableProtocolURLStreamHandlerfor its protocol.This method delegates to
registerURLStreamHandler(String, URLStreamHandler)using the protocol obtained from the given handler viaExtendableProtocolURLStreamHandler.getProtocol().Example Usage
{@code // Example: Registering a custom URLStreamHandler for the "myproto" protocol public class MyProtoURLStreamHandler extends ExtendableProtocolURLStreamHandler { public MyProtoURLStreamHandler() { super("myproto"); }- Parameters:
handler- the handler to register for its protocol- Throws:
java.lang.NullPointerException- if the provided handler is null
-
registerURLStreamHandler
public static void registerURLStreamHandler(java.lang.String protocol, java.net.URLStreamHandler handler)Registers aURLStreamHandlerfor the specified protocol.This method ensures that the provided handler is associated with the given protocol and integrated into the system-wide URL stream handler mechanism. If no global factory is currently set, a new
MutableURLStreamHandlerFactorywill be created, and the handler will be registered with it. If there's an existing factory, this method attempts to locate or create a composite structure to include the new handler while preserving existing ones.Example Usage
{@code // Example 1: Registering a custom URLStreamHandler for "myproto" protocol public class MyProtoURLStreamHandler extends URLStreamHandler {- Parameters:
protocol- the name of the protocol for which the handler is being registeredhandler- the URLStreamHandler instance to register; if null, this method has no effect
-
close
public static void close(java.net.URLConnection conn)
Closes the specified URL connection gracefully.If the provided connection is an instance of
HttpURLConnection, it will be disconnected using itsdisconnect()method. This ensures proper resource cleanup for HTTP connections.Example Usage
URL url = new URL("https://example.com"); URLConnection conn = url.openConnection(); try { // Use the connection } finally { URLUtils.close(conn); }- Parameters:
conn- The URL connection to close; may be null.
-
truncateMatrixString
protected static java.lang.String truncateMatrixString(java.lang.String value)
-
indexOfMatrixString
protected static int indexOfMatrixString(java.lang.String value)
-
getMutableURLStreamHandlerFactory
protected static MutableURLStreamHandlerFactory getMutableURLStreamHandlerFactory()
-
getMutableURLStreamHandlerFactory
protected static MutableURLStreamHandlerFactory getMutableURLStreamHandlerFactory(boolean createIfAbsent)
-
clearURLStreamHandlerFactory
protected static void clearURLStreamHandlerFactory()
-
reformProtocol
protected static java.lang.String reformProtocol(java.lang.String protocol, java.lang.String spec)
-
reformProtocol
protected static java.lang.String reformProtocol(java.lang.String protocol, java.util.List<java.lang.String> subProtocols)
-
resolveParameters
protected static java.util.Map<java.lang.String,java.util.List<java.lang.String>> resolveParameters(java.lang.String paramsString, char separatorChar)
-
buildString
protected static java.lang.String buildString(java.lang.String name, java.lang.String[] values, char separator, char joiner)
-
getFirst
protected static java.lang.String getFirst(java.util.Map<java.lang.String,java.util.List<java.lang.String>> parameters, java.lang.String name)
-
-