resource-manager/resource-manager-api/src/main/java/de/nclazz/resources/Resource.java

68 lines
1.9 KiB
Java

package de.nclazz.resources;
import de.nclazz.resources.protocol.ClasspathResourceHandler;
import de.nclazz.resources.protocol.CustomStreamHandlerFactory;
import lombok.NonNull;
import lombok.SneakyThrows;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Optional;
import java.util.function.Supplier;
import static de.nclazz.commons.func.Checked.checked;
public class Resource {
static {
// TODO not really a good place here is it...
URL.setURLStreamHandlerFactory(new CustomStreamHandlerFactory("classpath", new ClasspathResourceHandler()));
}
private final Supplier<InputStream> streamSupplier;
public Resource(Supplier<InputStream> streamSupplier) {
this.streamSupplier = streamSupplier;
}
public Optional<InputStream> getInputStream() {
if (this.streamSupplier != null) {
return Optional.ofNullable(this.streamSupplier.get());
}
return Optional.empty();
}
public boolean exists() {
if(this.streamSupplier == null) return false;
try(InputStream stream = this.streamSupplier.get()) {
return stream != null && stream.read() != -1;
}catch(Exception e) {
return false;
}
}
public static Resource fromFile(@NonNull File file) {
return new Resource(checked(() -> new FileInputStream(file)));
}
public static Resource fromStream(@NonNull InputStream stream) {
return new Resource(() -> stream);
}
public static Resource fromClasspath(String resourceName) {
return fromStream(Resource.class.getResourceAsStream(resourceName));
}
public static Resource fromURL(@NonNull URL url) {
return new Resource(checked(url::openStream));
}
@SneakyThrows
public static Resource load(@NonNull String url) {
return fromURL(new URL(url));
}
}