Create UrlResource factory methods that throw unchecked exceptions

UrlResource constructors throw checked exceptions which makes it
difficult to use them in java.util.Stream and java.util.Optional APIs
or other scenarios when a checked IOException is undesirable.

To support such use cases, this commit introduces `from(URI)` and
`from(String)` factory methods in UrlResource that throw
UncheckedIOExceptions.

Closes gh-28501
This commit is contained in:
Sam Brannen
2022-05-23 14:22:35 +02:00
parent 4515180195
commit f07e7ab39d
2 changed files with 62 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -208,6 +208,21 @@ class ResourceTests {
relative4::lastModified);
}
@Test
void urlResourceFactoryMethods() throws IOException {
Resource resource1 = new UrlResource("file:core/io/Resource.class");
Resource resource2 = UrlResource.from("file:core/io/Resource.class");
Resource resource3 = UrlResource.from(resource1.getURI());
assertThat(resource2.getURL()).isEqualTo(resource1.getURL());
assertThat(resource3.getURL()).isEqualTo(resource1.getURL());
assertThat(UrlResource.from("file:core/../core/io/./Resource.class")).isEqualTo(resource1);
assertThat(UrlResource.from("file:/dir/test.txt?argh").getFilename()).isEqualTo("test.txt");
assertThat(UrlResource.from("file:\\dir\\test.txt?argh").getFilename()).isEqualTo("test.txt");
assertThat(UrlResource.from("file:\\dir/test.txt?argh").getFilename()).isEqualTo("test.txt");
}
@Test
void classPathResourceWithRelativePath() throws IOException {
Resource resource = new ClassPathResource("dir/");