Newer
Older
fedex-api / src / main / java / io / ljunggren / fedex / api / service / BaseService.java
package io.ljunggren.fedex.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.ljunggren.fedex.api.model.ApiResponse;
import io.ljunggren.fedex.api.model.CodeMessage;
import io.ljunggren.fedex.api.model.Debug;
import io.ljunggren.fedex.api.model.HttpStatusCode;
import io.ljunggren.json.utils.JsonUtils;

public class BaseService {

    protected static final int CONNECT_TIMEOUT_MS = 5000;
    protected static final int SOCKET_TIMEOUT_MS = 15000;

    protected String domain;

    protected BaseService(String domain) {
        this.domain = domain;
    }

    // Response codes for which FedEx returns a structured JSON body matching the response DTO.
    protected static final List<Integer> KNOWN_CODES = List.of(200, 400, 401, 403, 422, 429, 500, 503);

    protected CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD)
                        .setConnectTimeout(CONNECT_TIMEOUT_MS)
                        .setConnectionRequestTimeout(CONNECT_TIMEOUT_MS)
                        .setSocketTimeout(SOCKET_TIMEOUT_MS)
                        .build())
                .build();
    }

    protected Header[] generateHeaders(String accessToken) {
        return new Header[] {
                new BasicHeader("content-type", "application/json"),
                new BasicHeader("x-locale", "en_US"),
                new BasicHeader("authorization", String.format("Bearer %s", accessToken))
        };
    }

    protected <T extends ApiResponse<T>> T post(String uri, Object requestBody, String accessToken,
            CloseableHttpClient httpClient, Class<T> responseClass, Supplier<T> errorResponseSupplier,
            String exceptionErrorCode) throws Exception {
        try {
            HttpPost post = new HttpPost(uri);
            post.setHeaders(generateHeaders(accessToken));
            post.setEntity(new StringEntity(JsonUtils.objectToJson(requestBody)));
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                int responseCode = response.getStatusLine().getStatusCode();
                String json = getResult(response);
                return createResponse(json, responseCode, responseClass, errorResponseSupplier).setResponseCode(responseCode);
            }
        } catch (Exception e) {
            return errorResponseSupplier.get().addError(new CodeMessage(exceptionErrorCode, e.getMessage()));
        } finally {
            httpClient.close();
        }
    }

    private <T extends ApiResponse<T>> T createResponse(String json, int responseCode, Class<T> responseClass,
            Supplier<T> errorResponseSupplier) throws Exception {
        if (KNOWN_CODES.contains(responseCode)) {
            return parse(json, responseClass);
        }
        return errorResponseSupplier.get().addError(new CodeMessage(HttpStatusCode.getTextByCode(responseCode), json));
    }

    protected static Debug debug(HttpRequestBase httpRequest, CloseableHttpClient httpClient) throws IOException {
        return debug(httpRequest, httpClient, new Debug());
    }

    protected static Debug debug(HttpRequestBase httpRequest, CloseableHttpClient httpClient, Debug debug) throws IOException {
        try {
            try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
                debug.setMethod(httpRequest.getMethod());
                debug.setUrl(httpRequest.getURI().toString());
                debug.setResponseCode(response.getStatusLine().getStatusCode());
                debug.setResponse(getResult(response));
            }
        } catch (Exception e) {
            debug.setResponse(e.getMessage());
        } finally {
            httpClient.close();
        }
        return debug;
    }

    protected static String getResult(HttpResponse response) throws UnsupportedOperationException, IOException {
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }

    protected <T> T parse(String json, Class<T> clazz) throws Exception {
        try {
            return JsonUtils.jsonToObject(json, clazz);
        } catch (JsonProcessingException e) {
            throw new Exception("Unable to parse response", e);
        }
    }

}