Created
February 27, 2023 03:40
-
-
Save joshlong/64c0925df73d9159b7ff836f22f398b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hollywood.framework; | |
import org.junit.jupiter.api.Assertions; | |
import org.junit.jupiter.api.Test; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.test.context.SpringBootTest; | |
import org.springframework.core.io.Resource; | |
import org.springframework.core.io.ResourceLoader; | |
import org.springframework.core.io.support.ResourcePatternResolver; | |
import org.springframework.util.FileCopyUtils; | |
import org.springframework.util.SystemPropertyUtils; | |
import java.io.InputStreamReader; | |
import static java.lang.System.out; | |
@SpringBootTest | |
class ResourceTest { | |
@Test | |
void resources(@Autowired ResourceLoader resourceLoader, @Autowired ResourcePatternResolver resourcePatternResolver) throws Exception { | |
log(resourceLoader.getResource(SystemPropertyUtils.resolvePlaceholders("file://${HOME}/Desktop/test.txt"))); | |
log(resourceLoader.getResource("classpath:/my/test.txt")); | |
log(resourceLoader.getResource("https://start.spring.io")); | |
var resources = resourcePatternResolver.getResources( | |
ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "application.properties"); | |
for (var r : resources) | |
out.println(r.getURI()); | |
Assertions.assertTrue(resources.length > 0, "there should be at least one file of this name"); | |
} | |
private static String truncate(String text) { | |
var max = 20; | |
return (text.length() > max) ? text.substring(0, max) + "..." : text; | |
} | |
private static void log(Resource resource) { | |
try (var in = new InputStreamReader(resource.getInputStream())) { | |
Assertions.assertTrue(resource.exists(), "the resource with the url [" + resource.getURI() + "] must exist"); | |
var string = FileCopyUtils.copyToString(in).trim(); | |
out.println("read: [" + truncate(string) + "] from [" + resource.getURI() + "]"); | |
}// | |
catch (Throwable t) { | |
out.println("got an error! " + t.getMessage()); // don't care .. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment