All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.fraunhofer.iese.ind2uce.json.GsonConverter Maven / Gradle / Ivy

Go to download

IND2UCE :: Webproject related contents like JSON, Autoconfiguration of Spring, etc.

There is a newer version: 3.2.69
Show newest version
/*-
 * =================================LICENSE_START=================================
 * IND2UCE
 * %%
 * Copyright (C) 2016 Fraunhofer IESE (www.iese.fraunhofer.de)
 * %%
 * The Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V., Hansastrasse 27c, 80686 Munich, Germany (further: Fraunhofer) is holder of all proprietary rights on this computer program.
 * You can only use this computer program if you have closed a license agreement with Fraunhofer or you get the right to use the computer program from someone who is authorized to grant you that right.
 * Any use of the computer program without a valid license is prohibited and liable to prosecution.
 *
 * Copyright (C) 2018 Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V. acting on behalf of its Fraunhofer Institute for Experimental Software Engineering (IESE)
 *
 * All rights reserved.
 *
 * Contact: [email protected]
 * =================================LICENSE_END=================================
 */

package de.fraunhofer.iese.ind2uce.json;

import de.fraunhofer.iese.ind2uce.api.common.Ind2uceEntity;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

// TODO: Auto-generated Javadoc
/**
 * Implementation of
 * {@link org.springframework.http.converter.HttpMessageConverter} that can read
 * and write JSON using the
 * Google Gson library's
 * {@link Gson} class.
 * 

* This converter can be used to bind to typed beans or untyped {@code HashMap} * s. By default, it supports {@code application/json} and * {@code application/*+json}. *

*

* Tested against Gson 2.3; compatible with Gson 2.0 and higher. *

* * @author Roy Clarkson * @see #setSupportedMediaTypes * @since 4.1 */ public class GsonConverter extends AbstractHttpMessageConverter implements GenericHttpMessageConverter { /** * The Constant DEFAULT_CHARSET. */ public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); /** * The gson. */ private final Gson gson = Ind2uceEntity.getGson(); /** * Construct a new {@code GsonHttpMessageConverter}. */ public GsonConverter() { super(new MediaType("application", "json", DEFAULT_CHARSET), new MediaType("application", "*+json", DEFAULT_CHARSET)); } /* * (non-Javadoc) * @see * org.springframework.http.converter.AbstractHttpMessageConverter#canRead( * java.lang.Class, org.springframework.http.MediaType) */ @Override public boolean canRead(Class clazz, MediaType mediaType) { return this.canRead(mediaType); } /* * (non-Javadoc) * @see * org.springframework.http.converter.GenericHttpMessageConverter#canRead(java * .lang.reflect.Type, java.lang.Class, org.springframework.http.MediaType) */ @Override public boolean canRead(Type type, Class contextClass, MediaType mediaType) { return this.canRead(mediaType); } /* * (non-Javadoc) * @see * org.springframework.http.converter.AbstractHttpMessageConverter#canWrite( * java.lang.Class, org.springframework.http.MediaType) */ @Override public boolean canWrite(Class clazz, MediaType mediaType) { return this.canWrite(mediaType); } /* * (non-Javadoc) * @see * org.springframework.http.converter.GenericHttpMessageConverter#canWrite( * java.lang.reflect.Type, java.lang.Class, * org.springframework.http.MediaType) */ @Override public boolean canWrite(Type arg0, Class arg1, MediaType arg2) { return this.canWrite(arg2); } /* * (non-Javadoc) * @see * org.springframework.http.converter.GenericHttpMessageConverter#write(java. * lang.Object, java.lang.reflect.Type, org.springframework.http.MediaType, * org.springframework.http.HttpOutputMessage) */ @Override public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { write(o, contentType, outputMessage); } /* * (non-Javadoc) * @see * org.springframework.http.converter.AbstractHttpMessageConverter#supports( * java.lang.Class) */ @Override protected boolean supports(Class clazz) { // should not be called, since we override canRead/Write instead throw new UnsupportedOperationException(); } /** * Read internal. * * @param arg0 the arg 0 * @param arg1 the arg 1 * @return the object * @throws IOException Signals that an I/O exception has occurred. * @throws HttpMessageNotReadableException the http message not readable * exception */ @Override protected Object readInternal(Class arg0, HttpInputMessage arg1) throws IOException, HttpMessageNotReadableException { final TypeToken token = this.getTypeToken(arg0); return this.readTypeToken(token, arg1); } /* * (non-Javadoc) * @see * org.springframework.http.converter.GenericHttpMessageConverter#read(java. * lang.reflect.Type, java.lang.Class, * org.springframework.http.HttpInputMessage) */ @Override public Object read(Type type, Class contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { final TypeToken token = this.getTypeToken(type); return this.readTypeToken(token, inputMessage); } /** * Return the Gson {@link TypeToken} for the specified type. *

* The default implementation returns {@code TypeToken.get(type)}, but this * can be overridden in subclasses to allow for custom generic collection * handling. For instance: * *

   * protected TypeToken<?> getTypeToken(Type type) {
   *   if (type instanceof Class && List.class.isAssignableFrom((Class<?>)type)) {
   *     return new TypeToken<ArrayList<MyBean>>() {
   *     };
   *   } else {
   *     return super.getTypeToken(type);
   *   }
   * }
   * 
* * @param type the type for which to return the TypeToken * @return the type token */ protected TypeToken getTypeToken(Type type) { return TypeToken.get(type); } /** * Read type token. * * @param token the token * @param inputMessage the input message * @return the object * @throws IOException Signals that an I/O exception has occurred. */ private Object readTypeToken(TypeToken token, HttpInputMessage inputMessage) throws IOException { final Reader json = new InputStreamReader(inputMessage.getBody(), this.getCharset(inputMessage.getHeaders())); try { return this.gson.fromJson(json, token.getType()); } catch (final JsonParseException ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex); } } /** * Gets the charset. * * @param headers the headers * @return the charset */ private Charset getCharset(HttpHeaders headers) { if (headers == null || headers.getContentType() == null || headers.getContentType().getCharset() == null) { return DEFAULT_CHARSET; } return headers.getContentType().getCharset(); } /* * (non-Javadoc) * @see org.springframework.http.converter.AbstractHttpMessageConverter# * writeInternal(java.lang.Object, org.springframework.http.HttpOutputMessage) */ @Override public void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException { final Charset charset = this.getCharset(outputMessage.getHeaders()); final OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset); try { final String json = this.gson.toJson(o); writer.write(json); writer.close(); } catch (final JsonIOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } } }