Skip to content

Simplify RemoveJsonAttributesResponseBodyGatewayFilterFactory #3776

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2020 the original author or authors.
* Copyright 2013-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -22,7 +22,6 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import reactor.core.publisher.Mono;

Expand All @@ -34,6 +33,7 @@

/**
* @author Marta Medio
* @author raccoonback
*/
public class RemoveJsonAttributesResponseBodyGatewayFilterFactory extends
AbstractGatewayFilterFactory<RemoveJsonAttributesResponseBodyGatewayFilterFactory.FieldListConfiguration> {
Expand Down Expand Up @@ -72,14 +72,14 @@ public GatewayFilter apply(FieldListConfiguration config) {
RewriteFunction<String, String> rewriteFunction = (exchange, body) -> {
if (MediaType.APPLICATION_JSON.isCompatibleWith(exchange.getResponse().getHeaders().getContentType())) {
try {
JsonNode jsonBodyContent = mapper.readValue(body, JsonNode.class);
JsonNode jsonNode = mapper.readValue(body, JsonNode.class);

removeJsonAttribute(jsonBodyContent, config.getFieldList(), config.isDeleteRecursively());
removeJsonAttributes(jsonNode, config.getFieldList(), config.isDeleteRecursively());

body = mapper.writeValueAsString(jsonBodyContent);
body = mapper.writeValueAsString(jsonNode);
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
return Mono.error(new IllegalStateException("Failed to process JSON of response body.", e));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. The caller wraps the error with Mono.error() to preserve the reactive pipeline and allow proper error handling.

  2. The exception type has been explicitly changed to IllegalStateException.

}
}
return Mono.just(body);
Expand All @@ -93,22 +93,12 @@ public GatewayFilter apply(FieldListConfiguration config) {

private ObjectMapper mapper = new ObjectMapper();

private void removeJsonAttribute(JsonNode jsonBodyContent, List<String> fieldsToRemove, boolean deleteRecursively) {
if (deleteRecursively) {
for (JsonNode jsonNode : jsonBodyContent) {
if (jsonNode instanceof ObjectNode) {
((ObjectNode) jsonNode).remove(fieldsToRemove);
removeJsonAttribute(jsonNode, fieldsToRemove, true);
}
if (jsonNode instanceof ArrayNode) {
for (JsonNode node : jsonNode) {
removeJsonAttribute(node, fieldsToRemove, true);
}
}
}
private void removeJsonAttributes(JsonNode jsonNode, List<String> fieldNames, boolean deleteRecursively) {
if (jsonNode instanceof ObjectNode objectNode) {
objectNode.remove(fieldNames);
}
if (jsonBodyContent instanceof ObjectNode) {
((ObjectNode) jsonBodyContent).remove(fieldsToRemove);
if (deleteRecursively) {
jsonNode.forEach(childNode -> removeJsonAttributes(childNode, fieldNames, true));
Comment on lines +96 to +101
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Modified the logic to recursively remove JSON nodes without type distinction, allowing recursive calls regardless of node type.

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.Map;

import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
Expand All @@ -30,8 +31,12 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
Expand All @@ -42,10 +47,10 @@
*/
@SpringBootTest(webEnvironment = RANDOM_PORT)
@DirtiesContext
public class RemoveJsonAttributesResponseBodyGatewayFilterFactoryTests extends BaseWebClientTests {
class RemoveJsonAttributesResponseBodyGatewayFilterFactoryTests extends BaseWebClientTests {

@Test
public void removeJsonAttributeRootWorks() {
void removeJsonAttributeRootWorks() {
testClient.post()
.uri("/post")
.header("Host", "www.removejsonattributes.org")
Expand All @@ -70,8 +75,7 @@ public void removeJsonAttributeRootWorks() {
}

@Test
public void removeJsonAttributeRecursivelyWorks() {

void removeJsonAttributeRecursivelyWorks() {
testClient.post()
.uri("/post")
.header("Host", "www.removejsonattributesrecursively.org")
Expand All @@ -93,8 +97,7 @@ public void removeJsonAttributeRecursivelyWorks() {
}

@Test
public void removeJsonAttributeNoMatchesWorks() {

void removeJsonAttributeNoMatchesWorks() {
testClient.post()
.uri("/post")
.header("Host", "www.removejsonattributesnomatches.org")
Expand All @@ -113,6 +116,21 @@ public void removeJsonAttributeNoMatchesWorks() {
});
}

@Test
void raisedWhenRemoveJsonAttributes() {
testClient.post()
.uri("/post")
.header("Host", "www.raisederrorwhenremovejsonattributes.org")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.exchange()
.expectStatus()
.is5xxServerError()
.expectBody(String.class)
.consumeWith(result -> {
assertThat(result.getResponseBody()).isEqualTo("Failed to process JSON of response body.");
});
}

@EnableAutoConfiguration
@SpringBootConfiguration
@Import(DefaultTestConfig.class)
Expand Down Expand Up @@ -142,9 +160,27 @@ public RouteLocator testRouteLocator(RouteLocatorBuilder builder) {
.host("{sub}.removejsonattributesnomatches.org")
.filters(f -> f.removeJsonAttributes("test"))
.uri(uri))
.route("raised_error_when_remove_json_attributes",
r -> r.path("/post")
.and()
.host("{sub}.raisederrorwhenremovejsonattributes.org")
.filters(f -> f.removeJsonAttributes("test")
.modifyResponseBody(String.class, String.class,
(exchange, response) -> Mono.just("{\"invalid_json\": test")))
.uri(uri))
.build();
}

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(IllegalStateException.class)
public ResponseEntity<String> handleIllegalException(IllegalStateException ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}

}

}

}
Loading