PrettyPrintingJsonBodyFilter implements BodyFilter { @Override public String filter(@Nullable final String contentType, final String body) { if (!JsonMediaType.JSON.test(contentType)) { return body; } if (body.indexOf('\n') != -1) { return body; } try ( final CharArrayWriter output = new CharArrayWriter(body.length() * 2); final JsonParser parser = factory.createParser(body); final JsonGenerator generator = factory.createGenerator(output); ) { generator.useDefaultPrettyPrinter(); while (parser.nextToken() != null) { generator.copyCurrentEvent(parser); } generator.flush(); return output.toString(); } catch (final IOException e) { log.trace("Unable to pretty print body. Is it JSON?. Keep it as-is: `{}`", e.getMessage()); return body; } } PrettyPrintingJsonBodyFilter(final JsonFactory factory);  PrettyPrintingJsonBodyFilter();  PrettyPrintingJsonBodyFilter(final ObjectMapper mapper); @Override String filter(@Nullable final String contentType, final String body);  }
@Test void shouldIgnoreEmptyBody() { assertThat(unit.filter("application/json", ""), is("")); }
@Test void shouldIgnoreInvalidContent() { final String invalidBody = "{\ninvalid}"; final String filtered = unit.filter("application/json", invalidBody); assertThat(filtered, is(invalidBody)); }
@Test void shouldIgnoreInvalidContentType() { final String filtered = unit.filter("text/plain", compacted); assertThat(filtered, is(compacted)); }
@Test void shouldTransformValidJsonRequestWithSimpleContentType() { final String filtered = unit.filter("application/json", compacted); assertThat(filtered, is(pretty)); }
@Test void shouldTransformValidJsonRequestWithCompatibleContentType() { final String filtered = unit.filter("application/custom+json", compacted); assertThat(filtered, is(pretty)); }
@Test void shouldSkipInvalidJsonLookingLikeAValidOne() { final String invalidJson = "{invalid}"; final String filtered = unit.filter("application/custom+json", invalidJson); assertThat(filtered, is(invalidJson)); }
@Test void shouldConstructFromObjectMapper() { BodyFilter bodyFilter = new PrettyPrintingJsonBodyFilter(new ObjectMapper()); final String filtered = bodyFilter.filter("application/json", compacted); assertThat(filtered, is(pretty)); }