Support CBOR and Protobuf with Kotlin Serialization
This commit introduces support for CBOR and Protobuf using Kotlin serialization. Support comes in the form of Encoder/Decoder as well as HttpMessageConverters. Seperate abstract base classes supply support for binary and string (de)serialization. The exising JSON codecs and message converters have been migrated to use the new base classes. Closes gh-27628
This commit is contained in:
committed by
Arjen Poutsma
parent
b6c2e8de23
commit
b8243e6f84
@@ -217,6 +217,18 @@ public class MediaType extends MimeType implements Serializable {
|
||||
*/
|
||||
public static final String APPLICATION_PROBLEM_XML_VALUE = "application/problem+xml";
|
||||
|
||||
/**
|
||||
* Public constant media type for {@code application/x-protobuf}.
|
||||
* @since 6.0
|
||||
*/
|
||||
public static final MediaType APPLICATION_PROTOBUF;
|
||||
|
||||
/**
|
||||
* A String equivalent of {@link MediaType#APPLICATION_PROTOBUF}.
|
||||
* @since 6.0
|
||||
*/
|
||||
public static final String APPLICATION_PROTOBUF_VALUE = "application/x-protobuf";
|
||||
|
||||
/**
|
||||
* Public constant media type for {@code application/rss+xml}.
|
||||
* @since 4.3.6
|
||||
@@ -418,6 +430,7 @@ public class MediaType extends MimeType implements Serializable {
|
||||
APPLICATION_PROBLEM_JSON = new MediaType("application", "problem+json");
|
||||
APPLICATION_PROBLEM_JSON_UTF8 = new MediaType("application", "problem+json", StandardCharsets.UTF_8);
|
||||
APPLICATION_PROBLEM_XML = new MediaType("application", "problem+xml");
|
||||
APPLICATION_PROTOBUF = new MediaType("application", "x-protobuf");
|
||||
APPLICATION_RSS_XML = new MediaType("application", "rss+xml");
|
||||
APPLICATION_STREAM_JSON = new MediaType("application", "stream+json");
|
||||
APPLICATION_XHTML_XML = new MediaType("application", "xhtml+xml");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 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.
|
||||
@@ -176,6 +176,22 @@ public interface CodecConfigurer {
|
||||
*/
|
||||
void jaxb2Encoder(Encoder<?> encoder);
|
||||
|
||||
/**
|
||||
* Override the default Kotlin Serialization CBOR {@code Decoder}.
|
||||
* @param decoder the decoder instance to use
|
||||
* @since 6.0
|
||||
* @see org.springframework.http.codec.cbor.KotlinSerializationCborDecoder
|
||||
*/
|
||||
void kotlinSerializationCborDecoder(Decoder<?> decoder);
|
||||
|
||||
/**
|
||||
* Override the default Kotlin Serialization CBOR {@code Encoder}.
|
||||
* @param encoder the encoder instance to use
|
||||
* @since 6.0
|
||||
* @see org.springframework.http.codec.cbor.KotlinSerializationCborDecoder
|
||||
*/
|
||||
void kotlinSerializationCborEncoder(Encoder<?> encoder);
|
||||
|
||||
/**
|
||||
* Override the default Kotlin Serialization JSON {@code Decoder}.
|
||||
* @param decoder the decoder instance to use
|
||||
@@ -192,6 +208,22 @@ public interface CodecConfigurer {
|
||||
*/
|
||||
void kotlinSerializationJsonEncoder(Encoder<?> encoder);
|
||||
|
||||
/**
|
||||
* Override the default Kotlin Serialization Protobuf {@code Decoder}.
|
||||
* @param decoder the decoder instance to use
|
||||
* @since 6.0
|
||||
* @see org.springframework.http.codec.protobuf.KotlinSerializationProtobufDecoder
|
||||
*/
|
||||
void kotlinSerializationProtobufDecoder(Decoder<?> decoder);
|
||||
|
||||
/**
|
||||
* Override the default Kotlin Serialization Protobuf {@code Encoder}.
|
||||
* @param encoder the encoder instance to use
|
||||
* @since 6.0
|
||||
* @see org.springframework.http.codec.protobuf.KotlinSerializationProtobufEncoder
|
||||
*/
|
||||
void kotlinSerializationProtobufEncoder(Encoder<?> encoder);
|
||||
|
||||
/**
|
||||
* Register a consumer to apply to default config instances. This can be
|
||||
* used to configure rather than replace a specific codec or multiple
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import kotlinx.serialization.BinaryFormat;
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.ByteArrayDecoder;
|
||||
import org.springframework.core.codec.Decoder;
|
||||
import org.springframework.core.codec.DecodingException;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.MimeType;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link Decoder} implementations that defer to Kotlin
|
||||
* {@linkplain BinaryFormat binary serializers}.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link BinaryFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationBinaryDecoder<T extends BinaryFormat> extends KotlinSerializationSupport<T>
|
||||
implements Decoder<Object> {
|
||||
|
||||
// Byte array decoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final ByteArrayDecoder byteArrayDecoder = new ByteArrayDecoder();
|
||||
|
||||
|
||||
public KotlinSerializationBinaryDecoder(T format, MimeType... supportedMimeTypes) {
|
||||
super(format, supportedMimeTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure a limit on the number of bytes that can be buffered whenever
|
||||
* the input stream needs to be aggregated. This can be a result of
|
||||
* decoding to a single {@code DataBuffer},
|
||||
* {@link java.nio.ByteBuffer ByteBuffer}, {@code byte[]},
|
||||
* {@link org.springframework.core.io.Resource Resource}, {@code String}, etc.
|
||||
* It can also occur when splitting the input stream, e.g. delimited text,
|
||||
* in which case the limit applies to data buffered between delimiters.
|
||||
* <p>By default this is set to 256K.
|
||||
* @param byteCount the max number of bytes to buffer, or -1 for unlimited
|
||||
*/
|
||||
public void setMaxInMemorySize(int byteCount) {
|
||||
this.byteArrayDecoder.setMaxInMemorySize(byteCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the {@link #setMaxInMemorySize configured} byte count limit.
|
||||
*/
|
||||
public int getMaxInMemorySize() {
|
||||
return this.byteArrayDecoder.getMaxInMemorySize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return canSerialize(elementType, mimeType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getDecodableMimeTypes() {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getDecodableMimeTypes(ResolvableType targetType) {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType,
|
||||
@Nullable Map<String, Object> hints) {
|
||||
|
||||
return Flux.error(new UnsupportedOperationException());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Object> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
return Mono.defer(() -> {
|
||||
KSerializer<Object> serializer = serializer(elementType);
|
||||
if (serializer == null) {
|
||||
return Mono.error(new DecodingException("Could not find KSerializer for " + elementType));
|
||||
}
|
||||
return this.byteArrayDecoder
|
||||
.decodeToMono(inputStream, elementType, mimeType, hints)
|
||||
.map(byteArray -> format().decodeFromByteArray(serializer, byteArray));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import kotlinx.serialization.BinaryFormat;
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.ByteArrayEncoder;
|
||||
import org.springframework.core.codec.Encoder;
|
||||
import org.springframework.core.codec.EncodingException;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.MimeType;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link Encoder} implementations that defer to Kotlin
|
||||
* {@linkplain BinaryFormat binary serializers}.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link BinaryFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationBinaryEncoder<T extends BinaryFormat> extends KotlinSerializationSupport<T>
|
||||
implements Encoder<Object> {
|
||||
|
||||
// ByteArraySequence encoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final ByteArrayEncoder byteArrayEncoder = new ByteArrayEncoder();
|
||||
|
||||
protected KotlinSerializationBinaryEncoder(T format, MimeType... supportedMimeTypes) {
|
||||
super(format, supportedMimeTypes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return canSerialize(elementType, mimeType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getEncodableMimeTypes() {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getEncodableMimeTypes(ResolvableType elementType) {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
|
||||
ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
if (inputStream instanceof Mono) {
|
||||
return Mono.from(inputStream)
|
||||
.map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
else {
|
||||
ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
|
||||
return Flux.from(inputStream)
|
||||
.collectList()
|
||||
.map(list -> encodeValue(list, bufferFactory, listType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
KSerializer<Object> serializer = serializer(valueType);
|
||||
if (serializer == null) {
|
||||
throw new EncodingException("Could not find KSerializer for " + valueType);
|
||||
}
|
||||
byte[] bytes = format().encodeToByteArray(serializer, value);
|
||||
return this.byteArrayEncoder.encodeValue(bytes, bufferFactory, valueType, mimeType, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.StringFormat;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.Decoder;
|
||||
import org.springframework.core.codec.DecodingException;
|
||||
import org.springframework.core.codec.StringDecoder;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.MimeType;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link Decoder} implementations that defer to Kotlin
|
||||
* {@linkplain StringFormat string serializers}.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link StringFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationStringDecoder<T extends StringFormat> extends KotlinSerializationSupport<T>
|
||||
implements Decoder<Object> {
|
||||
|
||||
// String decoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final StringDecoder stringDecoder = StringDecoder.allMimeTypes(StringDecoder.DEFAULT_DELIMITERS, false);
|
||||
|
||||
|
||||
public KotlinSerializationStringDecoder(T format, MimeType... supportedMimeTypes) {
|
||||
super(format, supportedMimeTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure a limit on the number of bytes that can be buffered whenever
|
||||
* the input stream needs to be aggregated. This can be a result of
|
||||
* decoding to a single {@code DataBuffer},
|
||||
* {@link java.nio.ByteBuffer ByteBuffer}, {@code byte[]},
|
||||
* {@link org.springframework.core.io.Resource Resource}, {@code String}, etc.
|
||||
* It can also occur when splitting the input stream, e.g. delimited text,
|
||||
* in which case the limit applies to data buffered between delimiters.
|
||||
* <p>By default this is set to 256K.
|
||||
* @param byteCount the max number of bytes to buffer, or -1 for unlimited
|
||||
*/
|
||||
public void setMaxInMemorySize(int byteCount) {
|
||||
this.stringDecoder.setMaxInMemorySize(byteCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the {@link #setMaxInMemorySize configured} byte count limit.
|
||||
*/
|
||||
public int getMaxInMemorySize() {
|
||||
return this.stringDecoder.getMaxInMemorySize();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return canSerialize(elementType, mimeType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getDecodableMimeTypes() {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getDecodableMimeTypes(ResolvableType targetType) {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType,
|
||||
@Nullable Map<String, Object> hints) {
|
||||
return Flux.error(new UnsupportedOperationException());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Object> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
return Mono.defer(() -> {
|
||||
KSerializer<Object> serializer = serializer(elementType);
|
||||
if (serializer == null) {
|
||||
return Mono.error(new DecodingException("Could not find KSerializer for " + elementType));
|
||||
}
|
||||
return this.stringDecoder
|
||||
.decodeToMono(inputStream, elementType, mimeType, hints)
|
||||
.map(string -> format().decodeFromString(serializer, string));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.StringFormat;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.CharSequenceEncoder;
|
||||
import org.springframework.core.codec.Encoder;
|
||||
import org.springframework.core.codec.EncodingException;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.MimeType;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link Encoder} implementations that defer to Kotlin
|
||||
* {@linkplain StringFormat string serializers}.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link StringFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationStringEncoder<T extends StringFormat> extends KotlinSerializationSupport<T>
|
||||
implements Encoder<Object> {
|
||||
|
||||
// CharSequence encoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final CharSequenceEncoder charSequenceEncoder = CharSequenceEncoder.allMimeTypes();
|
||||
|
||||
protected KotlinSerializationStringEncoder(T format, MimeType... supportedMimeTypes) {
|
||||
super(format, supportedMimeTypes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return canSerialize(elementType, mimeType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getEncodableMimeTypes() {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MimeType> getEncodableMimeTypes(ResolvableType elementType) {
|
||||
return supportedMimeTypes();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
|
||||
ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
if (inputStream instanceof Mono) {
|
||||
return Mono.from(inputStream)
|
||||
.map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
else {
|
||||
ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
|
||||
return Flux.from(inputStream)
|
||||
.collectList()
|
||||
.map(list -> encodeValue(list, bufferFactory, listType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
|
||||
ResolvableType valueType, @Nullable MimeType mimeType,
|
||||
@Nullable Map<String, Object> hints) {
|
||||
|
||||
KSerializer<Object> serializer = serializer(valueType);
|
||||
if (serializer == null) {
|
||||
throw new EncodingException("Could not find KSerializer for " + valueType);
|
||||
}
|
||||
String string = format().encodeToString(serializer, value);
|
||||
return this.charSequenceEncoder.encodeValue(string, bufferFactory, valueType, mimeType, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerialFormat;
|
||||
import kotlinx.serialization.SerializersKt;
|
||||
import kotlinx.serialization.descriptors.PolymorphicKind;
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
import org.springframework.util.MimeType;
|
||||
|
||||
/**
|
||||
* Base class providing support methods for encoding and decoding with Kotlin
|
||||
* serialization.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link SerialFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationSupport<T extends SerialFormat> {
|
||||
|
||||
private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
|
||||
private final T format;
|
||||
|
||||
private final List<MimeType> supportedMimeTypes;
|
||||
|
||||
/**
|
||||
* Creates a new instance of this support class with the given format
|
||||
* and supported mime types.
|
||||
*/
|
||||
protected KotlinSerializationSupport(T format, MimeType... supportedMimeTypes) {
|
||||
this.format = format;
|
||||
this.supportedMimeTypes = Arrays.asList(supportedMimeTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the format.
|
||||
*/
|
||||
protected final T format() {
|
||||
return this.format;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the supported mime types.
|
||||
*/
|
||||
protected final List<MimeType> supportedMimeTypes() {
|
||||
return this.supportedMimeTypes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates whether the given type can be serialized using Kotlin
|
||||
* serialization.
|
||||
* @param type the type to be serialized
|
||||
* @param mimeType the mimetype to use (can be {@code null})
|
||||
* @return {@code true} if {@code type} can be serialized; false otherwise
|
||||
*/
|
||||
protected final boolean canSerialize(ResolvableType type, @Nullable MimeType mimeType) {
|
||||
KSerializer<Object> serializer = serializer(type);
|
||||
if (serializer == null) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return (supports(mimeType) && !String.class.isAssignableFrom(type.toClass()) &&
|
||||
!ServerSentEvent.class.isAssignableFrom(type.toClass()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean supports(@Nullable MimeType mimeType) {
|
||||
if (mimeType == null) {
|
||||
return true;
|
||||
}
|
||||
for (MimeType candidate : this.supportedMimeTypes) {
|
||||
if (candidate.isCompatibleWith(mimeType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the serializer that can (de)serialize instances of the given
|
||||
* type. If no serializer can be found, or if {@code resolvableType} is
|
||||
* a <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic</a>
|
||||
* type, {@code null} is returned.
|
||||
* @param resolvableType the type to find a serializer for
|
||||
* @return a resolved serializer for the given type, or {@code null}
|
||||
*/
|
||||
@Nullable
|
||||
protected final KSerializer<Object> serializer(ResolvableType resolvableType) {
|
||||
Type type = resolvableType.getType();
|
||||
KSerializer<Object> serializer = serializerCache.get(type);
|
||||
if (serializer == null) {
|
||||
try {
|
||||
serializer = SerializersKt.serializerOrNull(type);
|
||||
}
|
||||
catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (serializer != null) {
|
||||
if (hasPolymorphism(serializer.getDescriptor(), new HashSet<>())) {
|
||||
return null;
|
||||
}
|
||||
serializerCache.put(type, serializer);
|
||||
}
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
|
||||
private static boolean hasPolymorphism(SerialDescriptor descriptor, Set<String> alreadyProcessed) {
|
||||
alreadyProcessed.add(descriptor.getSerialName());
|
||||
if (descriptor.getKind().equals(PolymorphicKind.OPEN.INSTANCE)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0 ; i < descriptor.getElementsCount() ; i++) {
|
||||
SerialDescriptor elementDescriptor = descriptor.getElementDescriptor(i);
|
||||
if (!alreadyProcessed.contains(elementDescriptor.getSerialName()) && hasPolymorphism(elementDescriptor, alreadyProcessed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec.cbor;
|
||||
|
||||
import kotlinx.serialization.cbor.Cbor;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.codec.KotlinSerializationBinaryDecoder;
|
||||
|
||||
/**
|
||||
* Decode a byte stream into CBOR and convert to Objects with
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This decoder can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/cbor}.
|
||||
*
|
||||
* <p>Decoding streams is not supported yet, see
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/issues/1073">kotlinx.serialization/issues/1073</a>
|
||||
* related issue.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationCborDecoder extends KotlinSerializationBinaryDecoder<Cbor> {
|
||||
|
||||
public KotlinSerializationCborDecoder() {
|
||||
this(Cbor.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationCborDecoder(Cbor cbor) {
|
||||
super(cbor, MediaType.APPLICATION_CBOR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec.cbor;
|
||||
|
||||
import kotlinx.serialization.cbor.Cbor;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.codec.KotlinSerializationBinaryEncoder;
|
||||
|
||||
/**
|
||||
* Encode from an {@code Object} stream to a byte stream of CBOR objects using
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This encoder can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/cbor}.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationCborEncoder extends KotlinSerializationBinaryEncoder<Cbor> {
|
||||
|
||||
public KotlinSerializationCborEncoder() {
|
||||
this(Cbor.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationCborEncoder(Cbor cbor) {
|
||||
super(cbor, MediaType.APPLICATION_CBOR);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,28 +16,10 @@
|
||||
|
||||
package org.springframework.http.codec.json;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerializersKt;
|
||||
import kotlinx.serialization.descriptors.PolymorphicKind;
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor;
|
||||
import kotlinx.serialization.json.Json;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.AbstractDecoder;
|
||||
import org.springframework.core.codec.StringDecoder;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
import org.springframework.util.MimeType;
|
||||
import org.springframework.http.codec.KotlinSerializationStringDecoder;
|
||||
|
||||
/**
|
||||
* Decode a byte stream into JSON and convert to Object's with
|
||||
@@ -54,110 +36,17 @@ import org.springframework.util.MimeType;
|
||||
* related issue.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @since 5.3
|
||||
*/
|
||||
public class KotlinSerializationJsonDecoder extends AbstractDecoder<Object> {
|
||||
|
||||
private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
private final Json json;
|
||||
|
||||
// String decoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final StringDecoder stringDecoder = StringDecoder.allMimeTypes(StringDecoder.DEFAULT_DELIMITERS, false);
|
||||
|
||||
public class KotlinSerializationJsonDecoder extends KotlinSerializationStringDecoder<Json> {
|
||||
|
||||
public KotlinSerializationJsonDecoder() {
|
||||
this(Json.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationJsonDecoder(Json json) {
|
||||
super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure a limit on the number of bytes that can be buffered whenever
|
||||
* the input stream needs to be aggregated. This can be a result of
|
||||
* decoding to a single {@code DataBuffer},
|
||||
* {@link java.nio.ByteBuffer ByteBuffer}, {@code byte[]},
|
||||
* {@link org.springframework.core.io.Resource Resource}, {@code String}, etc.
|
||||
* It can also occur when splitting the input stream, e.g. delimited text,
|
||||
* in which case the limit applies to data buffered between delimiters.
|
||||
* <p>By default this is set to 256K.
|
||||
* @param byteCount the max number of bytes to buffer, or -1 for unlimited
|
||||
*/
|
||||
public void setMaxInMemorySize(int byteCount) {
|
||||
this.stringDecoder.setMaxInMemorySize(byteCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the {@link #setMaxInMemorySize configured} byte count limit.
|
||||
*/
|
||||
public int getMaxInMemorySize() {
|
||||
return this.stringDecoder.getMaxInMemorySize();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return (serializer(elementType.getType()) != null &&
|
||||
super.canDecode(elementType, mimeType) &&
|
||||
!CharSequence.class.isAssignableFrom(elementType.toClass()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
return Flux.error(new UnsupportedOperationException());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Object> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType,
|
||||
@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
return this.stringDecoder
|
||||
.decodeToMono(inputStream, elementType, mimeType, hints)
|
||||
.map(jsonText -> this.json.decodeFromString(serializer(elementType.getType()), jsonText));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to find a serializer that can marshall or unmarshall instances of the given type
|
||||
* using kotlinx.serialization. If no serializer can be found, an exception is thrown.
|
||||
* <p>Resolved serializers are cached and cached results are returned on successive calls.
|
||||
* @param type the type to find a serializer for
|
||||
* @return a resolved serializer for the given type or {@code null} if no serializer
|
||||
* supporting the given type can be found
|
||||
*/
|
||||
@Nullable
|
||||
private KSerializer<Object> serializer(Type type) {
|
||||
KSerializer<Object> serializer = serializerCache.get(type);
|
||||
if (serializer == null) {
|
||||
try {
|
||||
serializer = SerializersKt.serializerOrNull(type);
|
||||
}
|
||||
catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (serializer == null || hasPolymorphism(serializer.getDescriptor(), new HashSet<>())) {
|
||||
return null;
|
||||
}
|
||||
serializerCache.put(type, serializer);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
|
||||
private boolean hasPolymorphism(SerialDescriptor descriptor, Set<String> alreadyProcessed) {
|
||||
alreadyProcessed.add(descriptor.getSerialName());
|
||||
if (descriptor.getKind().equals(PolymorphicKind.OPEN.INSTANCE)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0 ; i < descriptor.getElementsCount() ; i++) {
|
||||
SerialDescriptor elementDescriptor = descriptor.getElementDescriptor(i);
|
||||
if (!alreadyProcessed.contains(elementDescriptor.getSerialName()) && hasPolymorphism(elementDescriptor, alreadyProcessed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
super(json, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,31 +16,10 @@
|
||||
|
||||
package org.springframework.http.codec.json;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerializersKt;
|
||||
import kotlinx.serialization.descriptors.PolymorphicKind;
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor;
|
||||
import kotlinx.serialization.json.Json;
|
||||
import org.reactivestreams.Publisher;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.core.codec.AbstractEncoder;
|
||||
import org.springframework.core.codec.CharSequenceEncoder;
|
||||
import org.springframework.core.io.buffer.DataBuffer;
|
||||
import org.springframework.core.io.buffer.DataBufferFactory;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.codec.ServerSentEvent;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
import org.springframework.util.MimeType;
|
||||
import org.springframework.http.codec.KotlinSerializationStringEncoder;
|
||||
|
||||
/**
|
||||
* Encode from an {@code Object} stream to a byte stream of JSON objects using
|
||||
@@ -53,99 +32,17 @@ import org.springframework.util.MimeType;
|
||||
* various character sets, {@code UTF-8} being the default.
|
||||
*
|
||||
* @author Sebastien Deleuze
|
||||
* @author Iain Henderson
|
||||
* @since 5.3
|
||||
*/
|
||||
public class KotlinSerializationJsonEncoder extends AbstractEncoder<Object> {
|
||||
|
||||
private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
private final Json json;
|
||||
|
||||
// CharSequence encoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
|
||||
private final CharSequenceEncoder charSequenceEncoder = CharSequenceEncoder.allMimeTypes();
|
||||
|
||||
public class KotlinSerializationJsonEncoder extends KotlinSerializationStringEncoder<Json> {
|
||||
|
||||
public KotlinSerializationJsonEncoder() {
|
||||
this(Json.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationJsonEncoder(Json json) {
|
||||
super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
this.json = json;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
|
||||
return (serializer(elementType.getType()) != null &&
|
||||
super.canEncode(elementType, mimeType) &&
|
||||
!String.class.isAssignableFrom(elementType.toClass()) &&
|
||||
!ServerSentEvent.class.isAssignableFrom(elementType.toClass()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
|
||||
ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
if (inputStream instanceof Mono) {
|
||||
return Mono.from(inputStream)
|
||||
.map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
else {
|
||||
ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
|
||||
return Flux.from(inputStream)
|
||||
.collectList()
|
||||
.map(list -> encodeValue(list, bufferFactory, listType, mimeType, hints))
|
||||
.flux();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
|
||||
ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
|
||||
|
||||
String json = this.json.encodeToString(serializer(valueType.getType()), value);
|
||||
return this.charSequenceEncoder.encodeValue(json, bufferFactory, valueType, mimeType, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to find a serializer that can marshall or unmarshall instances of the given type
|
||||
* using kotlinx.serialization. If no serializer can be found, an exception is thrown.
|
||||
* <p>Resolved serializers are cached and cached results are returned on successive calls.
|
||||
* @param type the type to find a serializer for
|
||||
* @return a resolved serializer for the given type or {@code null} if no serializer
|
||||
* supporting the given type can be found
|
||||
*/
|
||||
@Nullable
|
||||
private KSerializer<Object> serializer(Type type) {
|
||||
KSerializer<Object> serializer = serializerCache.get(type);
|
||||
if (serializer == null) {
|
||||
try {
|
||||
serializer = SerializersKt.serializerOrNull(type);
|
||||
}
|
||||
catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (serializer == null || hasPolymorphism(serializer.getDescriptor(), new HashSet<>())) {
|
||||
return null;
|
||||
}
|
||||
serializerCache.put(type, serializer);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
|
||||
private boolean hasPolymorphism(SerialDescriptor descriptor, Set<String> alreadyProcessed) {
|
||||
alreadyProcessed.add(descriptor.getSerialName());
|
||||
if (descriptor.getKind().equals(PolymorphicKind.OPEN.INSTANCE)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0 ; i < descriptor.getElementsCount() ; i++) {
|
||||
SerialDescriptor elementDescriptor = descriptor.getElementDescriptor(i);
|
||||
if (!alreadyProcessed.contains(elementDescriptor.getSerialName()) && hasPolymorphism(elementDescriptor, alreadyProcessed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
super(json, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec.protobuf;
|
||||
|
||||
import kotlinx.serialization.protobuf.ProtoBuf;
|
||||
|
||||
import org.springframework.http.codec.KotlinSerializationBinaryDecoder;
|
||||
|
||||
/**
|
||||
* Decode a byte stream into a protocol Buffer and convert to Objects with
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This decoder can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/x-protobuf}, {@code application/octet-stream}, and {@code application/vnd.google.protobuf}.
|
||||
*
|
||||
* <p>Decoding streams is not supported yet, see
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/issues/1073">kotlinx.serialization/issues/1073</a>
|
||||
* related issue.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationProtobufDecoder extends KotlinSerializationBinaryDecoder<ProtoBuf> {
|
||||
|
||||
public KotlinSerializationProtobufDecoder() {
|
||||
this(ProtoBuf.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationProtobufDecoder(ProtoBuf protobuf) {
|
||||
super(protobuf, ProtobufCodecSupport.MIME_TYPES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.codec.protobuf;
|
||||
|
||||
import kotlinx.serialization.protobuf.ProtoBuf;
|
||||
|
||||
import org.springframework.http.codec.KotlinSerializationBinaryEncoder;
|
||||
|
||||
/**
|
||||
* Decode a byte stream into a Protocol Buffer and convert to Objects with
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This decoder can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/x-protobuf}, {@code application/octet-stream}, and {@code application/vnd.google.protobuf}.
|
||||
*
|
||||
* <p>Decoding streams is not supported yet, see
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/issues/1073">kotlinx.serialization/issues/1073</a>
|
||||
* related issue.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationProtobufEncoder extends KotlinSerializationBinaryEncoder<ProtoBuf> {
|
||||
|
||||
public KotlinSerializationProtobufEncoder() {
|
||||
this(ProtoBuf.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationProtobufEncoder(ProtoBuf protobuf) {
|
||||
super(protobuf, ProtobufCodecSupport.MIME_TYPES);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2021 the original author or authors.
|
||||
* Copyright 2002-2022 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.
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
package org.springframework.http.codec.protobuf;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.lang.Nullable;
|
||||
@@ -29,10 +30,11 @@ import org.springframework.util.MimeType;
|
||||
*/
|
||||
public abstract class ProtobufCodecSupport {
|
||||
|
||||
static final List<MimeType> MIME_TYPES = List.of(
|
||||
new MimeType("application", "x-protobuf"),
|
||||
new MimeType("application", "octet-stream"),
|
||||
new MimeType("application", "vnd.google.protobuf"));
|
||||
static final MimeType[] MIME_TYPES = new MimeType[]{
|
||||
new MimeType("application", "x-protobuf"),
|
||||
new MimeType("application", "octet-stream"),
|
||||
new MimeType("application", "vnd.google.protobuf")
|
||||
};
|
||||
|
||||
static final String DELIMITED_KEY = "delimited";
|
||||
|
||||
@@ -40,11 +42,19 @@ public abstract class ProtobufCodecSupport {
|
||||
|
||||
|
||||
protected boolean supportsMimeType(@Nullable MimeType mimeType) {
|
||||
return (mimeType == null || MIME_TYPES.stream().anyMatch(m -> m.isCompatibleWith(mimeType)));
|
||||
if (mimeType == null) {
|
||||
return true;
|
||||
}
|
||||
for (MimeType m : MIME_TYPES) {
|
||||
if (m.isCompatibleWith(mimeType)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected List<MimeType> getMimeTypes() {
|
||||
return MIME_TYPES;
|
||||
return Arrays.asList(MIME_TYPES);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
package org.springframework.http.codec.protobuf;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -56,8 +57,7 @@ import org.springframework.util.MimeType;
|
||||
*/
|
||||
public class ProtobufEncoder extends ProtobufCodecSupport implements HttpMessageEncoder<Message> {
|
||||
|
||||
private static final List<MediaType> streamingMediaTypes = MIME_TYPES
|
||||
.stream()
|
||||
private static final List<MediaType> streamingMediaTypes = Arrays.stream(MIME_TYPES)
|
||||
.map(mimeType -> new MediaType(mimeType.getType(), mimeType.getSubtype(),
|
||||
Collections.singletonMap(DELIMITED_KEY, DELIMITED_VALUE)))
|
||||
.toList();
|
||||
|
||||
@@ -50,6 +50,8 @@ import org.springframework.http.codec.ResourceHttpMessageReader;
|
||||
import org.springframework.http.codec.ResourceHttpMessageWriter;
|
||||
import org.springframework.http.codec.ServerSentEventHttpMessageReader;
|
||||
import org.springframework.http.codec.ServerSentEventHttpMessageWriter;
|
||||
import org.springframework.http.codec.cbor.KotlinSerializationCborDecoder;
|
||||
import org.springframework.http.codec.cbor.KotlinSerializationCborEncoder;
|
||||
import org.springframework.http.codec.json.AbstractJackson2Decoder;
|
||||
import org.springframework.http.codec.json.Jackson2JsonDecoder;
|
||||
import org.springframework.http.codec.json.Jackson2JsonEncoder;
|
||||
@@ -61,6 +63,8 @@ import org.springframework.http.codec.multipart.DefaultPartHttpMessageReader;
|
||||
import org.springframework.http.codec.multipart.MultipartHttpMessageReader;
|
||||
import org.springframework.http.codec.multipart.MultipartHttpMessageWriter;
|
||||
import org.springframework.http.codec.multipart.PartEventHttpMessageReader;
|
||||
import org.springframework.http.codec.protobuf.KotlinSerializationProtobufDecoder;
|
||||
import org.springframework.http.codec.protobuf.KotlinSerializationProtobufEncoder;
|
||||
import org.springframework.http.codec.protobuf.ProtobufDecoder;
|
||||
import org.springframework.http.codec.protobuf.ProtobufEncoder;
|
||||
import org.springframework.http.codec.protobuf.ProtobufHttpMessageWriter;
|
||||
@@ -100,8 +104,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
|
||||
static final boolean netty5BufferPresent;
|
||||
|
||||
static final boolean kotlinSerializationCborPresent;
|
||||
|
||||
static final boolean kotlinSerializationJsonPresent;
|
||||
|
||||
static final boolean kotlinSerializationProtobufPresent;
|
||||
|
||||
static {
|
||||
ClassLoader classLoader = BaseCodecConfigurer.class.getClassLoader();
|
||||
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
|
||||
@@ -112,7 +120,9 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
synchronossMultipartPresent = ClassUtils.isPresent("org.synchronoss.cloud.nio.multipart.NioMultipartParser", classLoader);
|
||||
nettyByteBufPresent = ClassUtils.isPresent("io.netty.buffer.ByteBuf", classLoader);
|
||||
netty5BufferPresent = ClassUtils.isPresent("io.netty5.buffer.Buffer", classLoader);
|
||||
kotlinSerializationCborPresent = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader);
|
||||
kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
|
||||
kotlinSerializationProtobufPresent = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader);
|
||||
}
|
||||
|
||||
|
||||
@@ -140,12 +150,24 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
@Nullable
|
||||
private Encoder<?> jaxb2Encoder;
|
||||
|
||||
@Nullable
|
||||
private Decoder<?> kotlinSerializationCborDecoder;
|
||||
|
||||
@Nullable
|
||||
private Encoder<?> kotlinSerializationCborEncoder;
|
||||
|
||||
@Nullable
|
||||
private Decoder<?> kotlinSerializationJsonDecoder;
|
||||
|
||||
@Nullable
|
||||
private Encoder<?> kotlinSerializationJsonEncoder;
|
||||
|
||||
@Nullable
|
||||
private Decoder<?> kotlinSerializationProtobufDecoder;
|
||||
|
||||
@Nullable
|
||||
private Encoder<?> kotlinSerializationProtobufEncoder;
|
||||
|
||||
@Nullable
|
||||
private Consumer<Object> codecConsumer;
|
||||
|
||||
@@ -204,8 +226,12 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
this.protobufEncoder = other.protobufEncoder;
|
||||
this.jaxb2Decoder = other.jaxb2Decoder;
|
||||
this.jaxb2Encoder = other.jaxb2Encoder;
|
||||
this.kotlinSerializationCborDecoder = other.kotlinSerializationCborDecoder;
|
||||
this.kotlinSerializationCborEncoder = other.kotlinSerializationCborEncoder;
|
||||
this.kotlinSerializationJsonDecoder = other.kotlinSerializationJsonDecoder;
|
||||
this.kotlinSerializationJsonEncoder = other.kotlinSerializationJsonEncoder;
|
||||
this.kotlinSerializationProtobufDecoder = other.kotlinSerializationProtobufDecoder;
|
||||
this.kotlinSerializationProtobufEncoder = other.kotlinSerializationProtobufEncoder;
|
||||
this.codecConsumer = other.codecConsumer;
|
||||
this.maxInMemorySize = other.maxInMemorySize;
|
||||
this.enableLoggingRequestDetails = other.enableLoggingRequestDetails;
|
||||
@@ -266,6 +292,18 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
initObjectWriters();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kotlinSerializationCborDecoder(Decoder<?> decoder) {
|
||||
this.kotlinSerializationCborDecoder = decoder;
|
||||
initObjectReaders();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kotlinSerializationCborEncoder(Encoder<?> encoder) {
|
||||
this.kotlinSerializationCborEncoder = encoder;
|
||||
initObjectWriters();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kotlinSerializationJsonDecoder(Decoder<?> decoder) {
|
||||
this.kotlinSerializationJsonDecoder = decoder;
|
||||
@@ -278,6 +316,18 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
initObjectWriters();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kotlinSerializationProtobufDecoder(Decoder<?> decoder) {
|
||||
this.kotlinSerializationProtobufDecoder = decoder;
|
||||
initObjectReaders();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void kotlinSerializationProtobufEncoder(Encoder<?> encoder) {
|
||||
this.kotlinSerializationProtobufEncoder = encoder;
|
||||
initObjectWriters();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureDefaultCodec(Consumer<Object> codecConsumer) {
|
||||
this.codecConsumer = (this.codecConsumer != null ?
|
||||
@@ -358,6 +408,10 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(this.protobufDecoder != null ?
|
||||
(ProtobufDecoder) this.protobufDecoder : new ProtobufDecoder()));
|
||||
}
|
||||
else if (kotlinSerializationProtobufPresent) {
|
||||
addCodec(this.typedReaders, new DecoderHttpMessageReader<>(this.kotlinSerializationProtobufDecoder != null ?
|
||||
(KotlinSerializationProtobufDecoder) this.kotlinSerializationProtobufDecoder : new KotlinSerializationProtobufDecoder()));
|
||||
}
|
||||
addCodec(this.typedReaders, new FormHttpMessageReader());
|
||||
|
||||
// client vs server..
|
||||
@@ -401,11 +455,21 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
((ProtobufDecoder) codec).setMaxMessageSize(size);
|
||||
}
|
||||
}
|
||||
if (kotlinSerializationCborPresent) {
|
||||
if (codec instanceof KotlinSerializationCborDecoder) {
|
||||
((KotlinSerializationCborDecoder) codec).setMaxInMemorySize(size);
|
||||
}
|
||||
}
|
||||
if (kotlinSerializationJsonPresent) {
|
||||
if (codec instanceof KotlinSerializationJsonDecoder) {
|
||||
((KotlinSerializationJsonDecoder) codec).setMaxInMemorySize(size);
|
||||
}
|
||||
}
|
||||
if (kotlinSerializationProtobufPresent) {
|
||||
if (codec instanceof KotlinSerializationProtobufDecoder) {
|
||||
((KotlinSerializationProtobufDecoder) codec).setMaxInMemorySize(size);
|
||||
}
|
||||
}
|
||||
if (jackson2Present) {
|
||||
if (codec instanceof AbstractJackson2Decoder) {
|
||||
((AbstractJackson2Decoder) codec).setMaxInMemorySize(size);
|
||||
@@ -493,9 +557,20 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
if (!this.registerDefaults) {
|
||||
return;
|
||||
}
|
||||
if (kotlinSerializationCborPresent) {
|
||||
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(this.kotlinSerializationCborDecoder != null ?
|
||||
(KotlinSerializationCborDecoder) this.kotlinSerializationCborDecoder :
|
||||
new KotlinSerializationCborDecoder()));
|
||||
}
|
||||
if (kotlinSerializationJsonPresent) {
|
||||
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getKotlinSerializationJsonDecoder()));
|
||||
}
|
||||
if (kotlinSerializationProtobufPresent) {
|
||||
addCodec(this.objectReaders,
|
||||
new DecoderHttpMessageReader<>(this.kotlinSerializationProtobufDecoder != null ?
|
||||
(KotlinSerializationProtobufDecoder) this.kotlinSerializationProtobufDecoder :
|
||||
new KotlinSerializationProtobufDecoder()));
|
||||
}
|
||||
if (jackson2Present) {
|
||||
addCodec(this.objectReaders, new DecoderHttpMessageReader<>(getJackson2JsonDecoder()));
|
||||
}
|
||||
@@ -533,7 +608,6 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
/**
|
||||
* Return all writers that support specific types.
|
||||
*/
|
||||
@SuppressWarnings({"rawtypes" })
|
||||
final List<HttpMessageWriter<?>> getTypedWriters() {
|
||||
return this.typedWriters;
|
||||
}
|
||||
@@ -608,9 +682,19 @@ class BaseDefaultCodecs implements CodecConfigurer.DefaultCodecs, CodecConfigure
|
||||
*/
|
||||
final List<HttpMessageWriter<?>> getBaseObjectWriters() {
|
||||
List<HttpMessageWriter<?>> writers = new ArrayList<>();
|
||||
if (kotlinSerializationCborPresent) {
|
||||
addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationCborEncoder != null ?
|
||||
(KotlinSerializationCborEncoder) this.kotlinSerializationCborEncoder :
|
||||
new KotlinSerializationCborEncoder()));
|
||||
}
|
||||
if (kotlinSerializationJsonPresent) {
|
||||
addCodec(writers, new EncoderHttpMessageWriter<>(getKotlinSerializationJsonEncoder()));
|
||||
}
|
||||
if (kotlinSerializationProtobufPresent) {
|
||||
addCodec(writers, new EncoderHttpMessageWriter<>(this.kotlinSerializationProtobufEncoder != null ?
|
||||
(KotlinSerializationProtobufEncoder) this.kotlinSerializationProtobufEncoder :
|
||||
new KotlinSerializationProtobufEncoder()));
|
||||
}
|
||||
if (jackson2Present) {
|
||||
addCodec(writers, new EncoderHttpMessageWriter<>(getJackson2JsonEncoder()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.converter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerialFormat;
|
||||
import kotlinx.serialization.SerializersKt;
|
||||
import kotlinx.serialization.descriptors.PolymorphicKind;
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor;
|
||||
|
||||
import org.springframework.core.GenericTypeResolver;
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link HttpMessageConverter} implementations that
|
||||
* use Kotlin serialization.
|
||||
*
|
||||
* @author Andreas Ahlenstorf
|
||||
* @author Sebastien Deleuze
|
||||
* @author Juergen Hoeller
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link SerialFormat}
|
||||
*/
|
||||
public abstract class AbstractKotlinSerializationHttpMessageConverter<T extends SerialFormat> extends AbstractGenericHttpMessageConverter<Object> {
|
||||
|
||||
private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
|
||||
private final T format;
|
||||
|
||||
|
||||
/**
|
||||
* Construct an {@code AbstractKotlinSerializationHttpMessageConverter} with multiple supported media type and
|
||||
* format.
|
||||
* @param format the format
|
||||
* @param supportedMediaTypes the supported media types
|
||||
*/
|
||||
protected AbstractKotlinSerializationHttpMessageConverter(T format, MediaType... supportedMediaTypes) {
|
||||
super(supportedMediaTypes);
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean supports(Class<?> clazz) {
|
||||
return serializer(clazz) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) {
|
||||
if (serializer(GenericTypeResolver.resolveType(type, contextClass)) != null) {
|
||||
return canRead(mediaType);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) {
|
||||
if (serializer(type != null ? GenericTypeResolver.resolveType(type, clazz) : clazz) != null) {
|
||||
return canWrite(mediaType);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
|
||||
Type resolvedType = GenericTypeResolver.resolveType(type, contextClass);
|
||||
KSerializer<Object> serializer = serializer(resolvedType);
|
||||
if (serializer == null) {
|
||||
throw new HttpMessageNotReadableException("Could not find KSerializer for " + resolvedType, inputMessage);
|
||||
}
|
||||
return readInternal(serializer, this.format, inputMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
|
||||
KSerializer<Object> serializer = serializer(clazz);
|
||||
if (serializer == null) {
|
||||
throw new HttpMessageNotReadableException("Could not find KSerializer for " + clazz, inputMessage);
|
||||
}
|
||||
return readInternal(serializer, this.format, inputMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the given input message with the given serializer and format.
|
||||
*/
|
||||
protected abstract Object readInternal(KSerializer<Object> serializer, T format, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException;
|
||||
|
||||
@Override
|
||||
protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
|
||||
throws IOException, HttpMessageNotWritableException {
|
||||
|
||||
Type resolvedType = type != null ? type : object.getClass();
|
||||
KSerializer<Object> serializer = serializer(resolvedType);
|
||||
if (serializer == null) {
|
||||
throw new HttpMessageNotWritableException("Could not find KSerializer for " + resolvedType);
|
||||
}
|
||||
writeInternal(object, serializer, this.format, outputMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the given object to the output message with the given serializer and format.
|
||||
*/
|
||||
protected abstract void writeInternal(Object object, KSerializer<Object> serializer, T format,
|
||||
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException;
|
||||
|
||||
/**
|
||||
* Tries to find a serializer that can marshall or unmarshall instances of the given type
|
||||
* using kotlinx.serialization. If no serializer can be found, {@code null} is returned.
|
||||
* <p>Resolved serializers are cached and cached results are returned on successive calls.
|
||||
* @param type the type to find a serializer for
|
||||
* @return a resolved serializer for the given type, or {@code null}
|
||||
*/
|
||||
@Nullable
|
||||
private KSerializer<Object> serializer(Type type) {
|
||||
KSerializer<Object> serializer = serializerCache.get(type);
|
||||
if (serializer == null) {
|
||||
try {
|
||||
serializer = SerializersKt.serializerOrNull(type);
|
||||
}
|
||||
catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (serializer != null) {
|
||||
if (hasPolymorphism(serializer.getDescriptor(), new HashSet<>())) {
|
||||
return null;
|
||||
}
|
||||
serializerCache.put(type, serializer);
|
||||
}
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
|
||||
private boolean hasPolymorphism(SerialDescriptor descriptor, Set<String> alreadyProcessed) {
|
||||
alreadyProcessed.add(descriptor.getSerialName());
|
||||
if (descriptor.getKind().equals(PolymorphicKind.OPEN.INSTANCE)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0 ; i < descriptor.getElementsCount() ; i++) {
|
||||
SerialDescriptor elementDescriptor = descriptor.getElementDescriptor(i);
|
||||
if (!alreadyProcessed.contains(elementDescriptor.getSerialName()) && hasPolymorphism(elementDescriptor, alreadyProcessed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.converter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import kotlinx.serialization.BinaryFormat;
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerializationException;
|
||||
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link HttpMessageConverter} implementations that
|
||||
* defer to Kotlin {@linkplain BinaryFormat binary serializers}.
|
||||
*
|
||||
* @author Andreas Ahlenstorf
|
||||
* @author Sebastien Deleuze
|
||||
* @author Juergen Hoeller
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link BinaryFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationBinaryHttpMessageConverter<T extends BinaryFormat>
|
||||
extends AbstractKotlinSerializationHttpMessageConverter<T> {
|
||||
|
||||
/**
|
||||
* Construct an {@code KotlinSerializationBinaryHttpMessageConverter} with format and supported media types.
|
||||
*/
|
||||
protected KotlinSerializationBinaryHttpMessageConverter(T format, MediaType... supportedMediaTypes) {
|
||||
super(format, supportedMediaTypes);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object readInternal(KSerializer<Object> serializer, T format, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
|
||||
byte[] bytes = StreamUtils.copyToByteArray(inputMessage.getBody());
|
||||
try {
|
||||
return format.decodeFromByteArray(serializer, bytes);
|
||||
}
|
||||
catch (SerializationException ex) {
|
||||
throw new HttpMessageNotReadableException("Could not read " + format + ": " + ex.getMessage(), ex,
|
||||
inputMessage);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeInternal(Object object, KSerializer<Object> serializer, T format,
|
||||
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
|
||||
|
||||
try {
|
||||
byte[] bytes = format.encodeToByteArray(serializer, object);
|
||||
outputMessage.getBody().write(bytes);
|
||||
outputMessage.getBody().flush();
|
||||
}
|
||||
catch (SerializationException ex) {
|
||||
throw new HttpMessageNotWritableException("Could not write " + format + ": " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.converter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerializationException;
|
||||
import kotlinx.serialization.StringFormat;
|
||||
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.StreamUtils;
|
||||
|
||||
/**
|
||||
* Abstract base class for {@link HttpMessageConverter} implementations that
|
||||
* defer to Kotlin {@linkplain StringFormat string serializers}.
|
||||
*
|
||||
* @author Andreas Ahlenstorf
|
||||
* @author Sebastien Deleuze
|
||||
* @author Juergen Hoeller
|
||||
* @author Iain Henderson
|
||||
* @author Arjen Poutsma
|
||||
* @since 6.0
|
||||
* @param <T> the type of {@link StringFormat}
|
||||
*/
|
||||
public abstract class KotlinSerializationStringHttpMessageConverter<T extends StringFormat>
|
||||
extends AbstractKotlinSerializationHttpMessageConverter<T> {
|
||||
|
||||
|
||||
/**
|
||||
* Construct an {@code KotlinSerializationStringHttpMessageConverter} with format and supported media types.
|
||||
*/
|
||||
protected KotlinSerializationStringHttpMessageConverter(T format, MediaType... supportedMediaTypes) {
|
||||
super(format, supportedMediaTypes);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected Object readInternal(KSerializer<Object> serializer, T format, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
|
||||
Charset charset = charset(inputMessage.getHeaders().getContentType());
|
||||
String s = StreamUtils.copyToString(inputMessage.getBody(), charset);
|
||||
try {
|
||||
return format.decodeFromString(serializer, s);
|
||||
}
|
||||
catch (SerializationException ex) {
|
||||
throw new HttpMessageNotReadableException("Could not read " + format + ": " + ex.getMessage(), ex,
|
||||
inputMessage);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void writeInternal(Object object, KSerializer<Object> serializer, T format,
|
||||
HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
|
||||
|
||||
try {
|
||||
String s = format.encodeToString(serializer, object);
|
||||
Charset charset = charset(outputMessage.getHeaders().getContentType());
|
||||
outputMessage.getBody().write(s.getBytes(charset));
|
||||
outputMessage.getBody().flush();
|
||||
}
|
||||
catch (SerializationException ex) {
|
||||
throw new HttpMessageNotWritableException("Could not write " + format + ": " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static Charset charset(@Nullable MediaType contentType) {
|
||||
if (contentType != null && contentType.getCharset() != null) {
|
||||
return contentType.getCharset();
|
||||
}
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.converter.cbor;
|
||||
|
||||
import kotlinx.serialization.cbor.Cbor;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.KotlinSerializationBinaryHttpMessageConverter;
|
||||
|
||||
/**
|
||||
* Implementation of {@link org.springframework.http.converter.HttpMessageConverter}
|
||||
* that can read and write CBOR using
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This converter can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/cbor}.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationCborHttpMessageConverter extends KotlinSerializationBinaryHttpMessageConverter<Cbor> {
|
||||
public KotlinSerializationCborHttpMessageConverter() {
|
||||
this(Cbor.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationCborHttpMessageConverter(Cbor cbor) {
|
||||
super(cbor, MediaType.APPLICATION_CBOR);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -16,32 +16,10 @@
|
||||
|
||||
package org.springframework.http.converter.json;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import kotlinx.serialization.KSerializer;
|
||||
import kotlinx.serialization.SerializationException;
|
||||
import kotlinx.serialization.SerializersKt;
|
||||
import kotlinx.serialization.descriptors.PolymorphicKind;
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor;
|
||||
import kotlinx.serialization.json.Json;
|
||||
|
||||
import org.springframework.core.GenericTypeResolver;
|
||||
import org.springframework.http.HttpInputMessage;
|
||||
import org.springframework.http.HttpOutputMessage;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.AbstractGenericHttpMessageConverter;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.http.converter.HttpMessageNotWritableException;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ConcurrentReferenceHashMap;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.http.converter.KotlinSerializationStringHttpMessageConverter;
|
||||
|
||||
/**
|
||||
* Implementation of {@link org.springframework.http.converter.HttpMessageConverter}
|
||||
@@ -57,16 +35,10 @@ import org.springframework.util.StreamUtils;
|
||||
* @author Andreas Ahlenstorf
|
||||
* @author Sebastien Deleuze
|
||||
* @author Juergen Hoeller
|
||||
* @author Iain Henderson
|
||||
* @since 5.3
|
||||
*/
|
||||
public class KotlinSerializationJsonHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
|
||||
|
||||
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
|
||||
|
||||
private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>();
|
||||
|
||||
private final Json json;
|
||||
|
||||
public class KotlinSerializationJsonHttpMessageConverter extends KotlinSerializationStringHttpMessageConverter<Json> {
|
||||
|
||||
/**
|
||||
* Construct a new {@code KotlinSerializationJsonHttpMessageConverter} with the default configuration.
|
||||
@@ -79,125 +51,6 @@ public class KotlinSerializationJsonHttpMessageConverter extends AbstractGeneric
|
||||
* Construct a new {@code KotlinSerializationJsonHttpMessageConverter} with a custom configuration.
|
||||
*/
|
||||
public KotlinSerializationJsonHttpMessageConverter(Json json) {
|
||||
super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
this.json = json;
|
||||
super(json, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean supports(Class<?> clazz) {
|
||||
return serializer(clazz) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canRead(Type type, @Nullable Class<?> contextClass, @Nullable MediaType mediaType) {
|
||||
return serializer(GenericTypeResolver.resolveType(type, contextClass)) != null && canRead(mediaType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canWrite(@Nullable Type type, Class<?> clazz, @Nullable MediaType mediaType) {
|
||||
return serializer(type != null ? GenericTypeResolver.resolveType(type, clazz) : clazz) != null && canWrite(mediaType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public final Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
KSerializer<Object> serializer = serializer(GenericTypeResolver.resolveType(type, contextClass));
|
||||
Assert.notNull(serializer, "The serializer should not be null");
|
||||
return decode(serializer, inputMessage);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
KSerializer<Object> serializer = serializer(clazz);
|
||||
Assert.notNull(serializer, "The serializer should not be null");
|
||||
return decode(serializer, inputMessage);
|
||||
}
|
||||
|
||||
private Object decode(KSerializer<Object> serializer, HttpInputMessage inputMessage)
|
||||
throws IOException, HttpMessageNotReadableException {
|
||||
|
||||
MediaType contentType = inputMessage.getHeaders().getContentType();
|
||||
String jsonText = StreamUtils.copyToString(inputMessage.getBody(), getCharsetToUse(contentType));
|
||||
try {
|
||||
// TODO Use stream based API when available
|
||||
return this.json.decodeFromString(serializer, jsonText);
|
||||
}
|
||||
catch (SerializationException ex) {
|
||||
throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex, inputMessage);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage)
|
||||
throws IOException, HttpMessageNotWritableException {
|
||||
KSerializer<Object> serializer = serializer(type != null ? type : object.getClass());
|
||||
Assert.notNull(serializer, "The serializer should not be null");
|
||||
encode(object, serializer, outputMessage);
|
||||
}
|
||||
|
||||
private void encode(Object object, KSerializer<Object> serializer, HttpOutputMessage outputMessage)
|
||||
throws IOException, HttpMessageNotWritableException {
|
||||
|
||||
try {
|
||||
String json = this.json.encodeToString(serializer, object);
|
||||
MediaType contentType = outputMessage.getHeaders().getContentType();
|
||||
outputMessage.getBody().write(json.getBytes(getCharsetToUse(contentType)));
|
||||
outputMessage.getBody().flush();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw ex;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
private Charset getCharsetToUse(@Nullable MediaType contentType) {
|
||||
if (contentType != null && contentType.getCharset() != null) {
|
||||
return contentType.getCharset();
|
||||
}
|
||||
return DEFAULT_CHARSET;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to find a serializer that can marshall or unmarshall instances of the given type
|
||||
* using kotlinx.serialization. If no serializer can be found, an exception is thrown.
|
||||
* <p>Resolved serializers are cached and cached results are returned on successive calls.
|
||||
* @param type the type to find a serializer for
|
||||
* @return a resolved serializer for the given type or {@code null} if no serializer
|
||||
* supporting the given type can be found
|
||||
*/
|
||||
@Nullable
|
||||
private KSerializer<Object> serializer(Type type) {
|
||||
KSerializer<Object> serializer = serializerCache.get(type);
|
||||
if (serializer == null) {
|
||||
try {
|
||||
serializer = SerializersKt.serializerOrNull(type);
|
||||
}
|
||||
catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
if (serializer == null || hasPolymorphism(serializer.getDescriptor(), new HashSet<>())) {
|
||||
return null;
|
||||
}
|
||||
serializerCache.put(type, serializer);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
|
||||
private boolean hasPolymorphism(SerialDescriptor descriptor, Set<String> alreadyProcessed) {
|
||||
alreadyProcessed.add(descriptor.getSerialName());
|
||||
if (descriptor.getKind().equals(PolymorphicKind.OPEN.INSTANCE)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0 ; i < descriptor.getElementsCount() ; i++) {
|
||||
SerialDescriptor elementDescriptor = descriptor.getElementDescriptor(i);
|
||||
if (!alreadyProcessed.contains(elementDescriptor.getSerialName()) && hasPolymorphism(elementDescriptor, alreadyProcessed)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright 2002-2022 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.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* https://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.http.converter.protobuf;
|
||||
|
||||
import kotlinx.serialization.protobuf.ProtoBuf;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.KotlinSerializationBinaryHttpMessageConverter;
|
||||
|
||||
/**
|
||||
* Implementation of {@link org.springframework.http.converter.HttpMessageConverter}
|
||||
* that can read and write Protocol Buffers using
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>.
|
||||
*
|
||||
* <p>This converter can be used to bind {@code @Serializable} Kotlin classes,
|
||||
* <a href="https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism">open polymorphic serialization</a>
|
||||
* is not supported.
|
||||
* It supports {@code application/x-protobuf}, {@code application/octet-stream}, and {@code application/vnd.google.protobuf}.
|
||||
*
|
||||
* @author Iain Henderson
|
||||
* @since 6.0
|
||||
*/
|
||||
public class KotlinSerializationProtobufHttpMessageConverter extends
|
||||
KotlinSerializationBinaryHttpMessageConverter<ProtoBuf> {
|
||||
|
||||
public KotlinSerializationProtobufHttpMessageConverter() {
|
||||
this(ProtoBuf.Default);
|
||||
}
|
||||
|
||||
public KotlinSerializationProtobufHttpMessageConverter(ProtoBuf protobuf) {
|
||||
super(protobuf, MediaType.APPLICATION_PROTOBUF, MediaType.APPLICATION_OCTET_STREAM,
|
||||
new MediaType("application", "vnd.google.protobuf"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2020 the original author or authors.
|
||||
* Copyright 2002-2021 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.
|
||||
@@ -18,10 +18,12 @@ package org.springframework.http.converter.support;
|
||||
|
||||
import org.springframework.core.SpringProperties;
|
||||
import org.springframework.http.converter.FormHttpMessageConverter;
|
||||
import org.springframework.http.converter.cbor.KotlinSerializationCborHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.GsonHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.KotlinSerializationJsonHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.http.converter.protobuf.KotlinSerializationProtobufHttpMessageConverter;
|
||||
import org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
|
||||
@@ -58,8 +60,12 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv
|
||||
|
||||
private static final boolean jsonbPresent;
|
||||
|
||||
private static final boolean kotlinSerializationCborPresent;
|
||||
|
||||
private static final boolean kotlinSerializationJsonPresent;
|
||||
|
||||
private static final boolean kotlinSerializationProtobufPresent;
|
||||
|
||||
static {
|
||||
ClassLoader classLoader = AllEncompassingFormHttpMessageConverter.class.getClassLoader();
|
||||
jaxb2Present = ClassUtils.isPresent("jakarta.xml.bind.Binder", classLoader);
|
||||
@@ -69,7 +75,9 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv
|
||||
jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader);
|
||||
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
|
||||
jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
|
||||
kotlinSerializationCborPresent = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader);
|
||||
kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
|
||||
kotlinSerializationProtobufPresent = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader);
|
||||
}
|
||||
|
||||
|
||||
@@ -107,6 +115,14 @@ public class AllEncompassingFormHttpMessageConverter extends FormHttpMessageConv
|
||||
if (jackson2SmilePresent) {
|
||||
addPartConverter(new MappingJackson2SmileHttpMessageConverter());
|
||||
}
|
||||
|
||||
if (kotlinSerializationCborPresent) {
|
||||
addPartConverter(new KotlinSerializationCborHttpMessageConverter());
|
||||
}
|
||||
|
||||
if (kotlinSerializationProtobufPresent) {
|
||||
addPartConverter(new KotlinSerializationProtobufHttpMessageConverter());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import org.springframework.http.converter.GenericHttpMessageConverter;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.ResourceHttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.http.converter.cbor.KotlinSerializationCborHttpMessageConverter;
|
||||
import org.springframework.http.converter.cbor.MappingJackson2CborHttpMessageConverter;
|
||||
import org.springframework.http.converter.feed.AtomFeedHttpMessageConverter;
|
||||
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
|
||||
@@ -61,6 +62,7 @@ import org.springframework.http.converter.json.GsonHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.KotlinSerializationJsonHttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.http.converter.protobuf.KotlinSerializationProtobufHttpMessageConverter;
|
||||
import org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverter;
|
||||
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
|
||||
@@ -125,8 +127,12 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
|
||||
|
||||
private static final boolean jsonbPresent;
|
||||
|
||||
private static final boolean kotlinSerializationCborPresent;
|
||||
|
||||
private static final boolean kotlinSerializationJsonPresent;
|
||||
|
||||
private static final boolean kotlinSerializationProtobufPresent;
|
||||
|
||||
private static final ClientHttpObservationConvention DEFAULT_OBSERVATION_CONVENTION = new DefaultClientHttpObservationConvention();
|
||||
|
||||
static {
|
||||
@@ -140,7 +146,9 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
|
||||
jackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader);
|
||||
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
|
||||
jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
|
||||
kotlinSerializationCborPresent = ClassUtils.isPresent("kotlinx.serialization.cbor.Cbor", classLoader);
|
||||
kotlinSerializationJsonPresent = ClassUtils.isPresent("kotlinx.serialization.json.Json", classLoader);
|
||||
kotlinSerializationProtobufPresent = ClassUtils.isPresent("kotlinx.serialization.protobuf.ProtoBuf", classLoader);
|
||||
}
|
||||
|
||||
|
||||
@@ -190,6 +198,10 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
|
||||
}
|
||||
}
|
||||
|
||||
if (kotlinSerializationProtobufPresent) {
|
||||
this.messageConverters.add(new KotlinSerializationProtobufHttpMessageConverter());
|
||||
}
|
||||
|
||||
if (kotlinSerializationJsonPresent) {
|
||||
this.messageConverters.add(new KotlinSerializationJsonHttpMessageConverter());
|
||||
}
|
||||
@@ -206,9 +218,13 @@ public class RestTemplate extends InterceptingHttpAccessor implements RestOperat
|
||||
if (jackson2SmilePresent) {
|
||||
this.messageConverters.add(new MappingJackson2SmileHttpMessageConverter());
|
||||
}
|
||||
|
||||
if (jackson2CborPresent) {
|
||||
this.messageConverters.add(new MappingJackson2CborHttpMessageConverter());
|
||||
}
|
||||
else if (kotlinSerializationCborPresent) {
|
||||
this.messageConverters.add(new KotlinSerializationCborHttpMessageConverter());
|
||||
}
|
||||
|
||||
updateErrorHandlerConverters();
|
||||
this.uriTemplateHandler = initUriTemplateHandler();
|
||||
|
||||
Reference in New Issue
Block a user