Skip to content

Commit

Permalink
Jackson media support for Níma (#6432)
Browse files Browse the repository at this point in the history
* Jackson media support for Níma
* Unit tests for all JSON media supports for Níma
  • Loading branch information
tomas-langer authored Mar 24, 2023
1 parent e92222e commit 907dd05
Show file tree
Hide file tree
Showing 20 changed files with 1,335 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2022 Oracle and/or its affiliates.
* Copyright (c) 2022, 2023 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,7 @@

package io.helidon.common.http;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
Expand Down Expand Up @@ -191,6 +192,18 @@ default HttpMediaType withCharset(String charset) {
.build();
}

/**
* Create a new {@link io.helidon.common.http.HttpMediaType} instance with the same type, subtype and parameters
* copied from the original instance and the supplied {@value #CHARSET_PARAMETER} parameter.
*
* @param charset the {@value #CHARSET_PARAMETER} parameter value
* @return copy of the current {@code MediaType} instance with the {@value #CHARSET_PARAMETER}
* parameter set to the supplied value.
*/
default HttpMediaType withCharset(Charset charset) {
return withCharset(charset.name());
}

/**
* Text of this media type, to be used on the wire.
*
Expand Down
90 changes: 90 additions & 0 deletions nima/http/media/jackson/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2023 Oracle and/or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.helidon.nima.http.media</groupId>
<artifactId>helidon-nima-http-media-project</artifactId>
<version>4.0.0-SNAPSHOT</version>
</parent>

<artifactId>helidon-nima-http-media-jacskon</artifactId>
<name>Helidon Níma HTTP Media Jackson</name>

<dependencies>
<dependency>
<groupId>io.helidon.nima.http.media</groupId>
<artifactId>helidon-nima-http-media</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.common.features</groupId>
<artifactId>helidon-common-features-api</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.helidon.common.testing</groupId>
<artifactId>helidon-common-testing-http-junit5</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.helidon.common.features</groupId>
<artifactId>helidon-common-features-processor</artifactId>
<version>${helidon.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.nima.http.media.jackson;

import io.helidon.common.GenericType;
import io.helidon.common.Weighted;
import io.helidon.common.http.Headers;
import io.helidon.common.http.Http;
import io.helidon.common.http.HttpMediaType;
import io.helidon.common.http.WritableHeaders;
import io.helidon.common.media.type.MediaTypes;
import io.helidon.nima.http.media.EntityReader;
import io.helidon.nima.http.media.EntityWriter;
import io.helidon.nima.http.media.MediaContext;
import io.helidon.nima.http.media.spi.MediaSupportProvider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import static io.helidon.common.http.Http.HeaderValues.CONTENT_TYPE_JSON;

/**
* {@link java.util.ServiceLoader} provider implementation for Jackson media support.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class JacksonMediaSupportProvider implements MediaSupportProvider, Weighted {
private JacksonReader reader;
private JacksonWriter writer;
private ObjectMapper objectMapper;

@Override
public void init(MediaContext context) {
objectMapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());

reader = new JacksonReader(objectMapper);
writer = new JacksonWriter(objectMapper);
}

@Override
public <T> ReaderResponse<T> reader(GenericType<T> type, Headers requestHeaders) {
if (requestHeaders.contentType()
.map(it -> it.test(MediaTypes.APPLICATION_JSON))
.orElse(true)) {
if (objectMapper.canDeserialize(objectMapper.constructType(type.type()))) {
return new ReaderResponse<>(SupportLevel.COMPATIBLE, this::reader);
}
}

return ReaderResponse.unsupported();
}

@Override
public <T> WriterResponse<T> writer(GenericType<T> type,
Headers requestHeaders,
WritableHeaders<?> responseHeaders) {
// check if accepted
for (HttpMediaType acceptedType : requestHeaders.acceptedTypes()) {
if (acceptedType.test(MediaTypes.APPLICATION_JSON)) {
if (objectMapper.canSerialize(type.rawType())) {
return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer);
}
return WriterResponse.unsupported();
}
}

if (requestHeaders.acceptedTypes().isEmpty()) {
if (objectMapper.canSerialize(type.rawType())) {
return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer);
}
}

return WriterResponse.unsupported();
}

@Override
public <T> ReaderResponse<T> reader(GenericType<T> type,
Headers requestHeaders,
Headers responseHeaders) {
// check if accepted
for (HttpMediaType acceptedType : requestHeaders.acceptedTypes()) {
if (acceptedType.test(MediaTypes.APPLICATION_JSON) || acceptedType.mediaType().isWildcardType()) {
if (objectMapper.canDeserialize(objectMapper.constructType(type.type()))) {
return new ReaderResponse<>(SupportLevel.COMPATIBLE, this::reader);
}
}
}

if (requestHeaders.acceptedTypes().isEmpty()) {
if (objectMapper.canDeserialize(objectMapper.constructType(type.type()))) {
return new ReaderResponse<>(SupportLevel.COMPATIBLE, this::reader);
}
}

return ReaderResponse.unsupported();
}

@Override
public <T> WriterResponse<T> writer(GenericType<T> type, WritableHeaders<?> requestHeaders) {
if (requestHeaders.contains(Http.Header.CONTENT_TYPE)) {
if (requestHeaders.contains(CONTENT_TYPE_JSON)) {
if (objectMapper.canSerialize(type.rawType())) {
return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer);
}
return WriterResponse.unsupported();
}
} else {
if (objectMapper.canSerialize(type.rawType())) {
return new WriterResponse<>(SupportLevel.SUPPORTED, this::writer);
}
return WriterResponse.unsupported();
}
return WriterResponse.unsupported();
}

@Override
public double weight() {
// very low weight, as this covers all, but higher than JSON-B
return 11;
}

<T> EntityReader<T> reader() {
return reader;
}

<T> EntityWriter<T> writer() {
return writer;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright (c) 2023 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.helidon.nima.http.media.jackson;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import io.helidon.common.GenericType;
import io.helidon.common.http.Headers;
import io.helidon.common.http.HttpMediaType;
import io.helidon.nima.http.media.EntityReader;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

class JacksonReader<T> implements EntityReader<T> {

private final ObjectMapper objectMapper;

JacksonReader(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}

@Override
public T read(GenericType<T> type, InputStream stream, Headers headers) {
return read(type, stream, contentTypeCharset(headers));
}

@Override
public T read(GenericType<T> type,
InputStream stream,
Headers requestHeaders,
Headers responseHeaders) {

return read(type, stream, contentTypeCharset(responseHeaders));
}

@SuppressWarnings("unchecked")
private T read(GenericType<T> type, InputStream in, Charset charset) {
try (Reader r = new InputStreamReader(in, charset)) {
Type t = type.type();
if (t instanceof ParameterizedType) {
JavaType javaType = objectMapper.getTypeFactory().constructType(t);
return objectMapper.readValue(r, javaType);
} else {
return objectMapper.readValue(r, (Class<T>) type.rawType());
}
} catch (IOException e) {
throw new JacksonRuntimeException("Failed to deserialize JSON to " + type, e);
}
}

private Charset contentTypeCharset(Headers headers) {
return headers.contentType()
.flatMap(HttpMediaType::charset)
.map(Charset::forName)
.orElse(StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (c) 2019, 2023 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.nima.http.media.jackson;

/**
* A {@link RuntimeException} that indicates a problem was encountered
* while performing JSON manipulation with Jackson.
*/
public class JacksonRuntimeException extends RuntimeException {

/**
* Creates a new exception.
*/
JacksonRuntimeException(String message, Throwable cause) {
super(message, cause);
}

}
Loading

0 comments on commit 907dd05

Please sign in to comment.