/** * Converts checked exceptions to unchecked based on the {@code Supplier} interface. * <p> * This wraps the specified supplier returning an instance that handles checked exceptions. * If a checked exception is thrown it is converted to an {@link UncheckedIOException} * or {@link RuntimeException} as appropriate. * * @param <R> the result type of the supplier * @param supplier the supplier to be decorated * @return the supplier instance that handles checked exceptions */ public static <R> Supplier<R> supplier(CheckedSupplier<R> supplier) { return () -> { try { return supplier.get(); } catch (Throwable ex) { throw propagate(ex); } }; }
/** * Wraps a block of code, converting checked exceptions to unchecked. * <pre> * Unchecked.wrap(() -> { * // any code that throws a checked exception * } * </pre> * <p> * If a checked exception is thrown it is converted to an {@link UncheckedIOException} * or {@link RuntimeException} as appropriate. * * @param <T> the type of the result * @param block the code block to wrap * @return the result of invoking the block * @throws UncheckedIOException if an IO exception occurs * @throws RuntimeException if an exception occurs */ public static <T> T wrap(CheckedSupplier<T> block) { try { return block.get(); } catch (Throwable ex) { throw propagate(ex); } }
/** * Creates an instance from an input stream. * <p> * This method use the supplier to open the input stream, extract the bytes and close the stream. * It is intended that invoking the supplier opens the stream. * It is not intended that an already open stream is supplied. * * @param inputStreamSupplier the supplier of the input stream * @return the byte source * @throws UncheckedIOException if an IO error occurs */ public static ArrayByteSource from(CheckedSupplier<InputStream> inputStreamSupplier) { return Unchecked.wrap(() -> { try (InputStream in = inputStreamSupplier.get()) { byte[] bytes = Unchecked.wrap(() -> ByteStreams.toByteArray(in)); return new ArrayByteSource(bytes); } }); }