|
| 1 | +/* |
| 2 | + * Copyright 2013 Netflix, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package feign.example.cli; |
| 17 | + |
| 18 | +import com.google.common.collect.ImmutableMap; |
| 19 | +import com.google.common.reflect.TypeToken; |
| 20 | +import com.google.gson.Gson; |
| 21 | + |
| 22 | +import java.io.Reader; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Map; |
| 25 | + |
| 26 | +import javax.inject.Singleton; |
| 27 | +import javax.ws.rs.GET; |
| 28 | +import javax.ws.rs.Path; |
| 29 | +import javax.ws.rs.PathParam; |
| 30 | + |
| 31 | +import dagger.Module; |
| 32 | +import dagger.Provides; |
| 33 | +import feign.Feign; |
| 34 | +import feign.codec.Decoder; |
| 35 | + |
| 36 | +/** |
| 37 | + * adapted from {@code com.example.retrofit.GitHubClient} |
| 38 | + */ |
| 39 | +public class GitHubExample { |
| 40 | + |
| 41 | + interface GitHub { |
| 42 | + @GET @Path("/repos/{owner}/{repo}/contributors") |
| 43 | + List<Contributor> contributors(@PathParam("owner") String owner, @PathParam("repo") String repo); |
| 44 | + } |
| 45 | + |
| 46 | + static class Contributor { |
| 47 | + String login; |
| 48 | + int contributions; |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String... args) { |
| 52 | + GitHub github = Feign.create(GitHub.class, "https://api.github.com", new GsonModule()); |
| 53 | + |
| 54 | + // Fetch and print a list of the contributors to this library. |
| 55 | + List<Contributor> contributors = github.contributors("netflix", "feign"); |
| 56 | + for (Contributor contributor : contributors) { |
| 57 | + System.out.println(contributor.login + " (" + contributor.contributions + ")"); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * Here's how to wire gson deserialization. |
| 63 | + */ |
| 64 | + @Module(overrides = true, library = true) |
| 65 | + static class GsonModule { |
| 66 | + @Provides @Singleton Map<String, Decoder> decoders() { |
| 67 | + return ImmutableMap.of("GitHub", jsonDecoder); |
| 68 | + } |
| 69 | + |
| 70 | + final Decoder jsonDecoder = new Decoder() { |
| 71 | + Gson gson = new Gson(); |
| 72 | + |
| 73 | + @Override public Object decode(String methodKey, Reader reader, TypeToken<?> type) { |
| 74 | + return gson.fromJson(reader, type.getType()); |
| 75 | + } |
| 76 | + }; |
| 77 | + } |
| 78 | +} |
0 commit comments