BuilderErrorHandlingTest.java

package tools.jackson.databind.deser.builder;

import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.JsonView;

import tools.jackson.core.JsonParser;
import tools.jackson.core.JsonToken;
import tools.jackson.databind.*;
import tools.jackson.databind.annotation.JsonDeserialize;
import tools.jackson.databind.deser.DeserializationProblemHandler;
import tools.jackson.databind.deser.ValueInstantiator;
import tools.jackson.databind.exc.MismatchedInputException;
import tools.jackson.databind.exc.ValueInstantiationException;
import tools.jackson.databind.testutil.DatabindTestUtil;

import static org.junit.jupiter.api.Assertions.*;

public class BuilderErrorHandlingTest extends DatabindTestUtil
{
    @JsonDeserialize(builder=SimpleBuilderXY.class)
    static class ValueClassXY
    {
        final int _x, _y;

        protected ValueClassXY(int x, int y) {
            _x = x+1;
            _y = y+1;
        }
    }

    static class SimpleBuilderXY
    {
        int x, y;

        public SimpleBuilderXY withX(int x0) {
              this.x = x0;
              return this;
        }

        public SimpleBuilderXY withY(int y0) {
              this.y = y0;
              return this;
        }

        public ValueClassXY build() {
              return new ValueClassXY(x, y);
        }
    }

    // [databind#2938]
    @JsonDeserialize(builder = ValidatingValue.Builder.class)
    static class ValidatingValue
    {
        final String first;
        final String second;

        ValidatingValue(String first, String second) {
            this.first = first;
            this.second = second;
        }

        @SuppressWarnings("serial")
        static class ValidationException extends RuntimeException
        {
            ValidationException(String message) {
                super(message);
            }
        }

        static class Builder
        {
            private String first;
            private String second;

            @JsonSetter("a")
            Builder first(String value) {
                this.first = value;
                return this;
            }

            @JsonSetter("b")
            Builder second(String value) {
                this.second = value;
                return this;
            }

            ValidatingValue build() {
                if (first == null) {
                    throw new ValidationException("Missing first");
                }
                if (second == null) {
                    throw new ValidationException("Missing second");
                }
                return new ValidatingValue(first, second);
            }
        }
    }

    // [databind#6219]: extra array elements must be reported the same way
    // with vanilla and non-vanilla processing
    @JsonDeserialize(builder = ArrayValueXY.Builder.class)
    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    static class ArrayValueXY
    {
        final int x, y;

        ArrayValueXY(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @JsonPropertyOrder({ "x", "y" })
        @JsonFormat(shape = JsonFormat.Shape.ARRAY)
        static class Builder {
            int x, y;

            @JsonView(Object.class)
            public Builder withX(int v) {
                x = v;
                return this;
            }

            @JsonView(Object.class)
            public Builder withY(int v) {
                y = v;
                return this;
            }

            public ArrayValueXY build() {
                return new ArrayValueXY(x, y);
            }
        }
    }

    @JsonDeserialize(builder = ArrayValueWithoutCreator.Builder.class)
    @JsonFormat(shape = JsonFormat.Shape.ARRAY)
    static class ArrayValueWithoutCreator
    {
        @JsonPropertyOrder({ "x" })
        @JsonFormat(shape = JsonFormat.Shape.ARRAY)
        static class Builder
        {
            @JsonCreator(mode = JsonCreator.Mode.DISABLED)
            public Builder(int a, int b) { }

            public Builder withX(int v) {
                return this;
            }

            public ArrayValueWithoutCreator build() {
                return new ArrayValueWithoutCreator();
            }
        }
    }

    /*
    /**********************************************************
    /* Unit tests
    /**********************************************************
     */

    private final ObjectMapper MAPPER = newJsonMapper();

    private final ObjectMapper MAPPER_WITH_WRAPPING = jsonMapperBuilder()
            .enable(DeserializationFeature.WRAP_EXCEPTIONS)
            .build();

    private final ObjectMapper MAPPER_NO_WRAPPING = jsonMapperBuilder()
            .disable(DeserializationFeature.WRAP_EXCEPTIONS)
            .build();

    @Test
    public void testUnknownProperty() throws Exception
    {
        // first, default failure
        String json = a2q("{'x':1,'z':2,'y':4}");
        try {
            MAPPER.readerFor(ValueClassXY.class)
                .with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .readValue(json);
            fail("Should not pass");
        } catch (MismatchedInputException e) {
            verifyException(e, "Unrecognized property ");
        }
        // but pass if ok to ignore
        ValueClassXY result = MAPPER.readerFor(ValueClassXY.class)
                .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .readValue(json);
        assertEquals(2, result._x);
        assertEquals(5, result._y);
    }

    @Test
    public void testWrongShape() throws Exception
    {
        try {
            MAPPER.readValue("123", ValueClassXY.class);
            fail("Should not pass");
        } catch (MismatchedInputException e) {
            verifyException(e, "Cannot construct instance of ");
            // should report Builder class, not value here, right?
            verifyException(e, "$SimpleBuilderXY");
        }
    }

    // [databind#6398]
    @Test
    void unexpectedObjectHandlerCanReturnNullForArrayBuilder() throws Exception
    {
        ObjectMapper mapper = jsonMapperBuilder()
                .addHandler(new DeserializationProblemHandler() {
                    @Override
                    public Object handleUnexpectedToken(DeserializationContext ctxt,
                            JavaType targetType, JsonToken token, JsonParser p, String failureMsg) {
                        if (token == JsonToken.START_OBJECT) {
                            p.skipChildren();
                            return null;
                        }
                        return NOT_HANDLED;
                    }
                })
                .build();

        assertNull(mapper.readValue("""
                {"x":1,"y":2}
                """, ArrayValueXY.class));
    }

    // [databind#6398]
    @Test
    void missingInstantiatorHandlerCanReturnNullForArrayBuilder() throws Exception
    {
        ObjectMapper mapper = jsonMapperBuilder()
                .addHandler(new DeserializationProblemHandler() {
                    @Override
                    public Object handleMissingInstantiator(DeserializationContext ctxt,
                            Class<?> instClass, ValueInstantiator valueInsta,
                            JsonParser p, String msg) {
                        assertSame(ArrayValueWithoutCreator.Builder.class, instClass);
                        p.skipChildren();
                        return null;
                    }
                })
                .build();

        assertNull(mapper.readValue("""
                [1,2]
                """, ArrayValueWithoutCreator.class));
    }

    // [databind#2938]

    @Test
    public void testSuccessfulValidatingBuilder() throws Exception
    {
        ValidatingValue result = MAPPER.readValue(a2q("{'a':'1','b':'2'}"), ValidatingValue.class);
        assertEquals("1", result.first);
        assertEquals("2", result.second);
    }

    @Test
    public void testFailingValidatingBuilderWithExceptionWrapping() throws Exception
    {
        try {
            MAPPER_WITH_WRAPPING.readValue(a2q("{'a':'1'}"), ValidatingValue.class);
            fail("Expected an exception");
        } catch (ValueInstantiationException e) {
            verifyException(e, "Missing second");
            assertInstanceOf(ValidatingValue.ValidationException.class, e.getCause());
        }
    }

    @Test
    public void testFailingValidatingBuilderWithExceptionWrappingFromTree() throws Exception
    {
        try {
            JsonNode tree = MAPPER_WITH_WRAPPING.readTree(a2q("{'a':'1'}"));
            MAPPER_WITH_WRAPPING.treeToValue(tree, ValidatingValue.class);
            fail("Expected an exception");
        } catch (ValueInstantiationException e) {
            verifyException(e, "Missing second");
            assertInstanceOf(ValidatingValue.ValidationException.class, e.getCause());
        }
    }

    @Test
    public void testFailingValidatingBuilderWithoutExceptionWrapping() throws Exception
    {
        try {
            MAPPER_NO_WRAPPING
                    .readValue(a2q("{'a':'1'}"), ValidatingValue.class);
            fail("Expected an exception");
        } catch (ValidatingValue.ValidationException e) {
            assertEquals("Missing second", e.getMessage());
        }
    }

    @Test
    public void testFailingValidatingBuilderWithoutExceptionWrappingFromTree() throws Exception
    {
        try {
            JsonNode tree = MAPPER_NO_WRAPPING.readTree(a2q("{'a':'1'}"));
            MAPPER_NO_WRAPPING.treeToValue(tree, ValidatingValue.class);
            fail("Expected an exception");
        } catch (ValidatingValue.ValidationException e) {
            assertEquals("Missing second", e.getMessage());
        }
    }

    // [databind#6219]
    @Test
    void extraArrayElementsReportedSameWithAndWithoutView() throws Exception
    {
        final String json = "[1,2,3]";
        ObjectReader r = MAPPER.readerFor(ArrayValueXY.class)
                .with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // Vanilla processing (no active view)
        MismatchedInputException vanilla = assertThrows(MismatchedInputException.class,
                () -> r.readValue(json));
        // Non-vanilla processing (active view)
        MismatchedInputException nonVanilla = assertThrows(MismatchedInputException.class,
                () -> r.withView(Object.class).readValue(json));

        verifyException(vanilla, "expected `JsonToken.END_ARRAY`");
        verifyException(vanilla, "expected at most 2 properties");
        assertEquals(nonVanilla.getOriginalMessage(), vanilla.getOriginalMessage());
    }
}