aboutsummaryrefslogtreecommitdiffstats
path: root/datafile-dmaap-client/src/main/java/org/onap/dcaegen2/collectors/datafile/service/producer/DmaapProducerHttpClient.java
blob: b0904b29563a94ab8743cd3f41434272cdaa03a7 (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
 * ============LICENSE_START======================================================================
 * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
 * ===============================================================================================
 * 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.
 * ============LICENSE_END========================================================================
 */

package org.onap.dcaegen2.collectors.datafile.service.producer;

import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.Future;

import javax.net.ssl.SSLContext;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.ssl.SSLContextBuilder;
import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
import org.onap.dcaegen2.collectors.datafile.http.HttpAsyncClientBuilderWrapper;
import org.onap.dcaegen2.collectors.datafile.http.IHttpAsyncClientBuilder;
import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy;
import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriBuilder;

/**
 * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
 * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
 */
public class DmaapProducerHttpClient {

    private static final Duration DEFAULT_REQUEST_TIMEOUT = Duration.ofMinutes(2);
    private static final Marker INVOKE = MarkerFactory.getMarker("INVOKE");
    private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE_RETURN");

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final DmaapPublisherConfiguration configuration;

    /**
     * Constructor DmaapProducerReactiveHttpClient.
     *
     * @param dmaapPublisherConfiguration - DMaaP producer configuration object
     */
    public DmaapProducerHttpClient(DmaapPublisherConfiguration dmaapPublisherConfiguration) {
        this.configuration = dmaapPublisherConfiguration;
    }

    public HttpResponse getDmaapProducerResponseWithRedirect(HttpUriRequest request, Map<String, String> contextMap)
            throws DatafileTaskException {
        MDC.setContextMap(contextMap);
        try (CloseableHttpAsyncClient webClient = createWebClient(true, DEFAULT_REQUEST_TIMEOUT)) {
            webClient.start();

            logger.trace(INVOKE, "Starting to produce to DR {}", request);
            Future<HttpResponse> future = webClient.execute(request, null);
            HttpResponse response = future.get();
            logger.trace(INVOKE_RETURN, "Response from DR {}", response);
            return response;
        } catch (Exception e) {
            throw new DatafileTaskException("Unable to create web client.", e);
        }
    }

    public HttpResponse getDmaapProducerResponseWithCustomTimeout(HttpUriRequest request, Duration requestTimeout,
            Map<String, String> contextMap) throws DatafileTaskException {
        MDC.setContextMap(contextMap);
        try (CloseableHttpAsyncClient webClient = createWebClient(false, requestTimeout)) {
            webClient.start();

            logger.trace(INVOKE, "Starting to produce to DR {}", request);
            Future<HttpResponse> future = webClient.execute(request, null);
            HttpResponse response = future.get();
            logger.trace(INVOKE_RETURN, "Response from DR {}", response);
            return response;
        } catch (Exception e) {
            throw new DatafileTaskException("Unable to create web client.", e);
        }
    }

    public void addUserCredentialsToHead(HttpUriRequest request) {
        String plainCreds = configuration.dmaapUserName() + ":" + configuration.dmaapUserPassword();
        byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        logger.trace("base64Creds...: {}", base64Creds);
        request.addHeader("Authorization", "Basic " + base64Creds);
    }

    public UriBuilder getBaseUri() {
        return new DefaultUriBuilderFactory().builder() //
                .scheme(configuration.dmaapProtocol()) //
                .host(configuration.dmaapHostName()) //
                .port(configuration.dmaapPortNumber());
    }

    private CloseableHttpAsyncClient createWebClient(boolean expectRedirect, Duration requestTimeout)
            throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        SSLContext sslContext =
                new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        IHttpAsyncClientBuilder clientBuilder = getHttpClientBuilder();
        clientBuilder.setSSLContext(sslContext) //
                .setSSLHostnameVerifier(new NoopHostnameVerifier());

        if (expectRedirect) {
            clientBuilder.setRedirectStrategy(PublishRedirectStrategy.INSTANCE);
        }

        if (requestTimeout.toMillis() > 0) {
            int millis = (int)requestTimeout.toMillis();
            RequestConfig requestConfig = RequestConfig.custom() //
                    .setSocketTimeout(millis) //
                    .setConnectTimeout(millis) //
                    .setConnectionRequestTimeout(millis) //
                    .build();

            clientBuilder.setDefaultRequestConfig(requestConfig);
        } else {
            logger.error("WEB client without timeout created {}", requestTimeout);
        }

        return clientBuilder.build();
    }

    IHttpAsyncClientBuilder getHttpClientBuilder() {
        return new HttpAsyncClientBuilderWrapper();
    }
}