diff --git a/AGENTS.md b/AGENTS.md index dac77fa..f5b61cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -378,10 +378,13 @@ However, test dependencies must not accidentally become runtime dependencies of JaCoCo (`jacoco.version` in the parent POM) is wired report-only: every `./mvnw clean verify` writes per-module reports to `target/site/jacoco` without failing the build. There are no coverage gates; use the reports during review -to spot untested branches. One known artifact: single-statement lines that -always throw (for example a guard delegating to a method that only throws) -execute but never complete, so JaCoCo reports them as missed despite a passing -test proving otherwise. +to spot untested branches. Two known artifacts, both verified by other means +and deliberately left alone: single-statement lines that always throw (for +example a guard delegating to a method that only throws) execute but never +complete, so JaCoCo reports them as missed despite a passing test proving +otherwise; and `this == obj` fast-path guards in `equals`, which only a +self-comparison could cover — a test SonarQube rightly flags as a bug, so the +partial branch stands. ### Completion Requirement diff --git a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetail.java b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetail.java index d061cff..01bbd0f 100644 --- a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetail.java +++ b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetail.java @@ -1,5 +1,6 @@ package io.github.othmaneataallah.problemdetails.core; +import java.io.Serializable; import java.net.URI; import java.util.Collections; import java.util.LinkedHashMap; @@ -33,6 +34,10 @@ * be reused to create several instances; values are copied at {@link Builder#build() build} time, * so later builder mutations never affect already-built instances. * + *

Instances are {@link Serializable} so problem details can cross process boundaries (for + * example inside a serialized {@link ProblemDetailException}); extension values travel + * along, so they should be serializable too. + * *

{@code
  * ProblemDetail problem =
  *     ProblemDetail.builder()
@@ -44,7 +49,9 @@
  *         .build();
  * }
*/ -public final class ProblemDetail { +public final class ProblemDetail implements Serializable { + + private static final long serialVersionUID = 1L; /** The problem type assumed when {@code type} is absent (RFC 9457, Section 3.1.1). */ public static final URI ABOUT_BLANK = URI.create("about:blank"); @@ -54,8 +61,15 @@ public final class ProblemDetail { private final Integer status; private final String detail; private final URI instance; - private final Map, Object> extensions; - private final Map extensionMembers; + + // S1948 is suppressed by design: the declared Map types are not Serializable, but the + // runtime instances always are — and extension values remain the caller's responsibility, + // as documented on the class. + @SuppressWarnings("java:S1948") + private final LinkedHashMap, Object> extensions; + + @SuppressWarnings("java:S1948") + private final LinkedHashMap extensionMembers; private ProblemDetail(Builder builder) { this.type = builder.type; @@ -63,10 +77,10 @@ private ProblemDetail(Builder builder) { this.status = builder.status; this.detail = builder.detail; this.instance = builder.instance; - this.extensions = Collections.unmodifiableMap(new LinkedHashMap<>(builder.extensions)); - Map members = new LinkedHashMap<>(); + this.extensions = new LinkedHashMap<>(builder.extensions); + LinkedHashMap members = new LinkedHashMap<>(); this.extensions.forEach((key, value) -> members.put(key.name(), value)); - this.extensionMembers = Collections.unmodifiableMap(members); + this.extensionMembers = members; } /** @@ -173,10 +187,11 @@ public boolean has(ProblemDetailKey key) { *

This view exists for serialization modules (JSON, XML), which must write members the typed * API does not know statically. Application code should prefer {@link #get(ProblemDetailKey)}. * - * @return an unmodifiable snapshot of the extension members; never null + * @return an unmodifiable view of the extension members; never null, and safe to retain since the + * underlying data never changes */ public Map extensionMembers() { - return extensionMembers; + return Collections.unmodifiableMap(extensionMembers); } @Override diff --git a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailException.java b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailException.java index 012f735..355fcab 100644 --- a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailException.java +++ b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailException.java @@ -21,6 +21,8 @@ public class ProblemDetailException extends RuntimeException { private static final long serialVersionUID = 1L; + private static final String PROBLEM_DETAIL_PARAMETER = "problemDetail"; + private final ProblemDetail problemDetail; /** @@ -31,7 +33,7 @@ public class ProblemDetailException extends RuntimeException { */ public ProblemDetailException(ProblemDetail problemDetail) { super(messageFor(problemDetail)); - this.problemDetail = Objects.requireNonNull(problemDetail, "problemDetail"); + this.problemDetail = Objects.requireNonNull(problemDetail, PROBLEM_DETAIL_PARAMETER); } /** @@ -43,7 +45,7 @@ public ProblemDetailException(ProblemDetail problemDetail) { */ public ProblemDetailException(ProblemDetail problemDetail, Throwable cause) { super(messageFor(problemDetail), cause); - this.problemDetail = Objects.requireNonNull(problemDetail, "problemDetail"); + this.problemDetail = Objects.requireNonNull(problemDetail, PROBLEM_DETAIL_PARAMETER); } /** @@ -56,7 +58,7 @@ public ProblemDetail getProblemDetail() { } private static String messageFor(ProblemDetail problemDetail) { - Objects.requireNonNull(problemDetail, "problemDetail"); + Objects.requireNonNull(problemDetail, PROBLEM_DETAIL_PARAMETER); if (problemDetail.getDetail() != null) { return problemDetail.getDetail(); } diff --git a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKey.java b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKey.java index df2690f..7446907 100644 --- a/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKey.java +++ b/problem-details-core/src/main/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKey.java @@ -1,5 +1,6 @@ package io.github.othmaneataallah.problemdetails.core; +import java.io.Serializable; import java.util.Objects; /** @@ -26,7 +27,9 @@ * * @param the Java type of the extension member value */ -public final class ProblemDetailKey { +public final class ProblemDetailKey implements Serializable { + + private static final long serialVersionUID = 1L; private final String name; private final Class type; diff --git a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailExceptionTest.java b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailExceptionTest.java index 9ad0e56..3a7c9e1 100644 --- a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailExceptionTest.java +++ b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailExceptionTest.java @@ -3,6 +3,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.net.URI; import org.junit.jupiter.api.Test; @@ -47,8 +51,33 @@ void messagePrefersDetailThenTitleThenType() { .isEqualTo(URI.create("about:blank").toString()); } + @Test + void survivesJavaSerialization() throws Exception { + ProblemDetailException original = + new ProblemDetailException( + ProblemDetail.builder() + .title("Title.") + .status(400) + .extension(ProblemDetailKey.of("balance", Integer.class), 30) + .build()); + + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { + out.writeObject(original); + } + ProblemDetailException readBack; + try (ObjectInputStream in = + new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) { + readBack = (ProblemDetailException) in.readObject(); + } + + assertThat(readBack.getProblemDetail()).isEqualTo(original.getProblemDetail()); + assertThat(readBack.getMessage()).isEqualTo(original.getMessage()); + } + @Test void nullProblemDetailIsRejected() { + assertThatThrownBy(() -> new ProblemDetailException(null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> new ProblemDetailException(null, new RuntimeException())) diff --git a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKeyTest.java b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKeyTest.java index c19f4d2..c4e8fb3 100644 --- a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKeyTest.java +++ b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailKeyTest.java @@ -42,16 +42,9 @@ void equalityIsByNameOnly() { assertThat(ProblemDetailKey.of("balance", Integer.class)) .isNotEqualTo(ProblemDetailKey.of("other", Integer.class)); assertThat(ProblemDetailKey.of("balance", Integer.class)).isNotEqualTo("balance"); - assertThat(ProblemDetailKey.of("balance", Integer.class)).isNotEqualTo(null); - assertThat(ProblemDetailKey.of("balance", Integer.class).hashCode()) - .isEqualTo(ProblemDetailKey.of("balance", String.class).hashCode()); - } - - @Test - void selfEquality() { - ProblemDetailKey key = ProblemDetailKey.of("balance", Integer.class); - - assertThat(key).isEqualTo(key); + assertThat(ProblemDetailKey.of("balance", Integer.class)).isNotNull(); + assertThat(ProblemDetailKey.of("balance", Integer.class)) + .hasSameHashCodeAs(ProblemDetailKey.of("balance", String.class)); } @Test diff --git a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailTest.java b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailTest.java index 02ba69d..4cf8620 100644 --- a/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailTest.java +++ b/problem-details-core/src/test/java/io/github/othmaneataallah/problemdetails/core/ProblemDetailTest.java @@ -23,7 +23,7 @@ void builderDefaultsToAboutBlankWithAbsentMembers() { @Test void aboutBlankConstantMatchesDefaultType() { - assertThat(ProblemDetail.ABOUT_BLANK).isEqualTo(URI.create("about:blank")); + assertThat(URI.create("about:blank")).isEqualTo(ProblemDetail.ABOUT_BLANK); assertThat(ProblemDetail.builder().build().getType()).isEqualTo(ProblemDetail.ABOUT_BLANK); } @@ -184,14 +184,12 @@ void valueSemantics() { ProblemDetail.builder().title("Title").status(400).extension(balance, 30).build(); ProblemDetail different = ProblemDetail.builder().title("Other").status(400).build(); - assertThat(first).isEqualTo(first); - assertThat(first).isEqualTo(second); + assertThat(first) + .isEqualTo(second) + .hasSameHashCodeAs(second) + .isNotEqualTo(different) + .isNotNull(); assertThat(second).isEqualTo(first); - assertThat(first.hashCode()).isEqualTo(second.hashCode()); - assertThat(first).isNotEqualTo(different); - assertThat(first).isNotEqualTo(null); - assertThat(first).isNotEqualTo("not a problem detail"); - assertThat(first.toString()).contains("Title", "400", "balance=30"); } @Test @@ -216,8 +214,7 @@ void inequalityIsDetectedPerMember() { .detail("Detail") .instance("/instances/1") .extension(balance, 30) - .build()); - assertThat(base) + .build()) .isNotEqualTo( ProblemDetail.builder() .type("https://example.com/probs/a") @@ -226,8 +223,7 @@ void inequalityIsDetectedPerMember() { .detail("Detail") .instance("/instances/1") .extension(balance, 30) - .build()); - assertThat(base) + .build()) .isNotEqualTo( ProblemDetail.builder() .type("https://example.com/probs/a") @@ -236,8 +232,7 @@ void inequalityIsDetectedPerMember() { .detail("Detail") .instance("/instances/1") .extension(balance, 30) - .build()); - assertThat(base) + .build()) .isNotEqualTo( ProblemDetail.builder() .type("https://example.com/probs/a") @@ -246,8 +241,7 @@ void inequalityIsDetectedPerMember() { .detail("Other") .instance("/instances/1") .extension(balance, 30) - .build()); - assertThat(base) + .build()) .isNotEqualTo( ProblemDetail.builder() .type("https://example.com/probs/a") @@ -256,8 +250,7 @@ void inequalityIsDetectedPerMember() { .detail("Detail") .instance("/instances/2") .extension(balance, 30) - .build()); - assertThat(base) + .build()) .isNotEqualTo( ProblemDetail.builder() .type("https://example.com/probs/a") @@ -294,8 +287,7 @@ void toStringRendersAllPresentMembers() { @Test void toStringOmitsAbsentMembers() { - assertThat(ProblemDetail.builder().build().toString()) - .isEqualTo("ProblemDetail[type=about:blank]"); + assertThat(ProblemDetail.builder().build()).hasToString("ProblemDetail[type=about:blank]"); } @Test diff --git a/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializer.java b/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializer.java index 323a4f6..4626bca 100644 --- a/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializer.java +++ b/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializer.java @@ -7,6 +7,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.function.BiConsumer; import tools.jackson.core.JsonParser; import tools.jackson.databind.DeserializationContext; import tools.jackson.databind.JsonNode; @@ -38,7 +39,9 @@ public final class ProblemDetailDeserializer extends ValueDeserializer { /** Creates a deserializer. */ - public ProblemDetailDeserializer() {} + public ProblemDetailDeserializer() { + // Stateless; instantiated directly or by the Jackson module. + } @Override public ProblemDetail deserialize(JsonParser p, DeserializationContext ctxt) { @@ -47,15 +50,14 @@ public ProblemDetail deserialize(JsonParser p, DeserializationContext ctxt) { return (ProblemDetail) ctxt.handleUnexpectedToken(ProblemDetail.class, p); } ProblemDetail.Builder builder = ProblemDetail.builder(); + readStandardMembers(node, builder); + readExtensions(node, builder); + return builder.build(); + } - JsonNode type = node.get("type"); - if (type != null && type.isTextual()) { - try { - builder.type(URI.create(type.asText())); - } catch (IllegalArgumentException ignored) { - // Fall through to the core default, per the ignore-mistyped-member rule above. - } - } + /** Reads the five standard members, ignoring mistyped values per RFC 9457, Section 3.1. */ + private static void readStandardMembers(JsonNode node, ProblemDetail.Builder builder) { + readUriMember(node.get("type"), builder, ProblemDetail.Builder::type); JsonNode status = node.get("status"); if (status != null && status.isIntegralNumber() && status.canConvertToInt()) { int value = status.intValue(); @@ -63,35 +65,44 @@ public ProblemDetail deserialize(JsonParser p, DeserializationContext ctxt) { builder.status(value); } } - JsonNode title = node.get("title"); - if (title != null && title.isTextual()) { - builder.title(title.asText()); - } - JsonNode detail = node.get("detail"); - if (detail != null && detail.isTextual()) { - builder.detail(detail.asText()); - } - JsonNode instance = node.get("instance"); - if (instance != null && instance.isTextual()) { + readTextMember(node.get("title"), builder, ProblemDetail.Builder::title); + readTextMember(node.get("detail"), builder, ProblemDetail.Builder::detail); + readUriMember(node.get("instance"), builder, ProblemDetail.Builder::instance); + } + + /** Reads one URI member, ignoring absent, non-textual, and unparseable values. */ + private static void readUriMember( + JsonNode member, + ProblemDetail.Builder builder, + BiConsumer setter) { + if (member != null && member.isTextual()) { try { - builder.instance(URI.create(instance.asText())); + setter.accept(builder, URI.create(member.asText())); } catch (IllegalArgumentException ignored) { - // Fall through to absent, per the ignore-mistyped-member rule above. + // Fall through, per the ignore-mistyped-member rule above. } } + } + + /** Reads one text member, ignoring absent and non-textual values. */ + private static void readTextMember( + JsonNode member, + ProblemDetail.Builder builder, + BiConsumer setter) { + if (member != null && member.isTextual()) { + setter.accept(builder, member.asText()); + } + } + /** Reads every non-standard member as an extension, skipping JSON nulls. */ + private static void readExtensions(JsonNode node, ProblemDetail.Builder builder) { for (Map.Entry field : node.properties()) { String name = field.getKey(); - if (isStandardMember(name)) { - continue; - } JsonNode member = field.getValue(); - if (member.isNull()) { - continue; + if (!isStandardMember(name) && !member.isNull()) { + putExtension(builder, name, toValue(member)); } - putExtension(builder, name, toValue(member)); } - return builder.build(); } private static boolean isStandardMember(String name) { diff --git a/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailSerializer.java b/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailSerializer.java index d9a6840..23428ff 100644 --- a/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailSerializer.java +++ b/problem-details-jackson/src/main/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailSerializer.java @@ -21,7 +21,9 @@ public final class ProblemDetailSerializer extends ValueSerializer { /** Creates a serializer. */ - public ProblemDetailSerializer() {} + public ProblemDetailSerializer() { + // Stateless; instantiated directly or by the Jackson module. + } @Override public void serialize(ProblemDetail value, JsonGenerator gen, SerializationContext ctxt) { diff --git a/problem-details-jackson/src/test/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializationTest.java b/problem-details-jackson/src/test/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializationTest.java index d31cdb4..37c5146 100644 --- a/problem-details-jackson/src/test/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializationTest.java +++ b/problem-details-jackson/src/test/java/io/github/othmaneataallah/problemdetails/jackson/ProblemDetailDeserializationTest.java @@ -20,12 +20,14 @@ class ProblemDetailDeserializationTest { @Test void outOfCreditExampleParses() { String json = - "{\"type\":\"https://example.com/probs/out-of-credit\"," - + "\"title\":\"You do not have enough credit.\"," - + "\"detail\":\"Your current balance is 30, but that costs 50.\"," - + "\"instance\":\"/account/12345/msgs/abc\"," - + "\"balance\":30," - + "\"accounts\":[\"/account/12345\",\"/account/67890\"]}"; + """ + {"type":"https://example.com/probs/out-of-credit",\ + "title":"You do not have enough credit.",\ + "detail":"Your current balance is 30, but that costs 50.",\ + "instance":"/account/12345/msgs/abc",\ + "balance":30,\ + "accounts":["/account/12345","/account/67890"]}\ + """; ProblemDetail problem = mapper.readValue(json, ProblemDetail.class); diff --git a/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailExceptionMapper.java b/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailExceptionMapper.java index ece9299..067ac28 100644 --- a/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailExceptionMapper.java +++ b/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailExceptionMapper.java @@ -22,7 +22,9 @@ public final class ProblemDetailExceptionMapper implements ExceptionMapper { /** Creates a mapper. */ - public ProblemDetailExceptionMapper() {} + public ProblemDetailExceptionMapper() { + // Stateless; instantiated by the JAX-RS runtime. + } @Override public Response toResponse(ProblemDetailException exception) { diff --git a/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailMessageBodyWriter.java b/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailMessageBodyWriter.java index 8029261..c43159d 100644 --- a/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailMessageBodyWriter.java +++ b/problem-details-jaxrs/src/main/java/io/github/othmaneataallah/problemdetails/jaxrs/ProblemDetailMessageBodyWriter.java @@ -35,7 +35,9 @@ public final class ProblemDetailMessageBodyWriter implements MessageBodyWriter

toResponseEntity( ProblemDetail problem) { - Objects.requireNonNull(problem, "problem"); + Objects.requireNonNull(problem, PROBLEM_PARAMETER); return ResponseEntity.status(statusCode(problem)) .contentType(MediaType.APPLICATION_PROBLEM_JSON) .body(toSpringDetail(problem)); diff --git a/problem-details-spring/src/test/java/io/github/othmaneataallah/problemdetails/spring/SpringProblemDetailsTest.java b/problem-details-spring/src/test/java/io/github/othmaneataallah/problemdetails/spring/SpringProblemDetailsTest.java index c196096..9bbb5e8 100644 --- a/problem-details-spring/src/test/java/io/github/othmaneataallah/problemdetails/spring/SpringProblemDetailsTest.java +++ b/problem-details-spring/src/test/java/io/github/othmaneataallah/problemdetails/spring/SpringProblemDetailsTest.java @@ -49,13 +49,12 @@ void convertsAllMembersAndExtensions() { 30) .build()); - assertThat(springDetail.getType().toString()) - .isEqualTo("https://example.com/probs/out-of-credit"); + assertThat(springDetail.getType()).hasToString("https://example.com/probs/out-of-credit"); assertThat(springDetail.getTitle()).isEqualTo("You do not have enough credit."); assertThat(springDetail.getStatus()).isEqualTo(403); assertThat(springDetail.getDetail()) .isEqualTo("Your current balance is 30, but that costs 50."); - assertThat(springDetail.getInstance().toString()).isEqualTo("/account/12345/msgs/abc"); + assertThat(springDetail.getInstance()).hasToString("/account/12345/msgs/abc"); assertThat(springDetail.getProperties()).containsEntry("balance", 30); } diff --git a/problem-details-xml/src/main/java/io/github/othmaneataallah/problemdetails/xml/ProblemXml.java b/problem-details-xml/src/main/java/io/github/othmaneataallah/problemdetails/xml/ProblemXml.java index 6478842..16a2f89 100644 --- a/problem-details-xml/src/main/java/io/github/othmaneataallah/problemdetails/xml/ProblemXml.java +++ b/problem-details-xml/src/main/java/io/github/othmaneataallah/problemdetails/xml/ProblemXml.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.function.BiConsumer; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; @@ -53,6 +54,11 @@ public final class ProblemXml { */ public static final String NAMESPACE = "urn:ietf:rfc:7807"; + /** Local name of the format's root element. */ + private static final String ROOT_ELEMENT = "problem"; + + private static final String PROBLEM_PARAMETER = "problem"; + private ProblemXml() {} /** @@ -67,7 +73,6 @@ private ProblemXml() {} * XML element names */ public static String toXml(ProblemDetail problem) throws XMLStreamException { - Objects.requireNonNull(problem, "problem"); StringWriter out = new StringWriter(); toXml(problem, XMLOutputFactory.newFactory().createXMLStreamWriter(out)); return out.toString(); @@ -87,10 +92,10 @@ public static String toXml(ProblemDetail problem) throws XMLStreamException { * XML element names */ public static void toXml(ProblemDetail problem, XMLStreamWriter out) throws XMLStreamException { - Objects.requireNonNull(problem, "problem"); + Objects.requireNonNull(problem, PROBLEM_PARAMETER); Objects.requireNonNull(out, "out"); out.writeStartDocument("UTF-8", "1.0"); - out.writeStartElement("problem"); + out.writeStartElement(ROOT_ELEMENT); out.writeDefaultNamespace(NAMESPACE); writeTextElement(out, "type", problem.getType().toString()); writeTextElement(out, "title", problem.getTitle()); @@ -122,11 +127,11 @@ public static void toXml(ProblemDetail problem, XMLStreamWriter out) throws XMLS */ public static ProblemDetail fromXml(String xml) throws XMLStreamException { Objects.requireNonNull(xml, "xml"); - XMLInputFactory factory = XMLInputFactory.newFactory(); - factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); - factory.setProperty(XMLInputFactory.IS_COALESCING, true); - XMLStreamReader in = factory.createXMLStreamReader(new StringReader(xml)); + // The factory never returns null (it throws instead), but its signature carries no + // nullness contract for analyzers. + XMLStreamReader in = + Objects.requireNonNull( + newInputFactory().createXMLStreamReader(new StringReader(xml)), "reader"); try { return fromXml(in); } finally { @@ -146,6 +151,21 @@ public static ProblemDetail fromXml(String xml) throws XMLStreamException { */ public static ProblemDetail fromXml(XMLStreamReader in) throws XMLStreamException { Objects.requireNonNull(in, "in"); + moveToRootElement(in); + ProblemDetail.Builder builder = ProblemDetail.builder(); + while (in.hasNext()) { + int event = in.next(); + if (event == START_ELEMENT) { + readMember(in, builder); + } else if (event == END_ELEMENT) { + return builder.build(); + } + } + throw new XMLStreamException("Unexpected end of input inside "); + } + + /** Consumes events up to the {@code problem} root element, rejecting anything else. */ + private static void moveToRootElement(XMLStreamReader in) throws XMLStreamException { boolean found = false; while (in.hasNext()) { if (in.next() == START_ELEMENT) { @@ -153,67 +173,70 @@ public static ProblemDetail fromXml(XMLStreamReader in) throws XMLStreamExceptio break; } } - if (!found || !"problem".equals(in.getLocalName())) { + if (!found || !ROOT_ELEMENT.equals(in.getLocalName())) { throw new XMLStreamException("Expected a root element"); } - ProblemDetail.Builder builder = ProblemDetail.builder(); - while (in.hasNext()) { - int event = in.next(); - if (event == START_ELEMENT) { - String name = in.getLocalName(); - switch (name) { - case "type" -> { - Object value = parseElement(in); - if (value instanceof String text) { - try { - builder.type(URI.create(text)); - } catch (IllegalArgumentException ignored) { - // Fall through to the core default, mirroring the JSON module. - } - } - } - case "status" -> { - Object value = parseElement(in); - if (value instanceof String text) { - try { - int status = Integer.parseInt(text); - if (status >= 100 && status <= 599) { - builder.status(status); - } - } catch (NumberFormatException ignored) { - // Fall through to absent, mirroring the JSON module. - } - } - } - case "title" -> { - Object value = parseElement(in); - if (value instanceof String text) { - builder.title(text); - } - } - case "detail" -> { - Object value = parseElement(in); - if (value instanceof String text) { - builder.detail(text); - } - } - case "instance" -> { - Object value = parseElement(in); - if (value instanceof String text) { - try { - builder.instance(URI.create(text)); - } catch (IllegalArgumentException ignored) { - // Fall through to absent, mirroring the JSON module. - } - } - } - default -> putExtension(builder, name, parseElement(in)); + } + + /** Reads the member the reader is positioned on into the builder. */ + private static void readMember(XMLStreamReader in, ProblemDetail.Builder builder) + throws XMLStreamException { + String name = in.getLocalName(); + switch (name) { + case "type" -> readUriMember(in, builder, ProblemDetail.Builder::type); + case "status" -> readStatusMember(in, builder); + case "title" -> readTextMember(in, builder, ProblemDetail.Builder::title); + case "detail" -> readTextMember(in, builder, ProblemDetail.Builder::detail); + case "instance" -> readUriMember(in, builder, ProblemDetail.Builder::instance); + default -> putExtension(builder, name, parseElement(in)); + } + } + + /** + * Reads a URI member, ignoring unparseable values. An ignored {@code type} falls back to the core + * default; an ignored {@code instance} stays absent. + */ + private static void readUriMember( + XMLStreamReader in, + ProblemDetail.Builder builder, + BiConsumer setter) + throws XMLStreamException { + Object value = parseElement(in); + if (value instanceof String text) { + try { + setter.accept(builder, URI.create(text)); + } catch (IllegalArgumentException ignored) { + // Fall through, mirroring the JSON module. + } + } + } + + /** Reads the {@code status} member, ignoring non-numeric and out-of-range values. */ + private static void readStatusMember(XMLStreamReader in, ProblemDetail.Builder builder) + throws XMLStreamException { + Object value = parseElement(in); + if (value instanceof String text) { + try { + int status = Integer.parseInt(text); + if (status >= 100 && status <= 599) { + builder.status(status); } - } else if (event == END_ELEMENT) { - return builder.build(); + } catch (NumberFormatException ignored) { + // Fall through to absent, mirroring the JSON module. } } - throw new XMLStreamException("Unexpected end of input inside "); + } + + /** Reads a plain text member, ignoring markup content. */ + private static void readTextMember( + XMLStreamReader in, + ProblemDetail.Builder builder, + BiConsumer setter) + throws XMLStreamException { + Object value = parseElement(in); + if (value instanceof String text) { + setter.accept(builder, text); + } } private static void writeTextElement(XMLStreamWriter out, String name, String value) @@ -256,6 +279,18 @@ private static void writeExtension(XMLStreamWriter out, String name, Object valu } } + /** + * Creates securely configured reader factories: DTDs and external entities stay disabled + * everywhere, including validation probes, so untrusted input can never resolve them. + */ + private static XMLInputFactory newInputFactory() { + XMLInputFactory factory = XMLInputFactory.newFactory(); + factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); + factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + factory.setProperty(XMLInputFactory.IS_COALESCING, true); + return factory; + } + /** * Rejects names the writer would otherwise emit as malformed markup. The check parses a probe * element, so exactly the XML {@code Name} production is enforced without reimplementing it. @@ -263,7 +298,7 @@ private static void writeExtension(XMLStreamWriter out, String name, Object valu private static void requireValidElementName(String name) throws XMLStreamException { try { XMLStreamReader probe = - XMLInputFactory.newFactory().createXMLStreamReader(new StringReader("<" + name + "/>")); + newInputFactory().createXMLStreamReader(new StringReader("<" + name + "/>")); try { while (probe.hasNext()) { probe.next(); @@ -317,7 +352,9 @@ private static Object parseElement(XMLStreamReader in) throws XMLStreamException children.forEach(child -> values.put(child.getKey(), child.getValue())); return values; } - default -> {} + default -> { + // Comments, processing instructions, and other non-element events carry no data. + } } } throw new XMLStreamException("Unexpected end of input inside an element"); diff --git a/problem-details-xml/src/test/java/io/github/othmaneataallah/problemdetails/xml/ProblemXmlDeserializationTest.java b/problem-details-xml/src/test/java/io/github/othmaneataallah/problemdetails/xml/ProblemXmlDeserializationTest.java index c732f3c..8b55d79 100644 --- a/problem-details-xml/src/test/java/io/github/othmaneataallah/problemdetails/xml/ProblemXmlDeserializationTest.java +++ b/problem-details-xml/src/test/java/io/github/othmaneataallah/problemdetails/xml/ProblemXmlDeserializationTest.java @@ -77,14 +77,16 @@ void outOfRangeStatusIsIgnored() throws XMLStreamException { @Test void prettyPrintedInputParsesCleanly() throws XMLStreamException { String xml = - "\n" - + "\n" - + " You do not have enough credit.\n" - + " \n" - + " /account/12345\n" - + " /account/67890\n" - + " \n" - + ""; + """ + + + You do not have enough credit. + + /account/12345 + /account/67890 + + + """; ProblemDetail problem = ProblemXml.fromXml(xml);