static String readString(final ClassLoader loader, final String path) { return Try.with(() -> loader.getResourceAsStream("whoops/" + path)) .apply(stream -> new String(ByteStreams.toByteArray(stream), StandardCharsets.UTF_8)) .get(); }
@Override public Collection<Import> apply(final String url, final Import previous) { String fname = nameWithExtension(url); List<String> segments = Splitter.on('/').trimResults().omitEmptyStrings() .splitToList(previous.getAbsoluteUri().toString()); String relative = segments.subList(0, segments.size() - 1).stream() .collect(Collectors.joining("/", "/", "")); return Arrays.asList(relative + fname, fname) .stream() .map(resolver::apply) .filter(it -> it != null) .findFirst() .map(throwingFunction(it -> Try.with(it.toURL()::openStream) .apply(in -> new String(ByteStreams.toByteArray(in), StandardCharsets.UTF_8)) .map(content -> Arrays.asList(new Import(it, it, content))) .get() )) .orElse(null); }
/** * Functional try-with-resources with 3 inputs. * * @param r1 Input resource. * @param r2 Input resource. * @param r3 Input resource. * @param <R1> Resource type. * @param <R2> Resource type. * @param <R3> Resource type. * @return A resource handler. */ public final static <R1 extends AutoCloseable, R2 extends AutoCloseable, R3 extends AutoCloseable> ResourceHandler3<R1, R2, R3> of( R1 r1, R2 r2, R3 r3) { return with(() -> r1, () -> r2, () -> r3); }
/** * Functional try-with-resources with 4 inputs. * * @param r1 Input resource. * @param r2 Input resource. * @param r3 Input resource. * @param r4 Input resource. * @param <R1> Resource type. * @param <R2> Resource type. * @param <R3> Resource type. * @param <R4> Resource type. * @return A resource handler. */ public final static <R1 extends AutoCloseable, R2 extends AutoCloseable, R3 extends AutoCloseable, R4 extends AutoCloseable> ResourceHandler4<R1, R2, R3, R4> of( R1 r1, R2 r2, R3 r3, R4 r4) { return with(() -> r1, () -> r2, () -> r3, () -> r4); }
/** * Functional try-with-resources: * * <pre>{@code * InputStream in = ...; * OutputStream out = ...; * * Try.of(in, out) * .run((from, to) -> copy(from, to)) * .onFailure(Throwable::printStacktrace); * * }</pre> * * @param r1 Input resource. * @param r2 Input resource. * @param <R1> Resource type. * @param <R2> Resource type. * @return A resource handler. */ public final static <R1 extends AutoCloseable, R2 extends AutoCloseable> ResourceHandler2<R1, R2> of( R1 r1, R2 r2) { return with(() -> r1, () -> r2); }
return with(() -> r1);
static String readString(final ClassLoader loader, final String path) { return Try.with(() -> loader.getResourceAsStream("whoops/" + path)) .apply(stream -> new String(ByteStreams.toByteArray(stream), StandardCharsets.UTF_8)) .get(); }