View Javadoc
1   package org.oxerr.okcoin.rest.dto.valuereader;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.nio.charset.Charset;
6   import java.nio.charset.StandardCharsets;
7   import java.util.logging.Level;
8   import java.util.logging.Logger;
9   
10  import javax.annotation.Nullable;
11  
12  import org.apache.commons.io.IOUtils;
13  
14  import com.fasterxml.jackson.core.type.TypeReference;
15  import com.fasterxml.jackson.databind.JsonMappingException;
16  import com.fasterxml.jackson.databind.ObjectMapper;
17  
18  public class JsonValueTypeRefReader<T> implements ValueReader<T> {
19  
20  	private final Logger log = Logger.getLogger(getClass().getName());
21  
22  	private final ObjectMapper objectMapper;
23  
24  	private final TypeReference<T> valueTypeRef;
25  
26  	public JsonValueTypeRefReader(ObjectMapper objectMapper,
27  			TypeReference<T> valueTypeRef) {
28  		this.objectMapper = objectMapper;
29  		this.valueTypeRef = valueTypeRef;
30  	}
31  
32  	/**
33  	 * {@inheritDoc}
34  	 */
35  	@Override
36  	public T read(InputStream inputStream,
37  		@Nullable String mimeType, @Nullable Charset charset) throws IOException {
38  		if (log.isLoggable(Level.FINEST)) {
39  			inputStream = IOUtils.buffer(inputStream);
40  			inputStream.mark(Integer.MAX_VALUE);
41  			String s = IOUtils.toString(inputStream, charset != null ? charset : StandardCharsets.UTF_8);
42  			log.log(Level.FINEST, "JSON: {0}", s);
43  			inputStream.reset();
44  		}
45  		try {
46  			return objectMapper.readValue(inputStream, valueTypeRef);
47  		} catch (JsonMappingException jme) {
48  			if (jme.getCause() instanceof RuntimeException) {
49  				throw (RuntimeException) jme.getCause();
50  			} else {
51  				throw jme;
52  			}
53  		}
54  	}
55  
56  }