reconf.infra.http.layer.SimpleHttpClient.java Source code

Java tutorial

Introduction

Here is the source code for reconf.infra.http.layer.SimpleHttpClient.java

Source

/*
 *    Copyright 2013-2014 ReConf Team
 *
 *   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 reconf.infra.http.layer;

import java.net.*;
import java.security.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import org.apache.http.*;
import org.apache.http.client.config.*;
import org.apache.http.impl.client.*;
import reconf.infra.i18n.*;

public class SimpleHttpClient {

    private static final MessagesBundle msg = MessagesBundle.getBundle(SimpleHttpClient.class);

    private static ExecutorService requestExecutor = Executors.newFixedThreadPool(10, new ThreadFactory() {
        private final AtomicInteger counter = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "reconf-http-client-" + counter.getAndIncrement());
            t.setDaemon(true);
            return t;
        }
    });

    public static SimpleHttpRequest newGetRequest(String pathBase, String... pathParam) throws URISyntaxException {
        return new SimpleHttpRequest("GET", pathBase, pathParam);
    }

    public static SimpleHttpResponse defaultExecute(SimpleHttpRequest request, long timeout, TimeUnit timeunit,
            int retries) throws Exception {
        return execute(newHttpClient(timeout, timeunit, retries), request, timeout, timeunit);
    }

    private static SimpleHttpResponse execute(CloseableHttpClient httpClient, SimpleHttpRequest request,
            long timeout, TimeUnit timeunit) throws Exception {

        RequestTask task = new RequestTask(httpClient, request);
        Future<SimpleHttpResponse> futureResponse = null;

        try {
            futureResponse = requestExecutor.submit(task);
            return futureResponse.get(timeout, timeunit);

        } catch (TimeoutException e) {
            httpClient.close();
            RequestLine line = request.getRequestLine();
            String method = request.getMethod();

            if (line != null && method != null) {
                throw new TimeoutException(msg.format("error.complete", method.toUpperCase(), line.getUri(),
                        timeout, timeunit.toString().toLowerCase()));

            } else {
                throw new TimeoutException(msg.format("error", timeout, timeunit.toString().toLowerCase()));
            }

        } catch (Exception e) {
            httpClient.close();
            throw e;

        } finally {
            if (futureResponse != null) {
                futureResponse.cancel(true);
            }
        }
    }

    private static CloseableHttpClient newHttpClient(long timeout, TimeUnit timeUnit, int retries)
            throws GeneralSecurityException {
        return HttpClientBuilder.create().setRetryHandler(new RetryHandler(retries))
                .setDefaultRequestConfig(createBasicHttpParams(timeout, timeUnit)).build();
    }

    private static RequestConfig createBasicHttpParams(long timeout, TimeUnit timeUnit) {
        int timemillis = (int) TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
        return RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .setStaleConnectionCheckEnabled(false).setConnectTimeout(timemillis).setSocketTimeout(timemillis)
                .setConnectionRequestTimeout(timemillis).build();
    }
}