diff options
Diffstat (limited to 'container-core')
-rw-r--r-- | container-core/abi-spec.json | 15 | ||||
-rw-r--r-- | container-core/src/main/java/com/yahoo/restapi/JacksonJsonResponse.java | 48 |
2 files changed, 63 insertions, 0 deletions
diff --git a/container-core/abi-spec.json b/container-core/abi-spec.json index e5875247855..8905a27a127 100644 --- a/container-core/abi-spec.json +++ b/container-core/abi-spec.json @@ -892,6 +892,21 @@ ], "fields": [] }, + "com.yahoo.restapi.JacksonJsonResponse": { + "superClass": "com.yahoo.container.jdisc.HttpResponse", + "interfaces": [], + "attributes": [ + "public" + ], + "methods": [ + "public void <init>(int, java.lang.Object)", + "public void <init>(int, java.lang.Object, com.fasterxml.jackson.databind.ObjectMapper)", + "public void render(java.io.OutputStream)", + "public java.lang.String getContentType()", + "public java.lang.Object getEntity()" + ], + "fields": [] + }, "com.yahoo.restapi.MessageResponse": { "superClass": "com.yahoo.container.jdisc.HttpResponse", "interfaces": [], diff --git a/container-core/src/main/java/com/yahoo/restapi/JacksonJsonResponse.java b/container-core/src/main/java/com/yahoo/restapi/JacksonJsonResponse.java new file mode 100644 index 00000000000..d3b960651b0 --- /dev/null +++ b/container-core/src/main/java/com/yahoo/restapi/JacksonJsonResponse.java @@ -0,0 +1,48 @@ +// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.restapi; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yahoo.container.jdisc.HttpResponse; +import com.yahoo.log.LogLevel; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.logging.Logger; + +/** + * A JSON response using Jackson for serialization. + * + * @author bjorncs + */ +public class JacksonJsonResponse<T> extends HttpResponse { + + private static final Logger log = Logger.getLogger(JacksonJsonResponse.class.getName()); + private static final ObjectMapper defaultJsonMapper = new ObjectMapper(); + + private final ObjectMapper jsonMapper; + private final T entity; + + public JacksonJsonResponse(int statusCode, T entity) { + this(statusCode, entity, defaultJsonMapper); + } + + public JacksonJsonResponse(int statusCode, T entity, ObjectMapper jsonMapper) { + super(statusCode); + this.entity = entity; + this.jsonMapper = jsonMapper; + } + + @Override + public void render(OutputStream outputStream) throws IOException { + if (log.isLoggable(LogLevel.DEBUG)) { + String json = jsonMapper.writeValueAsString(entity); + log.log(LogLevel.DEBUG, "Writing the following JSON to response output stream:\n" + json); + outputStream.write(json.getBytes()); + } else { + jsonMapper.writeValue(outputStream, entity); + } + } + + @Override public String getContentType() { return "application/json"; } + public T getEntity() { return entity; } +} |