1package com.squareup.okhttp.sample;
2
3import com.google.gson.Gson;
4import com.google.gson.reflect.TypeToken;
5import com.squareup.okhttp.OkHttpClient;
6import java.io.InputStream;
7import java.io.InputStreamReader;
8import java.net.HttpURLConnection;
9import java.net.URL;
10import java.util.Collections;
11import java.util.Comparator;
12import java.util.List;
13
14public class OkHttpContributors {
15  private static final String ENDPOINT = "https://api.github.com/repos/square/okhttp/contributors";
16  private static final Gson GSON = new Gson();
17  private static final TypeToken<List<Contributor>> CONTRIBUTORS =
18      new TypeToken<List<Contributor>>() {
19      };
20
21  static class Contributor {
22    String login;
23    int contributions;
24  }
25
26  public static void main(String... args) throws Exception {
27    OkHttpClient client = new OkHttpClient();
28
29    // Create request for remote resource.
30    HttpURLConnection connection = client.open(new URL(ENDPOINT));
31    InputStream is = connection.getInputStream();
32    InputStreamReader isr = new InputStreamReader(is);
33
34    // Deserialize HTTP response to concrete type.
35    List<Contributor> contributors = GSON.fromJson(isr, CONTRIBUTORS.getType());
36
37    // Sort list by the most contributions.
38    Collections.sort(contributors, new Comparator<Contributor>() {
39      @Override public int compare(Contributor c1, Contributor c2) {
40        return c2.contributions - c1.contributions;
41      }
42    });
43
44    // Output list of contributors.
45    for (Contributor contributor : contributors) {
46      System.out.println(contributor.login + ": " + contributor.contributions);
47    }
48  }
49
50  private OkHttpContributors() {
51    // No instances.
52  }
53}
54