tv.arte.resteventapi.core.clients.RestEventApiRestClient.java Source code

Java tutorial

Introduction

Here is the source code for tv.arte.resteventapi.core.clients.RestEventApiRestClient.java

Source

package tv.arte.resteventapi.core.clients;

/*
 * #%L
 * RestEventAPI
 * %%
 * Copyright (C) 2014 ARTE G.E.I.E
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of The MIT License (MIT) as published by the Open Source 
 * Initiative.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See The 
 * MIT License (MIT) for more details.
 * 
 * You should have received a copy of The MIT License (MIT) 
 * along with this program.  If not, see <http://opensource.org/licenses/MIT>
 * #L%
 */

import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BufferedHeader;
import org.apache.http.util.CharArrayBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tv.arte.resteventapi.core.RestEventApiRuntimeException;
import tv.arte.resteventapi.core.domain.entities.RestEvent;

/**
 * A HTTP client for {@link RestEvent}
 * 
 * @author Simeon Petev
 * @since 0.1
 */
public class RestEventApiRestClient {

    private static Logger logger = LoggerFactory.getLogger(RestEventApiRestClient.class);

    /**
     * Executes the REST request described by the {@link RestEvent}
     * 
     * @param restEvent The {@link RestEvent} to process
     * @return A result of the execution
     * @throws RestEventApiRuntimeException In case of non managed errors
     */
    public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException {
        RestClientExecutionResult result = new RestClientExecutionResult();
        String url = restEvent.getUrl();
        CloseableHttpClient client = null;
        HttpUriRequest request = null;
        Integer responseCode = null;

        try {
            //Request custom configs
            RequestConfig.Builder requestBuilder = RequestConfig.custom();
            requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout());
            requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout());

            client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build();

            //Determine the method to execute
            switch (restEvent.getMethod()) {
            case GET:
                request = new HttpGet(url);
                break;
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            case DELETE:
                request = new HttpDelete(url);
                break;
            case PATCH:
                request = new HttpPatch(url);
                break;
            case HEAD:
                request = new HttpHead(url);
                break;
            default:
                throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method");
            }

            //Set the body for eligible methods
            if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) {
                ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody()));
            }

            //Set headers
            if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) {
                for (String strHeader : restEvent.getHeaders()) {
                    CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1);
                    headerBuffer.append(strHeader);
                    request.addHeader(new BufferedHeader(headerBuffer));
                }
            }

            HttpResponse response = client.execute(request);
            responseCode = response.getStatusLine().getStatusCode();

            result.setState(RestClientCallState.OK);
        } catch (ConnectTimeoutException e) {
            result.setState(RestClientCallState.TIMEOUT);
        } catch (Exception e) {
            throw new RestEventApiRuntimeException("Un error occured while processing rest event", e);
        } finally {
            result.setResponseCode(responseCode);

            try {
                client.close();
            } catch (Exception e2) {
                logger.warn("Unable to close HTTP client", e2);
            }
        }

        return result;
    }

}