summaryrefslogtreecommitdiffstats
path: root/vespa-athenz/src/main/java/com/yahoo/vespa/athenz/client/common/ClientBase.java
blob: 7ff9db327d3fb581d18c5544a8274da421beb1b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.client.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.yahoo.vespa.athenz.client.common.bindings.ErrorResponseEntity;
import com.yahoo.vespa.athenz.identity.ServiceIdentitySslSocketFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.eclipse.jetty.http.HttpStatus;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.util.function.Supplier;

/**
 * @author bjorncs
 */
public abstract class ClientBase implements AutoCloseable {

    private static final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());

    private final CloseableHttpClient client;
    private final ClientExceptionFactory exceptionFactory;

    protected ClientBase(String userAgent,
                         Supplier<SSLContext> sslContextSupplier,
                         ClientExceptionFactory exceptionFactory) {
        this.exceptionFactory = exceptionFactory;
        this.client = createHttpClient(userAgent, sslContextSupplier);
    }

    protected  <T> T execute(HttpUriRequest request, ResponseHandler<T> responseHandler) {
        try {
            return client.execute(request, responseHandler);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    protected StringEntity toJsonStringEntity(Object entity) {
        try {
            return new StringEntity(objectMapper.writeValueAsString(entity), ContentType.APPLICATION_JSON);
        } catch (JsonProcessingException e) {
            throw new UncheckedIOException(e);
        }
    }

    protected <T> T readEntity(HttpResponse response, Class<T> entityType) throws IOException {
        if (HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) {
            if (entityType.equals(Void.class)) {
                return null;
            } else {
                return objectMapper.readValue(response.getEntity().getContent(), entityType);
            }
        } else {
            ErrorResponseEntity errorEntity = objectMapper.readValue(response.getEntity().getContent(), ErrorResponseEntity.class);
            throw exceptionFactory.createException(errorEntity.code, errorEntity.description);
        }
    }

    private static CloseableHttpClient createHttpClient(String userAgent, Supplier<SSLContext> sslContextSupplier) {
        return HttpClientBuilder.create()
                .setRetryHandler(new DefaultHttpRequestRetryHandler(3, /*requestSentRetryEnabled*/true))
                .setUserAgent(userAgent)
                .setSSLSocketFactory(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(sslContextSupplier), (HostnameVerifier)null))
                .setDefaultRequestConfig(RequestConfig.custom()
                                                 .setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
                                                 .setConnectionRequestTimeout((int)Duration.ofSeconds(10).toMillis())
                                                 .setSocketTimeout((int)Duration.ofSeconds(20).toMillis())
                                                 .build())
                .build();
    }

    @Override
    public void close()  {
        try {
            this.client.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    protected interface ClientExceptionFactory {
        RuntimeException createException(int errorCode, String description);
    }
}