import java.io.IOException;
import java.net.URL;
import java.util.logging.Logger;
public class ResourceLoader {
private static final Logger logger = Logger.getLogger(ResourceLoader.class.getName());
/**
* Loads resources from URLs provided as URL parameters.
*
* @param resourceUrls An array of URLs pointing to resources.
* @return A map where keys are resource names (extracted from URL paths)
* and values are the content of the resources as byte arrays.
* Returns an empty map if no URLs are provided or if an error occurs.
*/
public static java.util.Map<String, byte[]> loadResources(String[] resourceUrls) {
java.util.Map<String, byte[]> resources = new java.util.HashMap<>();
if (resourceUrls == null || resourceUrls.length == 0) {
logger.info("No resource URLs provided. Returning empty map.");
return resources;
}
for (String url : resourceUrls) {
if (url == null || url.trim().isEmpty()) {
logger.warning("Skipping null or empty URL.");
continue;
}
try {
URL resourceUrl = new URL(url);
byte[] resourceBytes = fetchResource(resourceUrl);
if (resourceBytes != null) {
// Extract resource name from URL path
String resourceName = extractResourceName(resourceUrl.getPath());
resources.put(resourceName, resourceBytes);
logger.info("Successfully loaded resource: " + resourceName + " from " + url);
} else {
logger.error("Failed to fetch resource from " + url);
}
} catch (IOException e) {
logger.error("Error loading resource from " + url, e);
}
}
return resources;
}
/**
* Fetches the content of a resource from a URL.
*
* @param url The URL of the resource.
* @return The content of the resource as a byte array, or null if an error occurs.
* @throws IOException if an I/O error occurs during the fetch.
*/
private static byte[] fetchResource(URL url) throws IOException {
try (java.io.InputStream in = url.openStream();
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
return out.toByteArray();
}
}
/**
* Extracts the resource name from the URL path.
*
* @param path The URL path.
* @return The extracted resource name.
*/
private static String extractResourceName(String path) {
String[] parts = path.split("/");
if (parts.length > 1) {
return parts[parts.length - 1];
} else {
return "unknown"; // Handle cases where the path is just the root
}
}
public static void main(String[] args) {
// Example usage
String[] urls = {
"https://www.example.com/image.jpg",
"https://www.example.com/data.txt",
"https://www.example.com/nonexistent.pdf",
"invalid_url" //Example of an invalid url.
};
java.util.Map<String, byte[]> loadedResources = loadResources(urls);
if (loadedResources != null) {
for (java.util.Map.Entry<String, byte[]> entry : loadedResources.entrySet()) {
System.out.println("Resource: " + entry.getKey() + ", Size: " + entry.getValue().length + " bytes");
}
}
}
}
Add your comment