944d3b3495aca5a746f8c77052b31ddab052ac56
[dcaegen2/collectors/datafile.git] /
1 /*
2  * ============LICENSE_START======================================================================
3  * Copyright (C) 2018 NOKIA Intellectual Property, 2018-2019 Nordix Foundation. All rights reserved.
4  * ===============================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
6  * in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  * ============LICENSE_END========================================================================
15  */
16
17 package org.onap.dcaegen2.collectors.datafile.service.producer;
18
19 import java.nio.charset.StandardCharsets;
20 import java.security.KeyManagementException;
21 import java.security.KeyStoreException;
22 import java.security.NoSuchAlgorithmException;
23 import java.util.Map;
24 import java.util.concurrent.Future;
25
26 import javax.net.ssl.SSLContext;
27
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.client.config.RequestConfig;
31 import org.apache.http.client.methods.HttpUriRequest;
32 import org.apache.http.conn.ssl.NoopHostnameVerifier;
33 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
34 import org.apache.http.ssl.SSLContextBuilder;
35 import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException;
36 import org.onap.dcaegen2.collectors.datafile.http.HttpAsyncClientBuilderWrapper;
37 import org.onap.dcaegen2.collectors.datafile.http.IHttpAsyncClientBuilder;
38 import org.onap.dcaegen2.collectors.datafile.model.logging.MdcVariables;
39 import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy;
40 import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.slf4j.Marker;
44 import org.slf4j.MarkerFactory;
45 import org.springframework.web.util.DefaultUriBuilderFactory;
46 import org.springframework.web.util.UriBuilder;
47
48 /**
49  * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18
50  * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a>
51  */
52 public class DmaapProducerReactiveHttpClient {
53
54     private static final int NO_REQUEST_TIMEOUT = -1;
55     private static final Marker INVOKE = MarkerFactory.getMarker("INVOKE");
56     private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE_RETURN");
57
58     private final Logger logger = LoggerFactory.getLogger(this.getClass());
59
60     private final DmaapPublisherConfiguration configuration;
61
62     /**
63      * Constructor DmaapProducerReactiveHttpClient.
64      *
65      * @param dmaapPublisherConfiguration - DMaaP producer configuration object
66      */
67     public DmaapProducerReactiveHttpClient(DmaapPublisherConfiguration dmaapPublisherConfiguration) {
68         this.configuration = dmaapPublisherConfiguration;
69     }
70
71     public HttpResponse getDmaapProducerResponseWithRedirect(HttpUriRequest request, Map<String, String> contextMap)
72             throws DatafileTaskException {
73         try (CloseableHttpAsyncClient webClient = createWebClient(true, NO_REQUEST_TIMEOUT)) {
74             MdcVariables.setMdcContextMap(contextMap);
75             webClient.start();
76
77             logger.trace(INVOKE, "Starting to produce to DR {}", request);
78             Future<HttpResponse> future = webClient.execute(request, null);
79             HttpResponse response = future.get();
80             logger.trace(INVOKE_RETURN, "Response from DR {}", response);
81             return response;
82         } catch (Exception e) {
83             throw new DatafileTaskException("Unable to create web client.", e);
84         }
85     }
86
87     public HttpResponse getDmaapProducerResponseWithCustomTimeout(HttpUriRequest request, int requestTimeout,
88             Map<String, String> contextMap) throws DatafileTaskException {
89         try (CloseableHttpAsyncClient webClient = createWebClient(false, requestTimeout)) {
90             MdcVariables.setMdcContextMap(contextMap);
91             webClient.start();
92
93             logger.trace(INVOKE, "Starting to produce to DR {}", request);
94             Future<HttpResponse> future = webClient.execute(request, null);
95             HttpResponse response = future.get();
96             logger.trace(INVOKE_RETURN, "Response from DR {}", response);
97             return response;
98         } catch (Exception e) {
99             throw new DatafileTaskException("Unable to create web client.", e);
100         }
101     }
102
103     public void addUserCredentialsToHead(HttpUriRequest request) {
104         String plainCreds = configuration.dmaapUserName() + ":" + configuration.dmaapUserPassword();
105         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
106         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
107         String base64Creds = new String(base64CredsBytes);
108         logger.trace("base64Creds...: {}", base64Creds);
109         request.addHeader("Authorization", "Basic " + base64Creds);
110     }
111
112     public UriBuilder getBaseUri() {
113         return new DefaultUriBuilderFactory().builder() //
114                 .scheme(configuration.dmaapProtocol()) //
115                 .host(configuration.dmaapHostName()) //
116                 .port(configuration.dmaapPortNumber());
117     }
118
119     private CloseableHttpAsyncClient createWebClient(boolean expectRedirect, int requestTimeout)
120             throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
121         SSLContext sslContext =
122                 new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
123
124         IHttpAsyncClientBuilder clientBuilder = getHttpClientBuilder();
125         clientBuilder.setSSLContext(sslContext) //
126                 .setSSLHostnameVerifier(new NoopHostnameVerifier());
127
128         if (expectRedirect) {
129             clientBuilder.setRedirectStrategy(PublishRedirectStrategy.INSTANCE);
130         }
131
132         if (requestTimeout > NO_REQUEST_TIMEOUT) {
133             RequestConfig requestConfig = RequestConfig.custom() //
134                     .setSocketTimeout(requestTimeout) //
135                     .setConnectTimeout(requestTimeout) //
136                     .setConnectionRequestTimeout(requestTimeout) //
137                     .build();
138
139             clientBuilder.setDefaultRequestConfig(requestConfig);
140         }
141
142         return clientBuilder.build();
143     }
144
145     IHttpAsyncClientBuilder getHttpClientBuilder() {
146         return new HttpAsyncClientBuilderWrapper();
147     }
148 }