-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere net URLUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.net | Since: 1.0.0
Source:
microsphere-java-core/src/main/java/io/microsphere/net/URLUtils.java
URL Utility class
public abstract class URLUtils implements UtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.1.10-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
// 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());
}// 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// 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// 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)// 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"]
// }// 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"] }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"// 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");
}// 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
}// 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");
}// 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");
}// 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// 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// 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)// Valid archive protocols
boolean result = URLUtils.isArchiveProtocol("jar");
System.out.println(result); // Output: true
result = URLUtils.isArchiveProtocol("war");
System.out.println(result); // Output: true
// Non-archive protocol
result = URLUtils.isArchiveProtocol("http");
System.out.println(result); // Output: false
// Case-sensitive check
result = URLUtils.isArchiveProtocol("JAR");
System.out.println(result); // Output: false// 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// 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// 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// 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// 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// 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: []// 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: []Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.net.URLUtils;| Method | Description |
|---|---|
ofURL |
The default encoding : "UTF-8" |
resolveArchiveEntryPath |
Resolves the archive entry path from the given URL. |
resolveBasePath |
Resolves the base path from the specified URL. |
resolveArchiveFile |
Resolves the archive file from the specified URL. |
normalizePath |
Resolve the query parameters Map from specified URL. The parameter name is used as the key, and the list of paramet... |
encode |
Encodes the provided string using URL encoding with the default encoding scheme. |
encode |
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme. |
decode |
Decodes a application/x-www-form-urlencoded string using the default encoding. |
decode |
Decodes a application/x-www-form-urlencoded string using a specific encoding scheme. The supplied |
isDirectoryURL |
Determines whether the specified URL refers to a directory. |
isJarURL |
Determines if the provided URL refers to a JAR file. |
isArchiveURL |
Determines if the provided URL refers to an archive. |
isArchiveProtocol |
Determines whether the specified protocol represents an archive type. |
buildURI |
Builds a normalized URI path by concatenating the provided path segments with slashes. |
buildMatrixString |
Builds a matrix string from the provided map of matrix parameters. |
buildMatrixString |
Builds a matrix parameter string in the format ";name=value1;name=value2..." from the provided values. |
toExternalForm |
Converts the provided URL to its external form as a string, including all components such as protocol, |
getSubProtocol |
Extracts the first sub-protocol value from the specified URL string. |
resolveSubProtocols |
Resolves the list of sub-protocols from the specified URL. |
resolveSubProtocols |
Resolves the list of sub-protocols from the specified URL string. |
public static URL ofURL(String url)The default encoding : "UTF-8" / public static final String DEFAULT_ENCODING = FILE_ENCODING;
/**
The empty array of URL
/
public static String resolveArchiveEntryPath(URL archiveFileURL)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 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
`
public static String resolveBasePath(URL url)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 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
`
public static File resolveArchiveFile(URL resourceURL)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 calls #doResolveArchiveFile(URL) to handle other protocols like "jar".
`// 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)
`
public static String normalizePath(final String path)Resolve the query parameters Map from specified URL. The parameter name is used as the key, and the list of parameter values is used as the value.
`// Example URL with query parameters
String url = "https://www.example.com?param1=value1¶m2=value2¶m1=value3";
Map> params = resolveQueryParameters(url);
// Resulting map structure:
// {
// "param1" : ["value1", "value3"],
// "param2" : ["value2"]
// `
}
public static String encode(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.
`// 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");
}
}
public static String encode(String value, String encoding)Translates a string into application/x-www-form-urlencoded format 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.
`// 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
}
}
public static String decode(String value)Decodes a application/x-www-form-urlencoded string 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.
`// 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");
}
}
public static String decode(String value, String encoding)Decodes a application/x-www-form-urlencoded string using a specific encoding scheme. The supplied
encoding is used to determine what characters are represented by any consecutive sequences of the form
"%*xy*".
`// 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");
}
}
public static boolean isDirectoryURL(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 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
`
public static boolean isJarURL(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.
`// 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
`
public static boolean isArchiveURL(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.
`// 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)
`
public static boolean isArchiveProtocol(String protocol)Determines whether the specified protocol represents an archive type.
This method checks if the given protocol matches known archive protocols such as "jar", "zip", "war", or "ear". These protocols are commonly used to reference compressed or packaged resources.
`// Valid archive protocols
boolean result = URLUtils.isArchiveProtocol("jar");
System.out.println(result); // Output: true
result = URLUtils.isArchiveProtocol("war");
System.out.println(result); // Output: true
// Non-archive protocol
result = URLUtils.isArchiveProtocol("http");
System.out.println(result); // Output: false
// Case-sensitive check
result = URLUtils.isArchiveProtocol("JAR");
System.out.println(result); // Output: false
`
public static String buildURI(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 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
`
public static String buildMatrixString(Map<String, List<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_NAME is excluded from the output.
`// Example 1: Basic usage with multiple parameters
Map> 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> emptyMap = Collections.emptyMap(); String result = URLUtils.buildMatrixString(emptyMap); System.out.println(result == null); // Output: true `
public static String buildMatrixString(String name, 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 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
`
public static String toExternalForm(URL url)Converts the provided URL to 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 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
`
public static String getSubProtocol(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_NAME and returns the first one if available. If no such
parameter exists, it returns null.
`// 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 `
public static List<String> resolveSubProtocols(URL url)Resolves the list of sub-protocols from the specified URL.
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 1: URL with multiple sub-protocols
URL urlWithMultipleSubProtocols = new URL("http://example.com/path;_sp=subproto1;_sp=subproto2/resource");
List 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 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 subProtocols = URLUtils.resolveSubProtocols(urlWithoutSubProtocols);
System.out.println(subProtocols); // Output: []
`
public static List<String> resolveSubProtocols(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 1: URL with multiple sub-protocols via matrix parameters String urlWithMatrixSubProtocols = "/path;_sp=subproto1;_sp=subproto2/resource"; List 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 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 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 subProtocols = URLUtils.resolveSubProtocols(urlWithoutSubProtocols); System.out.println(subProtocols); // Output: [] `
URLURLEncoderURLDecoder
This documentation was auto-generated from the source code of microsphere-java.
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
jdk-tools
lang-model
- AnnotatedElementJSONElementVisitor
- AnnotationUtils
- ClassUtils
- ConstructorUtils
- ElementUtils
- ExecutableElementComparator
- FieldUtils
- JSONAnnotationValueVisitor
- JSONElementVisitor
- LoggerUtils
- MemberUtils
- MessagerUtils
- MethodUtils
- ResolvableAnnotationValueVisitor
- StringAnnotationValue
- TypeUtils
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl