/** * Closes the underlying reader. * * @throws UncheckedIOException if an IO exception occurs */ @Override public void close() { Unchecked.wrap(() -> reader.close()); }
/** * Obtains an instance of the specified named type by name. * <p> * This method operates by reflection. * It requires a static method {@code of(String)} method to be present on the type specified. * If the method does not exist an exception is thrown. * * @param <T> the named type * @param type the named type with the {@code of(String)} method * @param name the name to find * @return the instance of the named type * @throws IllegalArgumentException if the specified name could not be found */ public static <T extends Named> T of(Class<T> type, String name) { return Unchecked.wrap(() -> { Method method = type.getMethod("of", String.class); return type.cast(method.invoke(null, name)); }); }
/** * 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); } }); }
public void test_wrap_runnable1() { // cannot use assertThrows() here try { Unchecked.wrap((CheckedRunnable) () -> { throw new IOException(); }); fail(); } catch (UncheckedIOException ex) { // success } }
public void test_wrap_supplier2() { // cannot use assertThrows() here try { Unchecked.wrap((CheckedSupplier<String>) () -> { throw new Exception(); }); fail(); } catch (RuntimeException ex) { // success } }
public void test_wrap_runnable2() { // cannot use assertThrows() here try { Unchecked.wrap((CheckedRunnable) () -> { throw new Exception(); }); fail(); } catch (RuntimeException ex) { // success } }
public void test_wrap_supplier() { // cannot use assertThrows() here try { Unchecked.wrap((CheckedSupplier<String>) () -> { throw new IOException(); }); fail(); } catch (UncheckedIOException ex) { // success } }
/** * Creates an instance from another byte source. * * @param other the other byte source * @return the byte source * @throws UncheckedIOException if an IO error occurs */ public static ArrayByteSource from(ByteSource other) { if (other instanceof ArrayByteSource) { return (ArrayByteSource) other; } return new ArrayByteSource(Unchecked.wrap(() -> other.read())); }
/** * Obtains an ordered list of resource locators. * <p> * This finds the all files with the specified name in the configuration directories. * The result is ordered from the lowest priority (base) file to the highest priority (application) file. * The result will always contain at least one file, but it may contain more than one. * * @param resourceName the resource name * @return the resource locators * @throws UncheckedIOException if an IO exception occurs * @throws IllegalStateException if there is a configuration error */ public static List<ResourceLocator> orderedResources(String resourceName) { ArgChecker.notNull(resourceName, "resourceName"); return Unchecked.wrap(() -> orderedResources0(resourceName)); }
/** * Checks whether there is another row in the CSV file. * * @return true if there is another row, false if not * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ @Override public boolean hasNext() { if (nextRow != null) { return true; } else { String line = null; while ((line = Unchecked.wrap(() -> reader.readLine())) != null) { currentLineNumber++; ImmutableList<String> fields = CsvFile.parseLine(line, currentLineNumber, separator); if (!fields.isEmpty()) { nextRow = new CsvRow(headers, searchHeaders, currentLineNumber, fields); return true; } } return false; } }
/** * Outputs the report table in CSV format. * * @param report the report * @param out the output stream to write to */ @SuppressWarnings("resource") public void writeCsv(R report, OutputStream out) { OutputStreamWriter outputWriter = new OutputStreamWriter(out, StandardCharsets.UTF_8); CsvOutput csvOut = CsvOutput.safe(outputWriter); csvOut.writeLine(report.getColumnHeaders()); IntStream.range(0, report.getRowCount()) .mapToObj(rowIdx -> formatRow(report, rowIdx, ReportOutputFormat.CSV)) .forEach(csvOut::writeLine); Unchecked.wrap(outputWriter::flush); }
/** * Capture system err for testing. * <p> * This returns the output from calls to {@code System.err}. * This is thread-safe, providing that no other utility alters system out. * <p> * For example: * <pre> * String sysErr = captureSystemErr(() -> myCode); * </pre> * * @param runner the lambda containing the code to test * @return the captured output */ public static synchronized String caputureSystemErr(Runnable runner) { // it would be possible to use some form of thread-local PrintStream to increase concurrency, // but that should be done only if synchronized is insufficient assertNotNull(runner, "caputureSystemErr() called with null Runnable"); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); PrintStream ps = Unchecked.wrap(() -> new PrintStream(baos, false, UTF_8)); PrintStream old = System.err; try { System.setErr(ps); runner.run(); System.err.flush(); } finally { System.setErr(old); } return Unchecked.wrap(() -> baos.toString(UTF_8)); }
/** * Capture system out for testing. * <p> * This returns the output from calls to {@code System.out}. * This is thread-safe, providing that no other utility alters system out. * <p> * For example: * <pre> * String sysOut = captureSystemOut(() -> myCode); * </pre> * * @param runner the lambda containing the code to test * @return the captured output */ public static synchronized String caputureSystemOut(Runnable runner) { // it would be possible to use some form of thread-local PrintStream to increase concurrency, // but that should be done only if synchronized is insufficient assertNotNull(runner, "caputureSystemOut() called with null Runnable"); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); PrintStream ps = Unchecked.wrap(() -> new PrintStream(baos, false, UTF_8)); PrintStream old = System.out; try { System.setOut(ps); runner.run(); System.out.flush(); } finally { System.setOut(old); } return Unchecked.wrap(() -> baos.toString(UTF_8)); }
/** * Parses the specified source as a CSV file where the separator is specified and might not be a comma. * <p> * This overload allows the separator to be controlled. * For example, a tab-separated file is very similar to a CSV file, the only difference is the separator. * <p> * This method opens the CSV file for reading. * The caller is responsible for closing it by calling {@link #close()}. * * @param source the file resource * @param headerRow whether the source has a header row, an empty source must still contain the header * @param separator the separator used to separate each field, typically a comma, but a tab is sometimes used * @return the CSV file * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ public static CsvIterator of(CharSource source, boolean headerRow, char separator) { ArgChecker.notNull(source, "source"); @SuppressWarnings("resource") BufferedReader reader = Unchecked.wrap(() -> source.openBufferedStream()); return create(reader, headerRow, separator); }
/** * Parses the specified source as an INI file. * <p> * This parses the specified character source expecting an INI file format. * The resulting instance can be queried for each section in the file. * <p> * INI files sometimes contain a Unicode Byte Order Mark. * Callers are responsible for handling this, such as by using {@link UnicodeBom}. * * @param source the INI file resource * @return the INI file * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ public static IniFile of(CharSource source) { ArgChecker.notNull(source, "source"); ImmutableList<String> lines = Unchecked.wrap(() -> source.readLines()); ImmutableMap<String, ImmutableListMultimap<String, String>> parsedIni = parse(lines); ImmutableMap.Builder<String, PropertySet> builder = ImmutableMap.builder(); parsedIni.forEach((sectionName, sectionData) -> builder.put(sectionName, PropertySet.of(sectionData))); return new IniFile(builder.build()); }
/** * Parses the specified source as a CSV file where the separator is specified and might not be a comma. * <p> * This overload allows the separator to be controlled. * For example, a tab-separated file is very similar to a CSV file, the only difference is the separator. * <p> * CSV files sometimes contain a Unicode Byte Order Mark. * Callers are responsible for handling this, such as by using {@link UnicodeBom}. * * @param source the file resource * @param headerRow whether the source has a header row, an empty source must still contain the header * @param separator the separator used to separate each field, typically a comma, but a tab is sometimes used * @return the CSV file * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ public static CsvFile of(CharSource source, boolean headerRow, char separator) { ArgChecker.notNull(source, "source"); List<String> lines = Unchecked.wrap(() -> source.readLines()); return create(lines, headerRow, separator); }
return Unchecked.wrap(() -> { try (InputStream in = source.openBufferedStream()) { XMLStreamReader xmlReader = xmlInputFactory().createXMLStreamReader(in);
/** * Parses the specified reader as a CSV file where the separator is specified and might not be a comma. * <p> * This factory method takes a {@link Reader}. * Callers are encouraged to use {@link CharSource} instead of {@code Reader} * as it allows the resource to be safely managed. * <p> * This factory method allows the separator to be controlled. * For example, a tab-separated file is very similar to a CSV file, the only difference is the separator. * <p> * CSV files sometimes contain a Unicode Byte Order Mark. * Callers are responsible for handling this, such as by using {@link UnicodeBom}. * * @param reader the file resource * @param headerRow whether the source has a header row, an empty source must still contain the header * @param separator the separator used to separate each field, typically a comma, but a tab is sometimes used * @return the CSV file * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ public static CsvFile of(Reader reader, boolean headerRow, char separator) { ArgChecker.notNull(reader, "source"); List<String> lines = Unchecked.wrap(() -> CharStreams.readLines(reader)); return create(lines, headerRow, separator); }
/** * Parses the specified source as a properties file. * <p> * This parses the specified character source expecting a properties file format. * The resulting instance can be queried for each key and value. * <p> * Properties files sometimes contain a Unicode Byte Order Mark. * Callers are responsible for handling this, such as by using {@link UnicodeBom}. * * @param source the properties file resource * @return the properties file * @throws UncheckedIOException if an IO exception occurs * @throws IllegalArgumentException if the file cannot be parsed */ public static PropertiesFile of(CharSource source) { ArgChecker.notNull(source, "source"); ImmutableList<String> lines = Unchecked.wrap(() -> source.readLines()); PropertySet keyValues = parse(lines); return new PropertiesFile(keyValues); }