Skip to content

Commit

Permalink
Improve JSON view handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
noboomu committed Jan 31, 2020
1 parent 82a22bc commit e713dcd
Showing 1 changed file with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package io.sinistral.proteus.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.inject.Inject;
import io.sinistral.proteus.server.predicates.ServerPredicates;
Expand All @@ -23,6 +24,7 @@
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
* @author jbauer
Expand All @@ -40,6 +42,8 @@ public class ServerResponse<T>
@Inject
protected static ObjectMapper OBJECT_MAPPER;

protected static Map<Class<?>, ObjectWriter> WRITER_CACHE = new ConcurrentHashMap<>();

protected ByteBuffer body;

protected int status = StatusCodes.OK;
Expand Down Expand Up @@ -634,11 +638,12 @@ public void send(final HttpHandler handler, final HttpServerExchange exchange) t
exchange.getResponseSender().send(ByteBuffer.wrap(XML_MAPPER.writeValueAsBytes(this.entity)));
} else {

final Class jsonViewClass = exchange.getAttachment(JsonViewWrapper.JSON_VIEW_KEY);
final Class<?> jsonViewClass = exchange.getAttachment(JsonViewWrapper.JSON_VIEW_KEY);

if(jsonViewClass != null)
{
exchange.getResponseSender().send(ByteBuffer.wrap(OBJECT_MAPPER.writerWithView(jsonViewClass).writeValueAsBytes(this.entity)));
ObjectWriter writer = WRITER_CACHE.computeIfAbsent(jsonViewClass, (view) -> OBJECT_MAPPER.writerWithView(view));
exchange.getResponseSender().send(ByteBuffer.wrap(writer.writeValueAsBytes(this.entity)));
}
else
{
Expand Down

0 comments on commit e713dcd

Please sign in to comment.