Skip to content

Commit

Permalink
Add Uncheck.getAsInt(IOIntSupplier, Supplier<String>)
Browse files Browse the repository at this point in the history
  • Loading branch information
garydgregory committed Jun 24, 2023
1 parent d6e836d commit c6d891e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/changes/changes.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ The <action> type attribute can be add,update,fix,remove.
Add IOIntSupplier.
</action>
<action dev="ggregory" type="add" due-to="Gary Gregory">
Add Uncheck.getAsInt(IOIntSupplier).
Add IOLongSupplier.
</action>
<action dev="ggregory" type="add" due-to="Gary Gregory">
Add IOLongSupplier.
Add Uncheck.getAsInt(IOIntSupplier [, Supplier&lt;String&gt;]).
</action>
<action dev="ggregory" type="add" due-to="Gary Gregory">
Add Uncheck.getAsLong(IOLongSupplier).
Expand Down
17 changes: 17 additions & 0 deletions src/main/java/org/apache/commons/io/function/Uncheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,23 @@ public static int getAsInt(final IOIntSupplier supplier) {
}
}

/**
* Gets the result from an IO int supplier.
*
* @param supplier Supplies the return value.
* @param message The UncheckedIOException message if an I/O error occurs.
* @return result from the supplier.
* @throws UncheckedIOException if an I/O error occurs.
* @since 2.14.0
*/
public static int getAsInt(final IOIntSupplier supplier, final Supplier<String> message) {
try {
return supplier.getAsInt();
} catch (final IOException e) {
throw wrap(e, message);
}
}

/**
* Gets the result from an IO long supplier.
*
Expand Down
19 changes: 19 additions & 0 deletions src/test/java/org/apache/commons/io/function/UncheckTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,25 @@ public void testGetAsInt() {
assertEquals(1, atomicInt.get());
}

@Test
public void testGetAsIntMessage() {
// No exception
assertThrows(UncheckedIOException.class, () -> Uncheck.getAsInt(() -> {
throw new IOException();
}, () -> CUSTOM_MESSAGE));
assertThrows(UncheckedIOException.class, () -> Uncheck.getAsInt(TestConstants.THROWING_IO_INT_SUPPLIER, () -> CUSTOM_MESSAGE));
assertEquals(1, Uncheck.getAsInt(() -> TestUtils.compareAndSetThrowsIO(atomicInt, 1), () -> CUSTOM_MESSAGE));
assertEquals(1, atomicInt.get());
// exception
final IOException expected = new IOException(CAUSE_MESSAGE);
try {
Uncheck.getAsInt(() -> new BrokenInputStream(expected).read(), () -> CUSTOM_MESSAGE);
fail();
} catch (final UncheckedIOException e) {
assertUncheckedIOException(expected, e);
}
}

/**
* Tests {@link Uncheck#get(IOSupplier, Supplier)}.
*/
Expand Down

0 comments on commit c6d891e

Please sign in to comment.