9bd5d57f7713bb7cdc84fac235af40fe1509a5df
[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 String dmaapHostName;
61     private final Integer dmaapPortNumber;
62     private final String dmaapProtocol;
63     private final String user;
64     private final String pwd;
65
66     /**
67      * Constructor DmaapProducerReactiveHttpClient.
68      *
69      * @param dmaapPublisherConfiguration - DMaaP producer configuration object
70      */
71     public DmaapProducerReactiveHttpClient(DmaapPublisherConfiguration dmaapPublisherConfiguration) {
72         this.dmaapHostName = dmaapPublisherConfiguration.dmaapHostName();
73         this.dmaapPortNumber = dmaapPublisherConfiguration.dmaapPortNumber();
74         this.dmaapProtocol = dmaapPublisherConfiguration.dmaapProtocol();
75         this.user = dmaapPublisherConfiguration.dmaapUserName();
76         this.pwd = dmaapPublisherConfiguration.dmaapUserPassword();
77     }
78
79     public HttpResponse getDmaapProducerResponseWithRedirect(HttpUriRequest request, Map<String, String> contextMap)
80             throws DatafileTaskException {
81         try (CloseableHttpAsyncClient webClient = createWebClient(true, NO_REQUEST_TIMEOUT)) {
82             MdcVariables.setMdcContextMap(contextMap);
83             webClient.start();
84
85             logger.trace(INVOKE, "Starting to produce to DR {}", request);
86             Future<HttpResponse> future = webClient.execute(request, null);
87             HttpResponse response = future.get();
88             logger.trace(INVOKE_RETURN, "Response from DR {}", response.toString());
89             return response;
90         } catch (Exception e) {
91             throw new DatafileTaskException("Unable to create web client.", e);
92         }
93     }
94
95     public HttpResponse getDmaapProducerResponseWithCustomTimeout(HttpUriRequest request, int requestTimeout,
96             Map<String, String> contextMap) throws DatafileTaskException {
97         try (CloseableHttpAsyncClient webClient = createWebClient(false, requestTimeout)) {
98             MdcVariables.setMdcContextMap(contextMap);
99             webClient.start();
100
101             logger.trace(INVOKE, "Starting to produce to DR {}", request);
102             Future<HttpResponse> future = webClient.execute(request, null);
103             HttpResponse response = future.get();
104             logger.trace(INVOKE_RETURN, "Response from DR {}", response.toString());
105             return response;
106         } catch (Exception e) {
107             throw new DatafileTaskException("Unable to create web client.", e);
108         }
109     }
110
111     public void addUserCredentialsToHead(HttpUriRequest request) {
112         String plainCreds = user + ":" + pwd;
113         byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1);
114         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
115         String base64Creds = new String(base64CredsBytes);
116         logger.trace("base64Creds...: {}", base64Creds);
117         request.addHeader("Authorization", "Basic " + base64Creds);
118     }
119
120     public UriBuilder getBaseUri() {
121         return new DefaultUriBuilderFactory().builder() //
122                 .scheme(dmaapProtocol) //
123                 .host(dmaapHostName) //
124                 .port(dmaapPortNumber);
125     }
126
127     private CloseableHttpAsyncClient createWebClient(boolean expectRedirect, int requestTimeout)
128             throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
129         SSLContext sslContext =
130                 new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
131
132         IHttpAsyncClientBuilder clientBuilder = getHttpClientBuilder();
133         clientBuilder.setSSLContext(sslContext) //
134                 .setSSLHostnameVerifier(new NoopHostnameVerifier());
135
136         if (expectRedirect) {
137             clientBuilder.setRedirectStrategy(PublishRedirectStrategy.INSTANCE);
138         }
139
140         if (requestTimeout > NO_REQUEST_TIMEOUT) {
141             RequestConfig requestConfig = RequestConfig.custom() //
142                     .setSocketTimeout(requestTimeout) //
143                     .setConnectTimeout(requestTimeout) //
144                     .setConnectionRequestTimeout(requestTimeout) //
145                     .build();
146
147             clientBuilder.setDefaultRequestConfig(requestConfig);
148         }
149
150         return clientBuilder.build();
151     }
152
153     IHttpAsyncClientBuilder getHttpClientBuilder() {
154         return new HttpAsyncClientBuilderWrapper();
155     }
156 }