Skip to content

Instantly share code, notes, and snippets.

@joshlong
Created February 27, 2023 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshlong/64c0925df73d9159b7ff836f22f398b7 to your computer and use it in GitHub Desktop.
Save joshlong/64c0925df73d9159b7ff836f22f398b7 to your computer and use it in GitHub Desktop.
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