com.raskasa.dropwizard.okhttp.samples.ExternalServiceResource.java Source code

Java tutorial

Introduction

Here is the source code for com.raskasa.dropwizard.okhttp.samples.ExternalServiceResource.java

Source

/*
 * Copyright 2015 Ras Kasa Williams
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.raskasa.dropwizard.okhttp.samples;

import com.google.common.base.Optional;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

@Path("/twitter")
public final class ExternalServiceResource {
    private final OkHttpClient client;

    public ExternalServiceResource(OkHttpClient client) {
        this.client = client;
    }

    @GET
    public String sayHello(@QueryParam("name") Optional<String> user) {
        Request request = new Request.Builder()
                .url(String.format("https://api.github.com/users/%s/repos", user.or("dropwizard"))).build();

        try {
            final CountDownLatch latch = new CountDownLatch(1);
            final Holder holder = new Holder();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    latch.countDown();
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    holder.setResponse(response.body().string());
                    latch.countDown();
                }
            });
            latch.await();
            return holder.getResponse();
        } catch (InterruptedException e) {
            return "Error making network request.  Try again?";
        }
    }

    private static final class Holder {
        private String response;

        public String getResponse() {
            return response;
        }

        public void setResponse(String response) {
            this.response = response;
        }
    }
}