From 26723e6906813032d9d80f44a4bd0a624df9a314 Mon Sep 17 00:00:00 2001 From: joshua bauer Date: Fri, 13 Jul 2018 09:30:53 -0700 Subject: [PATCH] Swapped out Jsoniter with Jackson. Slightly slower but easier to use. --- pom.xml | 7 +- .../proteus/modules/ApplicationModule.java | 45 ++++++++--- .../sinistral/proteus/server/Extractors.java | 80 ++++++++++++------- .../proteus/server/ServerResponse.java | 25 +++--- .../server/handlers/HandlerGenerator.java | 44 +++++----- .../ServerDefaultResponseListener.java | 14 +++- .../sinistral/proteus/controllers/Tests.java | 30 +++++-- .../server/TestControllerEndpoints.java | 3 - 8 files changed, 159 insertions(+), 89 deletions(-) diff --git a/pom.xml b/pom.xml index 65f6b43..2cfb39b 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 io.sinistral proteus-core - 0.2.3-SNAPSHOT + 0.3.0-SNAPSHOT proteus core Proteus is an extremely light, fast, and flexible Java REST API framework built atop Undertow. http://github.com/noboomu/proteus @@ -341,11 +341,6 @@ jansi 1.15 - - io.sinistral - jsoniter - 0.9.9 - org.reactivestreams reactive-streams diff --git a/src/main/java/io/sinistral/proteus/modules/ApplicationModule.java b/src/main/java/io/sinistral/proteus/modules/ApplicationModule.java index 68391c4..0da34d3 100644 --- a/src/main/java/io/sinistral/proteus/modules/ApplicationModule.java +++ b/src/main/java/io/sinistral/proteus/modules/ApplicationModule.java @@ -12,19 +12,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.google.common.util.concurrent.Service; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; -import com.jsoniter.DecodingMode; -import com.jsoniter.JsonIterator; -import com.jsoniter.annotation.JsoniterAnnotationSupport; -import com.jsoniter.output.EncodingMode; -import com.jsoniter.output.JsonStream; import com.typesafe.config.Config; +import io.sinistral.proteus.server.Extractors; +import io.sinistral.proteus.server.ServerResponse; import io.sinistral.proteus.server.endpoints.EndpointInfo; import io.undertow.server.DefaultResponseListener; import io.undertow.server.HandlerWrapper; @@ -102,12 +103,38 @@ protected void configure() { }).annotatedWith(Names.named("registeredHandlerWrappers")).toInstance(registeredHandlerWrappers); - this.bind(XmlMapper.class).toInstance(new XmlMapper()); + + this.bindMappers(); - JsonIterator.setMode(DecodingMode.DYNAMIC_MODE_AND_MATCH_FIELD_WITH_HASH); - JsonStream.setMode(EncodingMode.DYNAMIC_MODE); - JsoniterAnnotationSupport.enable(); + } + + /** + * Override for customizing XmlMapper and ObjectMapper + */ + public void bindMappers() + { + this.bind(XmlMapper.class).toInstance(new XmlMapper()); +// JsonIterator.setMode(DecodingMode.DYNAMIC_MODE_AND_MATCH_FIELD_WITH_HASH); +// JsonStream.setMode(EncodingMode.DYNAMIC_MODE); +// JsoniterAnnotationSupport.enable(); + + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true); + objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); + objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH,true); + objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); + objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true); + + objectMapper.registerModule(new AfterburnerModule()); + objectMapper.registerModule(new Jdk8Module()); + + this.bind(ObjectMapper.class).toInstance(objectMapper); + + this.requestStaticInjection(Extractors.class); + + this.requestStaticInjection(ServerResponse.class); } } diff --git a/src/main/java/io/sinistral/proteus/server/Extractors.java b/src/main/java/io/sinistral/proteus/server/Extractors.java index de2ca88..b6543b5 100644 --- a/src/main/java/io/sinistral/proteus/server/Extractors.java +++ b/src/main/java/io/sinistral/proteus/server/Extractors.java @@ -17,14 +17,17 @@ import java.util.Objects; import java.util.function.Function; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.jsoniter.JsonIterator; -import com.jsoniter.any.Any; -import com.jsoniter.spi.TypeLiteral; +import com.google.inject.Inject; import io.sinistral.proteus.server.predicates.ServerPredicates; import io.undertow.server.HttpServerExchange; -import io.undertow.server.handlers.form.FormData.FormValue; import io.undertow.server.handlers.form.FormDataParser; import io.undertow.util.HttpString; import io.undertow.util.Methods; @@ -34,8 +37,24 @@ */ public class Extractors { - - protected static final XmlMapper XML_MAPPER = new XmlMapper(); + private static Logger log = LoggerFactory.getLogger(Extractors.class.getCanonicalName()); + + @Inject + public static XmlMapper XML_MAPPER; + + @Inject + public static ObjectMapper OBJECT_MAPPER; + + public static Function parseJson = (bytes) -> { + try + { + return OBJECT_MAPPER.readTree(bytes); + } catch (Exception e) + { + log.error(e.getMessage(),e); + return null; + } + }; public static class Optional { @@ -45,12 +64,12 @@ public static java.util.Optional extractWithFunction(final HttpServerExch return string(exchange, name).map(function); } - public static java.util.Optional jsonIterator(final HttpServerExchange exchange) + public static java.util.Optional jsonNode(final HttpServerExchange exchange) { - return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(ByteBuffer::array).map(JsonIterator::parse); + return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(ByteBuffer::array).map(parseJson); } - public static java.util.Optional model(final HttpServerExchange exchange, final TypeLiteral type ) + public static java.util.Optional model(final HttpServerExchange exchange, final TypeReference type ) { if( ServerPredicates.XML_PREDICATE.resolve(exchange) ) { @@ -77,14 +96,15 @@ public static java.util.Optional model(final HttpServerExchange exchange } - public static java.util.Optional jsonModel(final HttpServerExchange exchange, final TypeLiteral type ) + public static java.util.Optional jsonModel(final HttpServerExchange exchange, final TypeReference type ) { - return jsonIterator(exchange).map(i -> { + return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(ByteBuffer::array).map( b -> { try { - return i.read(type); + return OBJECT_MAPPER.readValue(b, type); } catch (Exception e) { + //log.error(e.getMessage(),e); return null; } }); @@ -92,18 +112,19 @@ public static java.util.Optional jsonModel(final HttpServerExchange exch public static java.util.Optional jsonModel(final HttpServerExchange exchange, final Class type ) { - return jsonIterator(exchange).map(i -> { + return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(ByteBuffer::array).map( b -> { try { - return i.read(type); + return OBJECT_MAPPER.readValue(b, type); } catch (Exception e) { + //log.error(e.getMessage(),e); return null; } }); } - public static java.util.Optional xmlModel(final HttpServerExchange exchange, final TypeLiteral type ) + public static java.util.Optional xmlModel(final HttpServerExchange exchange, final TypeReference type ) { return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(ByteBuffer::array).map( b -> { try @@ -111,6 +132,7 @@ public static java.util.Optional xmlModel(final HttpServerExchange excha return XML_MAPPER.readValue(b,XML_MAPPER.getTypeFactory().constructType(type.getType())); } catch (Exception e) { + //log.error(e.getMessage(),e); return null; } }); @@ -124,6 +146,7 @@ public static java.util.Optional xmlModel(final HttpServerExchange excha return XML_MAPPER.readValue(b,type); } catch (Exception e) { + //log.error(e.getMessage(),e); return null; } }); @@ -150,9 +173,9 @@ public static java.util.Optional zonedDateTime(final HttpServerEx } - public static java.util.Optional any(final HttpServerExchange exchange ) + public static java.util.Optional any(final HttpServerExchange exchange ) { - return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map(t -> JsonIterator.deserialize(t.array())); + return java.util.Optional.ofNullable(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY)).map( b -> parseJson.apply(b.array())); } public static java.util.Optional integerValue(final HttpServerExchange exchange, final String name) @@ -267,11 +290,11 @@ public static OffsetDateTime offsetDateTime(final HttpServerExchange exchange,fi } - public static T jsonModel(final HttpServerExchange exchange, final TypeLiteral type ) throws IllegalArgumentException + public static T jsonModel(final HttpServerExchange exchange, final TypeReference type ) throws IllegalArgumentException { try { - return jsonIterator(exchange).read(type); + return OBJECT_MAPPER.readValue(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array(), type); } catch( Exception e ) { @@ -283,7 +306,7 @@ public static T jsonModel(final HttpServerExchange exchange, final Class { try { - return jsonIterator(exchange).read(type); + return OBJECT_MAPPER.readValue(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array(), type); } catch( Exception e ) { @@ -306,7 +329,7 @@ public static T xmlModel(final HttpServerExchange exchange, final Class } } - public static T xmlModel(final HttpServerExchange exchange, final TypeLiteral type ) throws IllegalArgumentException + public static T xmlModel(final HttpServerExchange exchange, final TypeReference type ) throws IllegalArgumentException { try { @@ -319,20 +342,21 @@ public static T xmlModel(final HttpServerExchange exchange, final TypeLiter } } - public static Any any(final HttpServerExchange exchange ) + public static JsonNode any(final HttpServerExchange exchange ) { try { - return JsonIterator.parse( exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array() ).readAny(); - } catch (IOException e) + return parseJson.apply( exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array() ); + } catch (Exception e) { - return Any.wrapNull(); + log.warn(e.getMessage(),e); + return OBJECT_MAPPER.createObjectNode(); } } - public static JsonIterator jsonIterator(final HttpServerExchange exchange ) + public static JsonNode jsonNode(final HttpServerExchange exchange ) { - return JsonIterator.parse(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array()); + return parseJson.apply(exchange.getAttachment(ServerRequest.BYTE_BUFFER_KEY).array()); } public static Path filePath(final HttpServerExchange exchange, final String name) throws java.lang.IllegalArgumentException @@ -413,7 +437,7 @@ public static Boolean booleanValue(final HttpServerExchange exchange, final Str return Boolean.parseBoolean(string(exchange, name)); } - public static T model(final HttpServerExchange exchange, final TypeLiteral type ) throws IllegalArgumentException + public static T model(final HttpServerExchange exchange, final TypeReference type ) throws IllegalArgumentException { if( ServerPredicates.XML_PREDICATE.resolve(exchange) ) { diff --git a/src/main/java/io/sinistral/proteus/server/ServerResponse.java b/src/main/java/io/sinistral/proteus/server/ServerResponse.java index f88ad6d..cd174ee 100644 --- a/src/main/java/io/sinistral/proteus/server/ServerResponse.java +++ b/src/main/java/io/sinistral/proteus/server/ServerResponse.java @@ -10,10 +10,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.jsoniter.output.JsonContext; -import com.jsoniter.output.JsonStream; +import com.google.inject.Inject; import io.sinistral.proteus.server.predicates.ServerPredicates; import io.undertow.io.IoCallback; @@ -34,7 +33,11 @@ public class ServerResponse { private static Logger log = LoggerFactory.getLogger(ServerResponse.class.getCanonicalName()); - protected static final XmlMapper XML_MAPPER = new XmlMapper(); + @Inject + protected static XmlMapper XML_MAPPER; + + @Inject + protected static ObjectMapper OBJECT_MAPPER; protected ByteBuffer body; @@ -44,7 +47,7 @@ public class ServerResponse protected String contentType = null; protected T entity; protected Throwable throwable; - protected Class jsonContext; +// protected Class jsonContext; protected IoCallback ioCallback; protected boolean hasCookies = false; protected boolean hasHeaders = false; @@ -239,11 +242,11 @@ public ServerResponse textPlain() return this; } - public ServerResponse jsonContext(Class context) - { - this.jsonContext = context; - return this; - } +// public ServerResponse jsonContext(Class context) +// { +// this.jsonContext = context; +// return this; +// } public ServerResponse ok() { @@ -420,7 +423,7 @@ else if (hasEntity) else { - exchange.getResponseSender().send(JsonStream.serializeToBytes(this.entity, this.jsonContext)); + exchange.getResponseSender().send(ByteBuffer.wrap(OBJECT_MAPPER.writeValueAsBytes(this.entity))); } } catch (Exception e) diff --git a/src/main/java/io/sinistral/proteus/server/handlers/HandlerGenerator.java b/src/main/java/io/sinistral/proteus/server/handlers/HandlerGenerator.java index 58be0d6..7a682df 100644 --- a/src/main/java/io/sinistral/proteus/server/handlers/HandlerGenerator.java +++ b/src/main/java/io/sinistral/proteus/server/handlers/HandlerGenerator.java @@ -42,7 +42,7 @@ import com.google.inject.Inject; import com.google.inject.name.Named; -import com.jsoniter.spi.TypeLiteral; +import com.fasterxml.jackson.core.type.TypeReference; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; @@ -99,8 +99,8 @@ public enum TypeHandler StringType("String $L = $T.string(exchange,$S)", false, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class, StatementParameterType.STRING), BooleanType("Boolean $L = $T.booleanValue(exchange,$S)", false, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class, StatementParameterType.STRING), FilePathType("$T $L = $T.filePath(exchange,$S)", true, java.nio.file.Path.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class, StatementParameterType.STRING), - AnyType("$T $L = $T.any(exchange)", true, com.jsoniter.any.Any.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class), - JsonIteratorType("$T $L = $T.jsonIterator(exchange)", true, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class), + AnyType("$T $L = $T.any(exchange)", true, com.fasterxml.jackson.databind.JsonNode.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class), + JsonNodeType("$T $L = $T.jsonNode(exchange)", true, com.fasterxml.jackson.databind.JsonNode.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.class), ModelType("$T $L = io.sinistral.proteus.server.Extractors.model(exchange,$L)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL, StatementParameterType.LITERAL), // EnumType("$T $L = $T.enumValue(exchange,$T.class,$S)", true, StatementParameterType.TYPE, StatementParameterType.LITERAL,io.sinistral.proteus.server.Extractors.class, StatementParameterType.TYPE, StatementParameterType.STRING), @@ -139,8 +139,8 @@ public enum TypeHandler OptionalBeanListFromStringType("java.util.Optional<$L> $L = $T.model(exchange,$L)", false, StatementParameterType.TYPE, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class, StatementParameterType.LITERAL), - OptionalJsonIteratorType("$T<$T> $L = $T.jsonIterator(exchange)", true, Optional.class, com.jsoniter.JsonIterator.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class), - OptionalAnyType("$T<$T> $L = $T.any(exchange)", true, Optional.class, com.jsoniter.any.Any.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class), + OptionalJsonNodeType("$T<$T> $L = $T.jsonNode(exchange)", true, Optional.class, com.fasterxml.jackson.databind.JsonNode.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class), + OptionalAnyType("$T<$T> $L = $T.any(exchange)", true, Optional.class, com.fasterxml.jackson.databind.JsonNode.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class), OptionalStringType("$T $L = $T.string(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class, StatementParameterType.STRING), OptionalLongType("$T $L = $T.longValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class, StatementParameterType.STRING), OptionalIntegerType("$T $L = $T.integerValue(exchange,$S)", false, Optional.class, StatementParameterType.LITERAL, io.sinistral.proteus.server.Extractors.Optional.class, StatementParameterType.STRING), @@ -182,7 +182,7 @@ public String statement() final private String statement; /** - * If the TypeLiteral requires the {@link io.undertow.server.HttpHandler} to block + * If the TypeReference requires the {@link io.undertow.server.HttpHandler} to block */ final private boolean isBlocking; @@ -211,7 +211,7 @@ public static void addStatement(MethodSpec.Builder builder, Parameter parameter, Object[] args = new Object[handler.parameterTypes.length]; -///typeLiteralNameForParameterizedType +///typeReferenceNameForParameterizedType for (int i = 0; i < handler.parameterTypes.length; i++) { if (handler.parameterTypes[i] instanceof StatementParameterType) @@ -474,13 +474,13 @@ else if (type.equals(java.time.OffsetDateTime.class)) { return OffsetDateTimeType; } - else if (type.equals(com.jsoniter.any.Any.class)) + else if (type.equals(com.fasterxml.jackson.databind.JsonNode.class)) { return AnyType; } - else if (type.equals(com.jsoniter.JsonIterator.class)) + else if (type.equals(com.fasterxml.jackson.databind.JsonNode.class)) { - return JsonIteratorType; + return JsonNodeType; } else if (isOptional) { @@ -693,7 +693,7 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class cla TypeHandler handler = TypeHandler.forType(t); return (handler.equals(TypeHandler.ModelType) || handler.equals(TypeHandler.OptionalModelType)); - }).collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeLiteralNameForParameterizedType)); + }).collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeReferenceNameForParameterizedType)); Arrays.stream(clazz.getDeclaredMethods()).filter( m -> m.getAnnotation(ApiOperation.class) != null).flatMap(m -> Arrays.stream(m.getParameters())).forEach( p -> { @@ -708,7 +708,7 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class cla if( handler.equals(TypeHandler.BeanListValueOfType) || handler.equals(TypeHandler.BeanListFromStringType) || handler.equals(TypeHandler.OptionalBeanListValueOfType) || handler.equals(TypeHandler.OptionalBeanListFromStringType)) { - parameterizedLiteralsNameMap.put(p.getParameterizedType(),HandlerGenerator.typeLiteralNameForParameterizedType(p.getParameterizedType())); + parameterizedLiteralsNameMap.put(p.getParameterizedType(),HandlerGenerator.typeReferenceNameForParameterizedType(p.getParameterizedType())); } } @@ -724,7 +724,7 @@ protected void addClassMethodHandlers(TypeSpec.Builder typeBuilder, Class cla // TypeHandler handler = TypeHandler.forType(t); // return (handler.equals(TypeHandler.ModelType) || handler.equals(TypeHandler.OptionalModelType)); - // }).collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeLiteralNameForParameterizedType)); + // }).collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeReferenceNameForParameterizedType)); final Map literalsNameMap = Arrays.stream(clazz.getDeclaredMethods()).filter( m -> m.getAnnotation(ApiOperation.class) != null).flatMap(m -> Arrays.stream(m.getParameters()).map(Parameter::getParameterizedType)).filter(t -> { @@ -784,11 +784,11 @@ else if (t.equals(HttpServerExchange.class) || t.equals(ServerRequest.class)) return true; - }).distinct().collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeLiteralNameForType)); + }).distinct().collect(Collectors.toMap(java.util.function.Function.identity(), HandlerGenerator::typeReferenceNameForType)); - parameterizedLiteralsNameMap.forEach((t, n) -> initBuilder.addStatement("final $T<$L> $LTypeLiteral = new $T<$L>(){}", TypeLiteral.class, t, n, TypeLiteral.class, t)); + parameterizedLiteralsNameMap.forEach((t, n) -> initBuilder.addStatement("final $T<$L> $LTypeReference = new $T<$L>(){}", TypeReference.class, t, n, TypeReference.class, t)); - literalsNameMap.forEach((t, n) -> initBuilder.addStatement("final $T<$T> $LTypeLiteral = new $T<$T>(){}", TypeLiteral.class, t, n, TypeLiteral.class, t)); + literalsNameMap.forEach((t, n) -> initBuilder.addStatement("final $T<$T> $LTypeReference = new $T<$T>(){}", TypeReference.class, t, n, TypeReference.class, t)); Optional typeLevelWrapAnnotation = Optional.ofNullable(clazz.getAnnotation(io.sinistral.proteus.annotations.Chain.class)); Map, String> typeLevelHandlerWrapperMap = new LinkedHashMap, String>(); @@ -1090,7 +1090,7 @@ else if (handler.equals(TypeHandler.FromStringType)) { String interfaceType = parameterizedLiteralsNameMap.get(type); - String pType = interfaceType != null ? interfaceType + "TypeLiteral" : type.getTypeName() + ".class"; + String pType = interfaceType != null ? interfaceType + "TypeReference" : type.getTypeName() + ".class"; methodBuilder.addStatement(t.statement, type, p.getName(), pType); @@ -1099,7 +1099,7 @@ else if (t.equals(TypeHandler.BeanListFromStringType) || t.equals(TypeHandler.Be { String interfaceType = parameterizedLiteralsNameMap.get(type); - String pType = interfaceType != null ? interfaceType + "TypeLiteral" : type.getTypeName() + ".class"; + String pType = interfaceType != null ? interfaceType + "TypeReference" : type.getTypeName() + ".class"; methodBuilder.addStatement(t.statement, type, p.getName(), pType); @@ -1506,7 +1506,7 @@ else if (matches > 2) return null; } - protected static String typeLiteralNameForParameterizedType(Type type) + protected static String typeReferenceNameForParameterizedType(Type type) { String typeName = type.getTypeName(); @@ -1586,7 +1586,7 @@ protected static String typeLiteralNameForParameterizedType(Type type) return typeName; } - protected static String typeLiteralNameForType(Type type) + protected static String typeReferenceNameForType(Type type) { String typeName = type.getTypeName(); @@ -1631,10 +1631,10 @@ protected static String generateFieldName(String name) return sb.toString(); } - protected static void generateTypeLiteral(MethodSpec.Builder builder, Type type, String name) + protected static void generateTypeReference(MethodSpec.Builder builder, Type type, String name) { - builder.addCode(CodeBlock.of("\n\ncom.jsoniter.spi.TypeLiteral<$T> $L = new com.jsoniter.spi.TypeLiteral<$L>(){};\n\n", type, name, type)); + builder.addCode(CodeBlock.of("\n\ncom.fasterxml.jackson.core.type.TypeReference<$T> $L = new com.fasterxml.jackson.core.type.TypeReference<$L>(){};\n\n", type, name, type)); } diff --git a/src/main/java/io/sinistral/proteus/server/handlers/ServerDefaultResponseListener.java b/src/main/java/io/sinistral/proteus/server/handlers/ServerDefaultResponseListener.java index 651d69b..bff3542 100644 --- a/src/main/java/io/sinistral/proteus/server/handlers/ServerDefaultResponseListener.java +++ b/src/main/java/io/sinistral/proteus/server/handlers/ServerDefaultResponseListener.java @@ -12,10 +12,10 @@ import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.inject.Inject; import com.google.inject.Singleton; -import com.jsoniter.output.JsonStream; import io.sinistral.proteus.server.predicates.ServerPredicates; import io.undertow.server.DefaultResponseListener; @@ -36,6 +36,8 @@ public class ServerDefaultResponseListener implements DefaultResponseListener @Inject protected XmlMapper xmlMapper; + @Inject + protected ObjectMapper objectMapper; @Override public boolean handleDefaultResponse(HttpServerExchange exchange) @@ -88,7 +90,15 @@ public boolean handleDefaultResponse(HttpServerExchange exchange) } else { - final String jsonBody = JsonStream.serialize(errorMap); + String jsonBody; + + try + { + jsonBody = objectMapper.writeValueAsString(errorMap); + } catch (Exception e) + { + jsonBody = errorMap.toString(); + } exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, MediaType.APPLICATION_JSON); exchange.getResponseHeaders().put(Headers.CONTENT_LENGTH, jsonBody.length()); diff --git a/src/test/java/io/sinistral/proteus/controllers/Tests.java b/src/test/java/io/sinistral/proteus/controllers/Tests.java index fde4af7..7e4bd95 100644 --- a/src/test/java/io/sinistral/proteus/controllers/Tests.java +++ b/src/test/java/io/sinistral/proteus/controllers/Tests.java @@ -26,10 +26,11 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; +import com.google.inject.Inject; import com.google.inject.Singleton; -import com.jsoniter.output.JsonStream; import io.sinistral.proteus.annotations.Blocking; import io.sinistral.proteus.models.User; @@ -39,7 +40,6 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.undertow.server.HttpServerExchange; -import io.undertow.server.handlers.RequestBufferingHandler; /** * @author jbauer @@ -61,14 +61,22 @@ public class Tests buffer.flip(); } + @Inject + protected ObjectMapper objectMapper; + + @GET @Path("/exchange/json/serialize") @ApiOperation(value = "Json serialization endpoint", httpMethod = "GET" ) - public void exchangeJsonSerialize(HttpServerExchange exchange) - { - - - response( JsonStream.serialize(ImmutableMap.of("message", "Hello, World!")) ).applicationJson().send(exchange); + public void exchangeJsonSerialize(HttpServerExchange exchange) + { + try + { + response( objectMapper.writeValueAsString(ImmutableMap.of("message", "Hello, World!")) ).applicationJson().send(exchange); + } catch(Exception e) + { + response().badRequest(e); + } } @GET @@ -76,7 +84,13 @@ public void exchangeJsonSerialize(HttpServerExchange exchange) @ApiOperation(value = "Json serialization with bytes endpoint", httpMethod = "GET" ) public void exchangeJsonSerializeToBytes(HttpServerExchange exchange) { - response( JsonStream.serializeToBytes(ImmutableMap.of("message", "Hello, World!")) ).applicationJson().send(exchange); + try + { + response( objectMapper.writeValueAsString(ImmutableMap.of("message", "Hello, World!")) ).applicationJson().send(exchange); + } catch(Exception e) + { + response().badRequest(e); + } } diff --git a/src/test/java/io/sinistral/proteus/server/TestControllerEndpoints.java b/src/test/java/io/sinistral/proteus/server/TestControllerEndpoints.java index bc3e56c..68b8e7e 100644 --- a/src/test/java/io/sinistral/proteus/server/TestControllerEndpoints.java +++ b/src/test/java/io/sinistral/proteus/server/TestControllerEndpoints.java @@ -27,9 +27,6 @@ import org.junit.Test; import org.junit.runner.RunWith; -import com.jsoniter.JsonIterator; -import com.jsoniter.output.JsonStream; - import io.restassured.http.ContentType; import io.sinistral.proteus.models.User; import io.sinistral.proteus.models.User.UserType;