This commit is contained in:
Moritz Halbritter 2024-07-29 10:30:33 +02:00
parent 3da45aabbf
commit 870b02b4d3
7 changed files with 30 additions and 36 deletions

View File

@ -26,6 +26,7 @@ import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.springframework.boot.json.JsonWriter.WritableJson;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.function.ThrowingConsumer;
@ -57,7 +58,6 @@ class JsonValueWriter {
* @param name the name of the pair or {@code null} if only the value should be
* written
* @param value the value
* @on IO error
*/
<N, V> void write(N name, V value) {
if (name != null) {
@ -81,7 +81,6 @@ class JsonValueWriter {
* All other values are written as JSON strings.
* @param <V> the value type
* @param value the value to write
* @on IO error
*/
<V> void write(V value) {
if (value == null) {
@ -118,7 +117,6 @@ class JsonValueWriter {
/**
* Start a new {@link Series} (JSON object or array).
* @param series the series to start
* @on IO error
* @see #end(Series)
* @see #writePairs(Consumer)
* @see #writeElements(Consumer)
@ -133,7 +131,6 @@ class JsonValueWriter {
/**
* End an active {@link Series} (JSON object or array).
* @param series the series type being ended (must match {@link #start(Series)})
* @on IO error
* @see #start(Series)
*/
void end(Series series) {
@ -148,7 +145,6 @@ class JsonValueWriter {
* @param <E> the element type
* @param elements a callback that will be used to provide each element. Typically a
* {@code forEach} method reference.
* @on IO error
* @see #writeElements(Consumer)
*/
<E> void writeArray(Consumer<Consumer<E>> elements) {
@ -171,6 +167,7 @@ class JsonValueWriter {
<E> void writeElement(E element) {
ActiveSeries activeSeries = this.activeSeries.peek();
Assert.notNull(activeSeries, "No series has been started");
activeSeries.appendCommaIfRequired();
write(element);
}
@ -181,7 +178,6 @@ class JsonValueWriter {
* @param <V> the value type in the pair
* @param pairs a callback that will be used to provide each pair. Typically a
* {@code forEach} method reference.
* @on IO error
* @see #writePairs(Consumer)
*/
<N, V> void writeObject(Consumer<BiConsumer<N, V>> pairs) {
@ -205,6 +201,7 @@ class JsonValueWriter {
private <N, V> void writePair(N name, V value) {
ActiveSeries activeSeries = this.activeSeries.peek();
Assert.notNull(activeSeries, "No series has been started");
activeSeries.appendCommaIfRequired();
writeString(name);
append(":");

View File

@ -44,8 +44,7 @@ import org.springframework.util.StringUtils;
/**
* Interface that can be used to write JSON output. Typically used to generate JSON when a
* a dependency on a fully marshalling library (such as Jackson or Gson) cannot be
* assumed.
* dependency on a fully marshalling library (such as Jackson or Gson) cannot be assumed.
* <p>
* For standard Java types, the {@link #standard()} factory method may be used to obtain
* an instance of this interface. It supports {@link String}, {@link Number} and
@ -143,7 +142,7 @@ public interface JsonWriter<T> {
* @return a {@link JsonWriter} instance
*/
static <T> JsonWriter<T> standard() {
return of((members) -> members.addSelf());
return of(Members::addSelf);
}
/**
@ -151,13 +150,13 @@ public interface JsonWriter<T> {
* mapping}. See {@link JsonValueWriter class-level javadoc} and {@link Members} for
* details.
* @param <T> the type to write
* @param members a consumer which should configure the members
* @param members a consumer, which should configure the members
* @return a {@link JsonWriter} instance
* @see Members
*/
static <T> JsonWriter<T> of(Consumer<Members<T>> members) {
Members<T> initiaizedMembers = new Members<>(members, false); // Don't inline
return (instance, out) -> initiaizedMembers.write(instance, new JsonValueWriter(out));
Members<T> initializedMembers = new Members<>(members, false); // Don't inline
return (instance, out) -> initializedMembers.write(instance, new JsonValueWriter(out));
}
/**
@ -202,6 +201,7 @@ public interface JsonWriter<T> {
* @return the JSON bytes
*/
default byte[] toByteArray(Charset charset) {
Assert.notNull(charset, "'charset' must not be null");
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
toWriter(new OutputStreamWriter(out, charset));
return out.toByteArray();
@ -303,7 +303,7 @@ public interface JsonWriter<T> {
/**
* Callback used to configure JSON members. Individual members can be declared using
* the various {@code add(...)} methods. Typically members are declared with a
* the various {@code add(...)} methods. Typically, members are declared with a
* {@code "name"} and a {@link Function} that will extract the value from the
* instance. Members can also be declared using a static value or a {@link Supplier}.
* The {@link #addSelf(String)} and {@link #addSelf()} methods may be used to access
@ -473,7 +473,7 @@ public interface JsonWriter<T> {
}
/**
* A member that contributes JSON. Typically a member will contribute a single
* A member that contributes JSON. Typically, a member will contribute a single
* name/value pair based on an extracted value. They may also contribute more complex
* JSON structures when configured with one of the {@code using(...)} methods.
* <p>
@ -520,7 +520,7 @@ public interface JsonWriter<T> {
}
/**
* Only include this member when its not {@code null} and has a
* Only include this member when it is not {@code null} and has a
* {@link Object#toString() toString()} that is not zero length.
* @return a {@link Member} which may be configured further
* @see StringUtils#hasLength(CharSequence)
@ -530,7 +530,7 @@ public interface JsonWriter<T> {
}
/**
* Only include this member when its not empty (See
* Only include this member when it is not empty (See
* {@link ObjectUtils#isEmpty(Object)} for details).
* @return a {@link Member} which may be configured further
*/
@ -603,16 +603,13 @@ public interface JsonWriter<T> {
* }
* </pre>
* @param <E> the element type
* @param <N> the name type
* @param <V> the value type
* @param elements callback used to provide the elements
* @param extractor a {@link PairExtractor} used to extract the name/value pair
* @return a {@link Member} which may be configured further
* @see #usingExtractedPairs(BiConsumer, Function, Function)
* @see #usingPairs(BiConsumer)
*/
public <E, N, V> Member<T> usingExtractedPairs(BiConsumer<T, Consumer<E>> elements,
PairExtractor<E> extractor) {
public <E> Member<T> usingExtractedPairs(BiConsumer<T, Consumer<E>> elements, PairExtractor<E> extractor) {
Assert.notNull(elements, "'elements' must not be null");
Assert.notNull(extractor, "'extractor' must not be null");
return usingExtractedPairs(elements, extractor::getName, extractor::getValue);
@ -784,8 +781,8 @@ public interface JsonWriter<T> {
}
/**
* Return if this members contributes one or more name/value pairs to the JSON.
* @return if a name/value pair is contributed
* Whether this contributes one or more name/value pairs to the JSON.
* @return whether a name/value pair is contributed
*/
boolean contributesPair() {
return this.name != null || this.pairs != null || (this.members != null && this.members.contributesPair());

View File

@ -62,7 +62,7 @@ class ElasticCommonSchemaStructuredLogFormatter extends JsonWriterStructuredLogF
members.addSelf().whenNotNull(ILoggingEvent::getThrowableProxy).usingMembers((throwableMembers) -> {
throwableMembers.add("error.type", ILoggingEvent::getThrowableProxy).as(IThrowableProxy::getClassName);
throwableMembers.add("error.message", ILoggingEvent::getThrowableProxy).as(IThrowableProxy::getMessage);
throwableMembers.add("error.stack_trace", (event) -> throwableProxyConverter.convert(event));
throwableMembers.add("error.stack_trace", throwableProxyConverter::convert);
});
members.add("ecs.version", "8.11");
}

View File

@ -37,7 +37,7 @@ public abstract class JsonWriterStructuredLogFormatter<E> implements StructuredL
/**
* Create a new {@link JsonWriterStructuredLogFormatter} instance with the given
* members.
* @param members a consumer which should configure the members
* @param members a consumer, which should configure the members
*/
protected JsonWriterStructuredLogFormatter(Consumer<Members<E>> members) {
this(JsonWriter.of(members).withNewLineAtEnd());
@ -59,7 +59,7 @@ public abstract class JsonWriterStructuredLogFormatter<E> implements StructuredL
@Override
public byte[] formatAsBytes(E event, Charset charset) {
return this.jsonWriter.write(event).toByteArray();
return this.jsonWriter.write(event).toByteArray(charset);
}
}

View File

@ -42,7 +42,7 @@ import org.springframework.util.Assert;
*/
public class StructuredLogFormatterFactory<E> {
private static FailureHandler failureHandler = (type, implementationName, failure) -> {
private static final FailureHandler failureHandler = (type, implementationName, failure) -> {
if (!(failure instanceof ClassNotFoundException)) {
throw new IllegalArgumentException(
"Unable to instantiate " + implementationName + " [" + type.getName() + "]", failure);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2023 the original author or authors.
* Copyright 2012-2024 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.
@ -50,7 +50,7 @@ public class ApplicationPid {
private Long currentProcessPid() {
try {
return Long.valueOf(ProcessHandle.current().pid());
return ProcessHandle.current().pid();
}
catch (Throwable ex) {
return null;

View File

@ -109,25 +109,25 @@ public class JsonWriterTests {
}
@Test
void ofAddingUnamedSelf() {
void ofAddingUnnamedSelf() {
JsonWriter<Person> writer = JsonWriter.of((members) -> members.addSelf());
assertThat(writer.writeToString(PERSON)).isEqualTo(quoted("Spring Boot (10)"));
}
@Test
void ofAddingUnamedValue() {
void ofAddingUnnamedValue() {
JsonWriter<Person> writer = JsonWriter.of((members) -> members.add("Boot"));
assertThat(writer.writeToString(PERSON)).isEqualTo(quoted("Boot"));
}
@Test
void ofAddingUnamedSupplier() {
void ofAddingUnnamedSupplier() {
JsonWriter<Person> writer = JsonWriter.of((members) -> members.add(() -> "Boot"));
assertThat(writer.writeToString(PERSON)).isEqualTo(quoted("Boot"));
}
@Test
void ofAddingUnamedExtractor() {
void ofAddingUnnamedExtractor() {
JsonWriter<Person> writer = JsonWriter.of((members) -> members.add(Person::lastName));
assertThat(writer.writeToString(PERSON)).isEqualTo(quoted("Boot"));
}
@ -162,7 +162,7 @@ public class JsonWriterTests {
}
@Test
void ofWhenOneContibutesPairByNameAndOneHasNoNameThrowsException() {
void ofWhenOneContributesPairByNameAndOneHasNoNameThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> JsonWriter.of((members) -> {
members.add("Spring", "Boot");
members.add("alone");
@ -172,7 +172,7 @@ public class JsonWriterTests {
}
@Test
void ofWhenOneContibutesPairByUsingPairsAndOneHasNoNameThrowsException() {
void ofWhenOneContributesPairByUsingPairsAndOneHasNoNameThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> JsonWriter.of((members) -> {
members.add(Map.of("Spring", "Boot")).usingPairs(Map::forEach);
members.add("alone");
@ -182,7 +182,7 @@ public class JsonWriterTests {
}
@Test
void ofWhenOneContibutesPairByUsingMembersAndOneHasNoNameThrowsException() {
void ofWhenOneContributesPairByUsingMembersAndOneHasNoNameThrowsException() {
assertThatIllegalStateException().isThrownBy(() -> JsonWriter.of((members) -> {
members.add(PERSON).usingMembers((personMembers) -> {
personMembers.add("first", Person::firstName);
@ -260,7 +260,7 @@ public class JsonWriterTests {
void whenHasLengthOnNonString() {
JsonWriter<StringBuilder> writer = JsonWriter.of((members) -> members.addSelf().whenHasLength());
assertThat(writer.writeToString(new StringBuilder("test"))).isEqualTo(quoted("test"));
assertThat(writer.writeToString(new StringBuilder(""))).isEmpty();
assertThat(writer.writeToString(new StringBuilder())).isEmpty();
assertThat(writer.writeToString(null)).isEmpty();
}