|
| 1 | +/** |
| 2 | + * Copyright 2012-2018 The Feign Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
| 5 | + * in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the License |
| 10 | + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
| 11 | + * or implied. See the License for the specific language governing permissions and limitations under |
| 12 | + * the License. |
| 13 | + */ |
| 14 | +package feign.jackson; |
| 15 | + |
| 16 | +import com.fasterxml.jackson.core.JsonParser; |
| 17 | +import com.fasterxml.jackson.core.JsonToken; |
| 18 | +import com.fasterxml.jackson.databind.*; |
| 19 | +import feign.Response; |
| 20 | +import feign.Util; |
| 21 | +import feign.codec.DecodeException; |
| 22 | +import feign.codec.Decoder; |
| 23 | + |
| 24 | +import java.io.BufferedReader; |
| 25 | +import java.io.Closeable; |
| 26 | +import java.io.IOException; |
| 27 | +import java.io.Reader; |
| 28 | +import java.lang.reflect.ParameterizedType; |
| 29 | +import java.lang.reflect.Type; |
| 30 | +import java.util.Collections; |
| 31 | +import java.util.Iterator; |
| 32 | + |
| 33 | +import static feign.Util.ensureClosed; |
| 34 | + |
| 35 | +/** |
| 36 | + * Jackson decoder which return a closeable iterator. |
| 37 | + * Returned iterator auto-close the {@code Response} when it reached json array end or failed to parse stream. |
| 38 | + * If this iterator is not fetched till the end, it has to be casted to {@code Closeable} and explicity {@code Closeable#close} by the consumer. |
| 39 | + * <p> |
| 40 | + * <p> |
| 41 | + * <p>Example: <br> |
| 42 | + * <pre><code> |
| 43 | + * Feign.builder() |
| 44 | + * .decoder(JacksonIteratorDecoder.create()) |
| 45 | + * .doNotCloseAfterDecode() // Required to fetch the iterator after the response is processed, need to be close |
| 46 | + * .target(GitHub.class, "https://api.github.com"); |
| 47 | + * interface GitHub { |
| 48 | + * {@literal @}RequestLine("GET /repos/{owner}/{repo}/contributors") |
| 49 | + * Iterator<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo); |
| 50 | + * }</code></pre> |
| 51 | + */ |
| 52 | +public final class JacksonIteratorDecoder implements Decoder { |
| 53 | + |
| 54 | + private final ObjectMapper mapper; |
| 55 | + |
| 56 | + JacksonIteratorDecoder(ObjectMapper mapper) { |
| 57 | + this.mapper = mapper; |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public Object decode(Response response, Type type) throws IOException { |
| 62 | + if (response.status() == 404) return Util.emptyValueOf(type); |
| 63 | + if (response.body() == null) return null; |
| 64 | + Reader reader = response.body().asReader(); |
| 65 | + if (!reader.markSupported()) { |
| 66 | + reader = new BufferedReader(reader, 1); |
| 67 | + } |
| 68 | + try { |
| 69 | + // Read the first byte to see if we have any data |
| 70 | + reader.mark(1); |
| 71 | + if (reader.read() == -1) { |
| 72 | + return null; // Eagerly returning null avoids "No content to map due to end-of-input" |
| 73 | + } |
| 74 | + reader.reset(); |
| 75 | + return new JacksonIterator<Object>(actualIteratorTypeArgument(type), mapper, response, reader); |
| 76 | + } catch (RuntimeJsonMappingException e) { |
| 77 | + if (e.getCause() != null && e.getCause() instanceof IOException) { |
| 78 | + throw IOException.class.cast(e.getCause()); |
| 79 | + } |
| 80 | + throw e; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + private static Type actualIteratorTypeArgument(Type type) { |
| 85 | + if (!(type instanceof ParameterizedType)) { |
| 86 | + throw new IllegalArgumentException("Not supported type " + type.toString()); |
| 87 | + } |
| 88 | + ParameterizedType parameterizedType = (ParameterizedType) type; |
| 89 | + if (!Iterator.class.equals(parameterizedType.getRawType())) { |
| 90 | + throw new IllegalArgumentException("Not an iterator type " + parameterizedType.getRawType().toString()); |
| 91 | + } |
| 92 | + return ((ParameterizedType) type).getActualTypeArguments()[0]; |
| 93 | + } |
| 94 | + |
| 95 | + public static JacksonIteratorDecoder create() { |
| 96 | + return create(Collections.<Module>emptyList()); |
| 97 | + } |
| 98 | + |
| 99 | + public static JacksonIteratorDecoder create(Iterable<Module> modules) { |
| 100 | + return new JacksonIteratorDecoder(new ObjectMapper() |
| 101 | + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) |
| 102 | + .registerModules(modules)); |
| 103 | + } |
| 104 | + |
| 105 | + public static JacksonIteratorDecoder create(ObjectMapper objectMapper) { |
| 106 | + return new JacksonIteratorDecoder(objectMapper); |
| 107 | + } |
| 108 | + |
| 109 | + static final class JacksonIterator<T> implements Iterator<T>, Closeable { |
| 110 | + private final Response response; |
| 111 | + private final JsonParser parser; |
| 112 | + private final ObjectReader objectReader; |
| 113 | + |
| 114 | + private T current; |
| 115 | + |
| 116 | + JacksonIterator(Type type, ObjectMapper mapper, Response response, Reader reader) |
| 117 | + throws IOException { |
| 118 | + this.response = response; |
| 119 | + this.parser = mapper.getFactory().createParser(reader); |
| 120 | + this.objectReader = mapper.reader().forType(mapper.constructType(type)); |
| 121 | + } |
| 122 | + |
| 123 | + @Override |
| 124 | + public boolean hasNext() { |
| 125 | + try { |
| 126 | + JsonToken jsonToken = parser.nextToken(); |
| 127 | + if (jsonToken == null) { |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + if (jsonToken == JsonToken.START_ARRAY) { |
| 132 | + jsonToken = parser.nextToken(); |
| 133 | + } |
| 134 | + |
| 135 | + if (jsonToken == JsonToken.END_ARRAY) { |
| 136 | + current = null; |
| 137 | + ensureClosed(this); |
| 138 | + return false; |
| 139 | + } |
| 140 | + |
| 141 | + current = objectReader.readValue(parser); |
| 142 | + } catch (IOException e) { |
| 143 | + // Input Stream closed automatically by parser |
| 144 | + throw new DecodeException(e.getMessage(), e); |
| 145 | + } |
| 146 | + return current != null; |
| 147 | + } |
| 148 | + |
| 149 | + @Override |
| 150 | + public T next() { |
| 151 | + return current; |
| 152 | + } |
| 153 | + |
| 154 | + @Override |
| 155 | + public void remove() { |
| 156 | + throw new UnsupportedOperationException(); |
| 157 | + } |
| 158 | + |
| 159 | + @Override |
| 160 | + public void close() throws IOException { |
| 161 | + ensureClosed(this.response); |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments