From 507d88c4e86778e4ef582b863cd4a161c65b93dc Mon Sep 17 00:00:00 2001 From: Andrei Voinea Date: Wed, 29 Mar 2023 23:07:29 +0300 Subject: [PATCH] Throw exception when json-patch append adds primitive to collection of complex types --- .../rest/webmvc/json/patch/PatchOperation.java | 8 +++++++- .../webmvc/json/patch/AddOperationUnitTests.java | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/patch/PatchOperation.java b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/patch/PatchOperation.java index 566e5990e..7cbf8cc11 100644 --- a/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/patch/PatchOperation.java +++ b/spring-data-rest-webmvc/src/main/java/org/springframework/data/rest/webmvc/json/patch/PatchOperation.java @@ -64,7 +64,13 @@ protected Object evaluateValueFromTarget(Object targetObject, Class entityTyp } protected final Object evaluate(Class type) { - return value instanceof LateObjectEvaluator ? ((LateObjectEvaluator) value).evaluate(type) : value; + if (value instanceof LateObjectEvaluator) { + return ((LateObjectEvaluator) value).evaluate(type); + } + if (value.getClass() != type) { + throw new PatchException(String.format("Could not read %s into %s", value, type)); + } + return value; } /** diff --git a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationUnitTests.java b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationUnitTests.java index 1cef6f18f..72bccc7c3 100755 --- a/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationUnitTests.java +++ b/spring-data-rest-webmvc/src/test/java/org/springframework/data/rest/webmvc/json/patch/AddOperationUnitTests.java @@ -159,6 +159,21 @@ void manipulatesNestedCollectionProperly() { assertThat(outer.todoList.getTodos()).containsExactly(todos.get(0), todos.get(1), newTodo); } + @Test + void failPrimitiveInNestedObjectCollection() { + List todos = new ArrayList<>(); + todos.add(new Todo(1L, "A", false)); + todos.add(new Todo(2L, "B", false)); + + TodoList todoList = new TodoList(); + todoList.setTodos(todos); + + assertThatExceptionOfType(PatchException.class) + .isThrownBy(() -> AddOperation.of("/todos/-", "Primitive").perform(todoList, TodoList.class, TestPropertyPathContext.INSTANCE)) + .withMessageContaining("Could not read") + .withMessageContaining("into class"); + } + @Data @AllArgsConstructor @NoArgsConstructor