Skip to content

Commit

Permalink
Guard Mapper.write against null writer
Browse files Browse the repository at this point in the history
A `null` writer passed to the `Mapper.write` method, sensibly, throws
an NPE upon flushing the buffer out. However, since the flushing
occurs at a later time, debugging that this occurred is challenging.
Thus, this commit implements a fail-fast `null` guard.
  • Loading branch information
pingpingy1 committed Mar 15, 2024
1 parent e41f969 commit 559d492
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Objects;

import static org.apache.johnzon.mapper.internal.Streams.noClose;

Expand Down Expand Up @@ -166,7 +167,7 @@ public JsonValue toStructure(final Object object) {

public void writeObject(final Object object, final Writer stream) {
if (object == null) {
try (final Writer w = stream) {
try (final Writer w = Objects.requireNonNull(stream, "stream")) {
w.write("null");
} catch (final IOException e) {
throw new MapperException(e);
Expand All @@ -175,7 +176,7 @@ public void writeObject(final Object object, final Writer stream) {
}
final Adapter adapter = config.findAdapter(object.getClass());
if (adapter != null && TypeAwareAdapter.class.isInstance(adapter) && TypeAwareAdapter.class.cast(adapter).getTo() == JsonString.class) {
writeObject(adapter.from(object), stream);
writeObject(adapter.from(object), Objects.requireNonNull(stream, "stream"));
return;
}
try (final JsonGenerator generator = generatorFactory.createGenerator(stream(stream))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.util.ArrayList;
Expand All @@ -52,6 +53,7 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;

import jakarta.json.Json;
Expand Down Expand Up @@ -1381,4 +1383,17 @@ public static class Parent {
public static class Child extends Parent {
public List<String> children;
}

/**
* Tests Mapper.writeObject with null Writer.
*/
@Test
public void testNullWriter () {
assertThrows(NullPointerException.class, () -> {
new MapperBuilder().build().writeObject(null, (Writer) null);
});
assertThrows(NullPointerException.class, () -> {
new MapperBuilder().build().writeObject("", (Writer) null);
});
}
}

0 comments on commit 559d492

Please sign in to comment.