| 30 | import java.util.Collections; |
| 31 | |
| 32 | public class JacksonDecoder implements Decoder, JsonDecoder { |
| 33 | |
| 34 | private final ObjectMapper mapper; |
| 35 | |
| 36 | public JacksonDecoder() { |
| 37 | this(Collections.<Module>emptyList()); |
| 38 | } |
| 39 | |
| 40 | public JacksonDecoder(Iterable<Module> modules) { |
| 41 | this( |
| 42 | new ObjectMapper() |
| 43 | .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) |
| 44 | .registerModules(modules)); |
| 45 | } |
| 46 | |
| 47 | public JacksonDecoder(ObjectMapper mapper) { |
| 48 | this.mapper = mapper; |
| 49 | } |
| 50 | |
| 51 | @Override |
| 52 | public Object decode(Response response, Type type) throws IOException { |
| 53 | if (response.status() == 404 || response.status() == 204) return Util.emptyValueOf(type); |
| 54 | if (response.body() == null) return null; |
| 55 | Reader reader = response.body().asReader(response.charset()); |
| 56 | if (!reader.markSupported()) { |
| 57 | reader = new BufferedReader(reader, 1); |
| 58 | } |
| 59 | try { |
| 60 | // Read the first byte to see if we have any data |
| 61 | reader.mark(1); |
| 62 | if (reader.read() == -1) { |
| 63 | return null; // Eagerly returning null avoids "No content to map due to end-of-input" |
| 64 | } |
| 65 | reader.reset(); |
| 66 | return mapper.readValue(reader, mapper.constructType(type)); |
| 67 | } catch (RuntimeJsonMappingException e) { |
| 68 | if (e.getCause() != null && e.getCause() instanceof IOException) { |
| 69 | throw IOException.class.cast(e.getCause()); |
| 70 | } |
| 71 | throw e; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | @Override |
| 76 | public Object convert(Object object, Type type) { |
| 77 | return mapper.convertValue(object, mapper.constructType(type)); |
| 78 | } |
| 79 | } |
nothing calls this directly
no outgoing calls
no test coverage detected