|
| 1 | +/* |
| 2 | + * Copyright 2002-present 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.json; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.OutputStreamWriter; |
| 21 | +import java.nio.charset.StandardCharsets; |
| 22 | +import java.util.ArrayList; |
| 23 | +import java.util.Collections; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Map; |
| 26 | + |
| 27 | +import com.google.gson.Gson; |
| 28 | +import org.jspecify.annotations.Nullable; |
| 29 | +import org.reactivestreams.Publisher; |
| 30 | +import reactor.core.publisher.Flux; |
| 31 | +import reactor.core.publisher.Mono; |
| 32 | + |
| 33 | +import org.springframework.core.ResolvableType; |
| 34 | +import org.springframework.core.codec.AbstractEncoder; |
| 35 | +import org.springframework.core.codec.EncodingException; |
| 36 | +import org.springframework.core.io.buffer.DataBuffer; |
| 37 | +import org.springframework.core.io.buffer.DataBufferFactory; |
| 38 | +import org.springframework.http.MediaType; |
| 39 | +import org.springframework.http.codec.HttpMessageEncoder; |
| 40 | +import org.springframework.util.Assert; |
| 41 | +import org.springframework.util.FastByteArrayOutputStream; |
| 42 | +import org.springframework.util.MimeType; |
| 43 | + |
| 44 | +/** |
| 45 | + * Encode from an {@code Object} stream to a byte stream of JSON objects using |
| 46 | + * <a href="https://google.github.io/gson/">Google Gson</a>. |
| 47 | + * |
| 48 | + * @author Brian Clozel |
| 49 | + * @since 7.0 |
| 50 | + */ |
| 51 | +public class GsonEncoder extends AbstractEncoder<Object> implements HttpMessageEncoder<Object> { |
| 52 | + |
| 53 | + private static final byte[] NEWLINE_SEPARATOR = {'\n'}; |
| 54 | + |
| 55 | + private static final byte[] EMPTY_BYTES = new byte[0]; |
| 56 | + |
| 57 | + private static final MimeType[] DEFAULT_JSON_MIME_TYPES = new MimeType[] { |
| 58 | + MediaType.APPLICATION_JSON, |
| 59 | + new MediaType("application", "*+json"), |
| 60 | + MediaType.APPLICATION_NDJSON |
| 61 | + }; |
| 62 | + |
| 63 | + private final Gson gson; |
| 64 | + |
| 65 | + private final List<MediaType> streamingMediaTypes = new ArrayList<>(1); |
| 66 | + |
| 67 | + /** |
| 68 | + * Construct a new encoder using a default {@link Gson} instance |
| 69 | + * and the {@code "application/json"} and {@code "application/*+json"} |
| 70 | + * MIME types. The {@code "application/x-ndjson"} is configured for streaming. |
| 71 | + */ |
| 72 | + public GsonEncoder() { |
| 73 | + this(new Gson(), DEFAULT_JSON_MIME_TYPES); |
| 74 | + setStreamingMediaTypes(List.of(MediaType.APPLICATION_NDJSON)); |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Construct a new encoder using the given {@link Gson} instance |
| 79 | + * and the provided MIME types. Use {@link #setStreamingMediaTypes(List)} |
| 80 | + * for configuring streaming media types. |
| 81 | + * @param gson the gson instance to use |
| 82 | + * @param mimeTypes the mime types the decoder should support |
| 83 | + */ |
| 84 | + public GsonEncoder(Gson gson, MimeType... mimeTypes) { |
| 85 | + super(mimeTypes); |
| 86 | + Assert.notNull(gson, "A Gson instance is required"); |
| 87 | + this.gson = gson; |
| 88 | + } |
| 89 | + |
| 90 | + /** |
| 91 | + * Configure "streaming" media types for which flushing should be performed |
| 92 | + * automatically vs at the end of the stream. |
| 93 | + */ |
| 94 | + public void setStreamingMediaTypes(List<MediaType> mediaTypes) { |
| 95 | + this.streamingMediaTypes.clear(); |
| 96 | + this.streamingMediaTypes.addAll(mediaTypes); |
| 97 | + } |
| 98 | + |
| 99 | + @Override |
| 100 | + public List<MediaType> getStreamingMediaTypes() { |
| 101 | + return Collections.unmodifiableList(this.streamingMediaTypes); |
| 102 | + } |
| 103 | + |
| 104 | + @Override |
| 105 | + public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) { |
| 106 | + if (!super.canEncode(elementType, mimeType)) { |
| 107 | + return false; |
| 108 | + } |
| 109 | + Class<?> clazz = elementType.toClass(); |
| 110 | + return !String.class.isAssignableFrom(elementType.resolve(clazz)); |
| 111 | + } |
| 112 | + |
| 113 | + @Override |
| 114 | + public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, |
| 115 | + @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { |
| 116 | + |
| 117 | + boolean isStreaming = isStreamingMediaType(mimeType); |
| 118 | + if (isStreaming) { |
| 119 | + return Flux.from(inputStream).map(message -> encodeValue(message, bufferFactory, EMPTY_BYTES, NEWLINE_SEPARATOR)); |
| 120 | + } |
| 121 | + else { |
| 122 | + JsonArrayJoinHelper helper = new JsonArrayJoinHelper(); |
| 123 | + // Do not prepend JSON array prefix until first signal is known, onNext vs onError |
| 124 | + // Keeps response not committed for error handling |
| 125 | + return Flux.from(inputStream) |
| 126 | + .map(value -> { |
| 127 | + byte[] prefix = helper.getPrefix(); |
| 128 | + byte[] delimiter = helper.getDelimiter(); |
| 129 | + DataBuffer dataBuffer = encodeValue(value, bufferFactory, delimiter, EMPTY_BYTES); |
| 130 | + return (prefix.length > 0 ? |
| 131 | + bufferFactory.join(List.of(bufferFactory.wrap(prefix), dataBuffer)) : |
| 132 | + dataBuffer); |
| 133 | + }) |
| 134 | + .switchIfEmpty(Mono.fromCallable(() -> bufferFactory.wrap(helper.getPrefix()))) |
| 135 | + .concatWith(Mono.fromCallable(() -> bufferFactory.wrap(helper.getSuffix()))); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + @Override |
| 140 | + public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType, |
| 141 | + @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { |
| 142 | + return encodeValue(value, bufferFactory, EMPTY_BYTES, EMPTY_BYTES); |
| 143 | + } |
| 144 | + |
| 145 | + private DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, |
| 146 | + byte[] prefix, byte[] suffix) { |
| 147 | + try { |
| 148 | + FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); |
| 149 | + OutputStreamWriter writer = new OutputStreamWriter(bos, StandardCharsets.UTF_8); |
| 150 | + bos.write(prefix); |
| 151 | + this.gson.toJson(value, writer); |
| 152 | + writer.flush(); |
| 153 | + bos.write(suffix); |
| 154 | + byte[] bytes = bos.toByteArrayUnsafe(); |
| 155 | + return bufferFactory.wrap(bytes); |
| 156 | + } |
| 157 | + catch (IOException ex) { |
| 158 | + throw new EncodingException("JSON encoding error: " + ex.getMessage(), ex); |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * Return the separator to use for the given mime type. |
| 164 | + * <p>By default, this method returns new line {@code "\n"} if the given |
| 165 | + * mime type is one of the configured {@link #setStreamingMediaTypes(List) |
| 166 | + * streaming} mime types. |
| 167 | + */ |
| 168 | + protected boolean isStreamingMediaType(@Nullable MimeType mimeType) { |
| 169 | + for (MediaType streamingMediaType : this.streamingMediaTypes) { |
| 170 | + if (streamingMediaType.isCompatibleWith(mimeType)) { |
| 171 | + return true; |
| 172 | + } |
| 173 | + } |
| 174 | + return false; |
| 175 | + } |
| 176 | + |
| 177 | + |
| 178 | + private static class JsonArrayJoinHelper { |
| 179 | + |
| 180 | + private static final byte[] COMMA_SEPARATOR = {','}; |
| 181 | + |
| 182 | + private static final byte[] OPEN_BRACKET = {'['}; |
| 183 | + |
| 184 | + private static final byte[] CLOSE_BRACKET = {']'}; |
| 185 | + |
| 186 | + private boolean firstItemEmitted; |
| 187 | + |
| 188 | + public byte[] getDelimiter() { |
| 189 | + if (this.firstItemEmitted) { |
| 190 | + return COMMA_SEPARATOR; |
| 191 | + } |
| 192 | + this.firstItemEmitted = true; |
| 193 | + return EMPTY_BYTES; |
| 194 | + } |
| 195 | + |
| 196 | + public byte[] getPrefix() { |
| 197 | + return (this.firstItemEmitted ? EMPTY_BYTES : OPEN_BRACKET); |
| 198 | + } |
| 199 | + |
| 200 | + public byte[] getSuffix() { |
| 201 | + return CLOSE_BRACKET; |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | +} |
0 commit comments