Skip to content

Commit c6d891e

Browse files
committed
Add Uncheck.getAsInt(IOIntSupplier, Supplier<String>)
1 parent d6e836d commit c6d891e

3 files changed

Lines changed: 38 additions & 2 deletions

File tree

src/changes/changes.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,10 @@ The <action> type attribute can be add,update,fix,remove.
6565
Add IOIntSupplier.
6666
</action>
6767
<action dev="ggregory" type="add" due-to="Gary Gregory">
68-
Add Uncheck.getAsInt(IOIntSupplier).
68+
Add IOLongSupplier.
6969
</action>
7070
<action dev="ggregory" type="add" due-to="Gary Gregory">
71-
Add IOLongSupplier.
71+
Add Uncheck.getAsInt(IOIntSupplier [, Supplier&lt;String&gt;]).
7272
</action>
7373
<action dev="ggregory" type="add" due-to="Gary Gregory">
7474
Add Uncheck.getAsLong(IOLongSupplier).

src/main/java/org/apache/commons/io/function/Uncheck.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,23 @@ public static int getAsInt(final IOIntSupplier supplier) {
233233
}
234234
}
235235

236+
/**
237+
* Gets the result from an IO int supplier.
238+
*
239+
* @param supplier Supplies the return value.
240+
* @param message The UncheckedIOException message if an I/O error occurs.
241+
* @return result from the supplier.
242+
* @throws UncheckedIOException if an I/O error occurs.
243+
* @since 2.14.0
244+
*/
245+
public static int getAsInt(final IOIntSupplier supplier, final Supplier<String> message) {
246+
try {
247+
return supplier.getAsInt();
248+
} catch (final IOException e) {
249+
throw wrap(e, message);
250+
}
251+
}
252+
236253
/**
237254
* Gets the result from an IO long supplier.
238255
*

src/test/java/org/apache/commons/io/function/UncheckTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,25 @@ public void testGetAsInt() {
235235
assertEquals(1, atomicInt.get());
236236
}
237237

238+
@Test
239+
public void testGetAsIntMessage() {
240+
// No exception
241+
assertThrows(UncheckedIOException.class, () -> Uncheck.getAsInt(() -> {
242+
throw new IOException();
243+
}, () -> CUSTOM_MESSAGE));
244+
assertThrows(UncheckedIOException.class, () -> Uncheck.getAsInt(TestConstants.THROWING_IO_INT_SUPPLIER, () -> CUSTOM_MESSAGE));
245+
assertEquals(1, Uncheck.getAsInt(() -> TestUtils.compareAndSetThrowsIO(atomicInt, 1), () -> CUSTOM_MESSAGE));
246+
assertEquals(1, atomicInt.get());
247+
// exception
248+
final IOException expected = new IOException(CAUSE_MESSAGE);
249+
try {
250+
Uncheck.getAsInt(() -> new BrokenInputStream(expected).read(), () -> CUSTOM_MESSAGE);
251+
fail();
252+
} catch (final UncheckedIOException e) {
253+
assertUncheckedIOException(expected, e);
254+
}
255+
}
256+
238257
/**
239258
* Tests {@link Uncheck#get(IOSupplier, Supplier)}.
240259
*/

0 commit comments

Comments
 (0)