Skip to content

Commit 376779c

Browse files
authored
Add ifPresent action on JsonNullable (#16)
1 parent 2035b51 commit 376779c

3 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/main/java/org/openapitools/jackson/nullable/JsonNullable.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.io.Serializable;
44
import java.util.NoSuchElementException;
5+
import java.util.function.Consumer;
56

67
public class JsonNullable<T> implements Serializable {
78

@@ -68,6 +69,20 @@ public boolean isPresent() {
6869
return isPresent;
6970
}
7071

72+
/**
73+
* If a value is present, performs the given action with the value,
74+
* otherwise does nothing.
75+
*
76+
* @param action the action to be performed, if a value is present
77+
*/
78+
public void ifPresent(
79+
Consumer<? super T> action) {
80+
81+
if (this.isPresent) {
82+
action.accept(value);
83+
}
84+
}
85+
7186
@Override
7287
public boolean equals(Object obj) {
7388
if (this == obj) {

src/main/java/org/openapitools/jackson/nullable/JsonNullableModule.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.openapitools.jackson.nullable;
22

33
import com.fasterxml.jackson.core.Version;
4+
import com.fasterxml.jackson.core.json.PackageVersion;
45
import com.fasterxml.jackson.databind.Module;
56

67
public class JsonNullableModule extends Module {

src/test/java/org/openapitools/jackson/nullable/JsonNullableSimpleTest.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,30 @@ public void orElseMissing() {
5757
assertEquals("world", test.orElse("world"));
5858
}
5959

60+
@Test
61+
public void ifPresentWithValueNotPresent() {
62+
JsonNullable<String> test = JsonNullable.undefined();
63+
test.ifPresent(string -> {
64+
throw new RuntimeException();
65+
});
66+
}
67+
68+
@Test(expected = RuntimeException.class)
69+
public void ifPresentWithNullValuePresent() {
70+
JsonNullable<String> test = JsonNullable.of(null);
71+
test.ifPresent(string -> {
72+
throw new RuntimeException();
73+
});
74+
}
75+
76+
@Test(expected = RuntimeException.class)
77+
public void ifPresentWithNonNullValuePresent() {
78+
JsonNullable<String> test = JsonNullable.of("test");
79+
test.ifPresent(string -> {
80+
throw new RuntimeException();
81+
});
82+
}
83+
6084
@Test
6185
public void serializeNonBeanProperty() throws JsonProcessingException {
6286
assertEquals("null", mapper.writeValueAsString(JsonNullable.of(null)));

0 commit comments

Comments
 (0)