|
| 1 | +/* |
| 2 | + * Copyright 2002-2024 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.http.codec.protobuf; |
| 18 | + |
| 19 | +import java.io.InputStreamReader; |
| 20 | +import java.lang.reflect.Method; |
| 21 | +import java.util.List; |
| 22 | +import java.util.Map; |
| 23 | +import java.util.concurrent.ConcurrentMap; |
| 24 | + |
| 25 | +import com.google.protobuf.Message; |
| 26 | +import com.google.protobuf.util.JsonFormat; |
| 27 | +import org.reactivestreams.Publisher; |
| 28 | +import reactor.core.publisher.Flux; |
| 29 | +import reactor.core.publisher.Mono; |
| 30 | + |
| 31 | +import org.springframework.core.ResolvableType; |
| 32 | +import org.springframework.core.codec.Decoder; |
| 33 | +import org.springframework.core.codec.DecodingException; |
| 34 | +import org.springframework.core.io.buffer.DataBuffer; |
| 35 | +import org.springframework.core.io.buffer.DataBufferLimitException; |
| 36 | +import org.springframework.core.io.buffer.DataBufferUtils; |
| 37 | +import org.springframework.http.MediaType; |
| 38 | +import org.springframework.lang.Nullable; |
| 39 | +import org.springframework.util.ConcurrentReferenceHashMap; |
| 40 | +import org.springframework.util.MimeType; |
| 41 | + |
| 42 | +/** |
| 43 | + * A {@code Decoder} that reads a JSON byte stream and converts it to |
| 44 | + * <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a> |
| 45 | + * {@link com.google.protobuf.Message}s. |
| 46 | + * |
| 47 | + * <p>Flux deserialized via |
| 48 | + * {@link #decode(Publisher, ResolvableType, MimeType, Map)} are not supported because |
| 49 | + * the Protobuf Java Util library does not provide a non-blocking parser |
| 50 | + * that splits a JSON stream into tokens. |
| 51 | + * Applications should consider decoding to {@code Mono<Message>} or |
| 52 | + * {@code Mono<List<Message>>}, which will use the supported |
| 53 | + * {@link #decodeToMono(Publisher, ResolvableType, MimeType, Map)}. |
| 54 | + * |
| 55 | + * <p>To generate {@code Message} Java classes, you need to install the |
| 56 | + * {@code protoc} binary. |
| 57 | + * |
| 58 | + * <p>This decoder requires Protobuf 3.29 or higher, and supports |
| 59 | + * {@code "application/json"} and {@code "application/*+json"} with |
| 60 | + * the official {@code "com.google.protobuf:protobuf-java-util"} library. |
| 61 | + * |
| 62 | + * @author Brian Clozel |
| 63 | + * @since 6.2 |
| 64 | + * @see ProtobufJsonEncoder |
| 65 | + */ |
| 66 | +public class ProtobufJsonDecoder implements Decoder<Message> { |
| 67 | + |
| 68 | + /** The default max size for aggregating messages. */ |
| 69 | + protected static final int DEFAULT_MESSAGE_MAX_SIZE = 256 * 1024; |
| 70 | + |
| 71 | + private static final List<MimeType> defaultMimeTypes = List.of(MediaType.APPLICATION_JSON, |
| 72 | + new MediaType("application", "*+json")); |
| 73 | + |
| 74 | + private static final ConcurrentMap<Class<?>, Method> methodCache = new ConcurrentReferenceHashMap<>(); |
| 75 | + |
| 76 | + private final JsonFormat.Parser parser; |
| 77 | + |
| 78 | + private int maxMessageSize = DEFAULT_MESSAGE_MAX_SIZE; |
| 79 | + |
| 80 | + /** |
| 81 | + * Construct a new {@link ProtobufJsonDecoder} using a default {@link JsonFormat.Parser} instance. |
| 82 | + */ |
| 83 | + public ProtobufJsonDecoder() { |
| 84 | + this(JsonFormat.parser()); |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Construct a new {@link ProtobufJsonDecoder} using the given {@link JsonFormat.Parser} instance. |
| 89 | + */ |
| 90 | + public ProtobufJsonDecoder(JsonFormat.Parser parser) { |
| 91 | + this.parser = parser; |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * Return the {@link #setMaxMessageSize configured} message size limit. |
| 96 | + */ |
| 97 | + public int getMaxMessageSize() { |
| 98 | + return this.maxMessageSize; |
| 99 | + } |
| 100 | + |
| 101 | + /** |
| 102 | + * The max size allowed per message. |
| 103 | + * <p>By default, this is set to 256K. |
| 104 | + * @param maxMessageSize the max size per message, or -1 for unlimited |
| 105 | + */ |
| 106 | + public void setMaxMessageSize(int maxMessageSize) { |
| 107 | + this.maxMessageSize = maxMessageSize; |
| 108 | + } |
| 109 | + |
| 110 | + @Override |
| 111 | + public boolean canDecode(ResolvableType elementType, @Nullable MimeType mimeType) { |
| 112 | + return Message.class.isAssignableFrom(elementType.toClass()) && supportsMimeType(mimeType); |
| 113 | + } |
| 114 | + |
| 115 | + private static boolean supportsMimeType(@Nullable MimeType mimeType) { |
| 116 | + if (mimeType == null) { |
| 117 | + return false; |
| 118 | + } |
| 119 | + for (MimeType m : defaultMimeTypes) { |
| 120 | + if (m.isCompatibleWith(mimeType)) { |
| 121 | + return true; |
| 122 | + } |
| 123 | + } |
| 124 | + return false; |
| 125 | + } |
| 126 | + |
| 127 | + |
| 128 | + @Override |
| 129 | + public List<MimeType> getDecodableMimeTypes() { |
| 130 | + return defaultMimeTypes; |
| 131 | + } |
| 132 | + |
| 133 | + @Override |
| 134 | + public Flux<Message> decode(Publisher<DataBuffer> inputStream, ResolvableType targetType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { |
| 135 | + return Flux.error(new UnsupportedOperationException("Protobuf decoder does not support Flux, use Mono<List<...>> instead.")); |
| 136 | + } |
| 137 | + |
| 138 | + @Override |
| 139 | + public Message decode(DataBuffer dataBuffer, ResolvableType targetType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) throws DecodingException { |
| 140 | + try { |
| 141 | + Message.Builder builder = getMessageBuilder(targetType.toClass()); |
| 142 | + this.parser.merge(new InputStreamReader(dataBuffer.asInputStream()), builder); |
| 143 | + return builder.build(); |
| 144 | + } |
| 145 | + catch (Exception ex) { |
| 146 | + throw new DecodingException("Could not read Protobuf message: " + ex.getMessage(), ex); |
| 147 | + } |
| 148 | + finally { |
| 149 | + DataBufferUtils.release(dataBuffer); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Create a new {@code Message.Builder} instance for the given class. |
| 155 | + * <p>This method uses a ConcurrentHashMap for caching method lookups. |
| 156 | + */ |
| 157 | + private static Message.Builder getMessageBuilder(Class<?> clazz) throws Exception { |
| 158 | + Method method = methodCache.get(clazz); |
| 159 | + if (method == null) { |
| 160 | + method = clazz.getMethod("newBuilder"); |
| 161 | + methodCache.put(clazz, method); |
| 162 | + } |
| 163 | + return (Message.Builder) method.invoke(clazz); |
| 164 | + } |
| 165 | + |
| 166 | + @Override |
| 167 | + public Mono<Message> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { |
| 168 | + return DataBufferUtils.join(inputStream, this.maxMessageSize) |
| 169 | + .map(dataBuffer -> decode(dataBuffer, elementType, mimeType, hints)) |
| 170 | + .onErrorMap(DataBufferLimitException.class, exc -> new DecodingException("Could not decode JSON as Protobuf message", exc)); |
| 171 | + } |
| 172 | + |
| 173 | +} |
0 commit comments