|
| 1 | +package uk.gov.digital.ho.hocs.casework.api.utils; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonEncoding; |
| 4 | +import com.fasterxml.jackson.core.JsonFactory; |
| 5 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 6 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 7 | +import lombok.extern.slf4j.Slf4j; |
| 8 | +import org.apache.http.entity.ContentType; |
| 9 | +import org.springframework.http.HttpHeaders; |
| 10 | +import org.springframework.http.HttpStatus; |
| 11 | +import org.springframework.http.ResponseEntity; |
| 12 | +import org.springframework.stereotype.Service; |
| 13 | +import org.springframework.transaction.TransactionStatus; |
| 14 | +import org.springframework.transaction.support.TransactionCallback; |
| 15 | +import org.springframework.transaction.support.TransactionTemplate; |
| 16 | +import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; |
| 17 | +import uk.gov.digital.ho.hocs.casework.application.LogEvent; |
| 18 | +import uk.gov.digital.ho.hocs.casework.domain.exception.ApplicationExceptions; |
| 19 | + |
| 20 | +import java.io.IOException; |
| 21 | +import java.io.OutputStream; |
| 22 | +import java.util.Map; |
| 23 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 24 | +import java.util.function.BiFunction; |
| 25 | +import java.util.function.Supplier; |
| 26 | +import java.util.stream.Stream; |
| 27 | + |
| 28 | +@Service |
| 29 | +@Slf4j |
| 30 | +public class JsonResponseStreamer { |
| 31 | + |
| 32 | + private final ObjectMapper objectMapper; |
| 33 | + |
| 34 | + private final TransactionTemplate transactionTemplate; |
| 35 | + |
| 36 | + public JsonResponseStreamer(ObjectMapper objectMapper, TransactionTemplate transactionTemplate) { |
| 37 | + this.objectMapper = objectMapper; |
| 38 | + this.transactionTemplate = transactionTemplate; |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Convert a stream of objects that can be serialised to JSON by the default ObjectMapper into a json object |
| 43 | + * containing an array field with the serialised contents of the stream as the array's items. The stream will be |
| 44 | + * consumed within a transaction to prevent issues with the database query closing before the stream is closed. |
| 45 | + * |
| 46 | + * @param fieldName The field name attached to the array of streamed items |
| 47 | + * @param streamSupplier A callback that will supply the stream of items to serialise. This will be run within a |
| 48 | + * transaction |
| 49 | + * @return StreamingResponseBody producing a root json object with the stream items in an array field |
| 50 | + */ |
| 51 | + public ResponseEntity<StreamingResponseBody> jsonWrappedTransactionalStreamingResponseBody( |
| 52 | + String fieldName, |
| 53 | + Supplier<Stream<?>> streamSupplier) |
| 54 | + { |
| 55 | + return jsonWrappedTransactionalStreamingResponseBody(fieldName, streamSupplier, Map.of()); |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Convert a stream of objects that can be serialised to JSON by the default ObjectMapper into a json object |
| 60 | + * containing an array field with the serialised contents of the stream as the array's items. The stream will be |
| 61 | + * consumed within a transaction to prevent issues with the database query closing before the stream is closed. |
| 62 | + * |
| 63 | + * @param fieldName The field name attached to the array of streamed items |
| 64 | + * @param streamSupplier A callback that will supply the stream of items to serialise. This will be run within a |
| 65 | + * transaction |
| 66 | + * @param additionalFields These will be added as fields to the root JSON object. The keys will be used as the field |
| 67 | + * names and the values will be serialised to JSON |
| 68 | + * @return StreamingResponseBody producing a root json object with the stream items in an array field |
| 69 | + */ |
| 70 | + public ResponseEntity<StreamingResponseBody> jsonWrappedTransactionalStreamingResponseBody( |
| 71 | + String fieldName, |
| 72 | + Supplier<Stream<?>> streamSupplier, |
| 73 | + Map<String, Object> additionalFields) |
| 74 | + { |
| 75 | + return wrapStream( |
| 76 | + fieldName, |
| 77 | + (generator, outputStream) -> status -> { |
| 78 | + streamSupplier.get().forEach(streamItem -> { |
| 79 | + try { |
| 80 | + generator.writeObject(streamItem); |
| 81 | + } catch (IOException e) { |
| 82 | + throw new ApplicationExceptions.ReportBodyStreamingException( |
| 83 | + String.format( |
| 84 | + "Failed to write streaming response body for item: %s - %s", |
| 85 | + streamItem, |
| 86 | + e |
| 87 | + ), |
| 88 | + LogEvent.STREAMING_JSON_SERIALISATION_EXCEPTION |
| 89 | + ); |
| 90 | + } |
| 91 | + }); |
| 92 | + |
| 93 | + return null; |
| 94 | + }, |
| 95 | + additionalFields |
| 96 | + ); |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Convert a stream of json strings into a json object containing an array field with the raw strings from the |
| 101 | + * stream as the array's items. The stream will be consumed within a transaction to prevent issues with the database |
| 102 | + * query closing before the stream is closed. |
| 103 | + * |
| 104 | + * @param fieldName The field name attached to the array of streamed items |
| 105 | + * @param streamSupplier A callback that will supply a stream of valid JSON Strings. This will be run within a |
| 106 | + * transaction. |
| 107 | + * @return StreamingResponseBody producing a root json object with the stream items in an array field |
| 108 | + */ |
| 109 | + public ResponseEntity<StreamingResponseBody> jsonStringsWrappedTransactionalStreamingResponseBody( |
| 110 | + String fieldName, |
| 111 | + Supplier<Stream<String>> streamSupplier) |
| 112 | + { |
| 113 | + return jsonStringsWrappedTransactionalStreamingResponseBody(fieldName, streamSupplier, Map.of()); |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Convert a stream of json strings into a json object containing an array field with the raw strings from the |
| 118 | + * stream as the array's items. The stream will be consumed within a transaction to prevent issues with the database |
| 119 | + * query closing before the stream is closed. |
| 120 | + * |
| 121 | + * @param fieldName The field name attached to the array of streamed items |
| 122 | + * @param streamSupplier A callback that will supply a stream of valid JSON Strings. This will be run within a |
| 123 | + * transaction. |
| 124 | + * @param additionalFields These will be added as fields to the root JSON object. The keys will be used as the field |
| 125 | + * names and the values will be serialised to JSON |
| 126 | + * @return StreamingResponseBody producing a root json object with the stream items in an array field |
| 127 | + */ |
| 128 | + public ResponseEntity<StreamingResponseBody> jsonStringsWrappedTransactionalStreamingResponseBody( |
| 129 | + String fieldName, |
| 130 | + Supplier<Stream<String>> streamSupplier, |
| 131 | + Map<String, Object> additionalFields |
| 132 | + ) { |
| 133 | + return wrapStream( |
| 134 | + fieldName, |
| 135 | + (generator, outputStream) -> status -> { |
| 136 | + // Needs to be final to be used in stream. |
| 137 | + AtomicBoolean prefixComma = new AtomicBoolean(false); |
| 138 | + |
| 139 | + streamSupplier.get().forEach( |
| 140 | + (streamItem) -> { |
| 141 | + try { |
| 142 | + if (prefixComma.get()) { |
| 143 | + outputStream.write(','); |
| 144 | + } else { |
| 145 | + prefixComma.set(true); |
| 146 | + } |
| 147 | + |
| 148 | + outputStream.write(streamItem.getBytes()); |
| 149 | + } catch (IOException e) { |
| 150 | + log.error("Failed to write {} to json response - {}", streamItem, e); |
| 151 | + } |
| 152 | + } |
| 153 | + ); |
| 154 | + |
| 155 | + return null; |
| 156 | + }, |
| 157 | + additionalFields |
| 158 | + ); |
| 159 | + } |
| 160 | + |
| 161 | + private ResponseEntity<StreamingResponseBody> wrapStream( |
| 162 | + String fieldName, |
| 163 | + BiFunction<JsonGenerator, OutputStream, TransactionCallback<TransactionStatus>> transactionCallbackSupplier, |
| 164 | + Map<String, Object> additionalFields |
| 165 | + ) { |
| 166 | + StreamingResponseBody body = outputStream -> { |
| 167 | + try { |
| 168 | + JsonFactory factory = new JsonFactory(); |
| 169 | + |
| 170 | + JsonGenerator generator = factory.createGenerator(outputStream, JsonEncoding.UTF8); |
| 171 | + generator.setCodec(objectMapper); |
| 172 | + |
| 173 | + generator.writeStartObject(); |
| 174 | + |
| 175 | + additionalFields.forEach((nestedFieldName, object) -> { |
| 176 | + try { |
| 177 | + generator.writeObjectField(nestedFieldName, object); |
| 178 | + } catch (IOException e) { |
| 179 | + log.error("Failed to write {} to json response - {}", nestedFieldName, e); |
| 180 | + } |
| 181 | + }); |
| 182 | + |
| 183 | + generator.writeArrayFieldStart(fieldName); |
| 184 | + // jsonStringsWrappedTransactionalStreamingResponseBody writes JSON strings directly to the output |
| 185 | + // stream, so flush current json first |
| 186 | + generator.flush(); |
| 187 | + |
| 188 | + transactionTemplate.execute(transactionCallbackSupplier.apply(generator, outputStream)); |
| 189 | + |
| 190 | + generator.writeEndArray(); |
| 191 | + generator.writeEndObject(); |
| 192 | + generator.close(); |
| 193 | + } catch (Exception e) { |
| 194 | + log.error("Failed to write streaming response body - {}", e); |
| 195 | + } |
| 196 | + }; |
| 197 | + |
| 198 | + HttpHeaders responseHeaders = new HttpHeaders(); |
| 199 | + responseHeaders.add(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); |
| 200 | + |
| 201 | + return new ResponseEntity<>( |
| 202 | + body, |
| 203 | + responseHeaders, |
| 204 | + HttpStatus.OK |
| 205 | + ); |
| 206 | + } |
| 207 | +} |
0 commit comments