e13117bbaa0c4e941c3195e1e1234b944c7a4c03
[dcaegen2/analytics/tca.git] / dcae-analytics-aai / src / main / java / org / onap / dcae / apod / analytics / aai / service / AAIHttpClientImpl.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
4  * ================================================================================
5  *    Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *   You may obtain a copy of the License at
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *  ============================LICENSE_END===========================================
19  */
20
21 package org.onap.dcae.apod.analytics.aai.service;
22
23 import com.google.inject.Inject;
24 import com.google.inject.assistedinject.Assisted;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.http.HttpHeaders;
28 import org.apache.http.HttpHost;
29 import org.apache.http.auth.AuthScope;
30 import org.apache.http.auth.Credentials;
31 import org.apache.http.auth.UsernamePasswordCredentials;
32 import org.apache.http.client.CredentialsProvider;
33 import org.apache.http.conn.ssl.NoopHostnameVerifier;
34 import org.apache.http.impl.client.BasicCredentialsProvider;
35 import org.apache.http.impl.client.CloseableHttpClient;
36 import org.apache.http.impl.client.HttpClientBuilder;
37 import org.apache.http.impl.client.HttpClients;
38 import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
39 import org.apache.http.message.BasicHeader;
40 import org.apache.http.ssl.SSLContextBuilder;
41 import org.onap.dcae.apod.analytics.aai.domain.config.AAIHttpClientConfig;
42 import org.onap.dcae.apod.analytics.aai.utils.ssl.AlwaysTrustingTrustStrategy;
43 import org.onap.dcae.apod.analytics.common.exception.DCAEAnalyticsRuntimeException;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import java.net.URL;
48 import java.nio.charset.Charset;
49 import java.security.KeyManagementException;
50 import java.security.KeyStoreException;
51 import java.security.NoSuchAlgorithmException;
52 import java.util.Arrays;
53
54 /**
55  * <p>
56  * A concrete implementation of {@link AAIHttpClient} which provides Apache {@link CloseableHttpClient} for
57  * making rest calls to A&AI Enrichment API.
58  * </p>
59  *
60  * @author Rajiv Singla . Creation Date: 9/19/2017.
61  */
62 public class AAIHttpClientImpl implements AAIHttpClient {
63
64     private static final Logger LOG = LoggerFactory.getLogger(AAIHttpClientImpl.class);
65
66     private final AAIHttpClientConfig aaiHttpClientConfig;
67
68     @Inject
69     public AAIHttpClientImpl(@Assisted final AAIHttpClientConfig aaiHttpClientConfig) {
70         this.aaiHttpClientConfig = aaiHttpClientConfig;
71     }
72
73     /**
74      * Provides an instance of {@link CloseableHttpClient} used to make REST calls to A&AI Enrichment API
75      *
76      * @return An instance of Closeable HTTP Client used to make A&AI API Rest calls
77      */
78     @Override
79     public CloseableHttpClient getAAIHttpClient() {
80
81         final HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();
82         final boolean aaiIgnoreSSLCertificateErrors = aaiHttpClientConfig.isAaiIgnoreSSLCertificateErrors();
83
84         // Setup SSL Context to ignore SSL certificate issues if ignoreSSLCertificateErrors is true
85         LOG.info("SSL Certificate Errors attributed is set to : {}", aaiIgnoreSSLCertificateErrors);
86
87         if (aaiIgnoreSSLCertificateErrors) {
88             LOG.warn("SSL Certificate Errors will be ignored for this A&AI Http Client Instance");
89             try {
90                 SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
91                 sslContextBuilder.loadTrustMaterial(null, new AlwaysTrustingTrustStrategy());
92                 httpClientBuilder.setSSLContext(sslContextBuilder.build());
93             } catch (NoSuchAlgorithmException e) {
94                 final String errorMessage = "NoSuchAlgorithmException while setting SSL Context for AAI HTTP Client.";
95                 throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
96             } catch (KeyStoreException e) {
97                 final String errorMessage = "KeyStoreException while setting SSL Context for AAI HTTP Client.";
98                 throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
99             } catch (KeyManagementException e) {
100                 final String errorMessage = "KeyManagementException while setting SSL Context for AAI HTTP Client.";
101                 throw new DCAEAnalyticsRuntimeException(errorMessage, LOG, e);
102             }
103
104             httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
105
106         } else {
107             LOG.info("SSL Certification Errors will be enforced for A&AI Http Client instance");
108         }
109
110         // Setup credentials and proxy
111         final String aaiUserName = aaiHttpClientConfig.getAaiUserName();
112
113         final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
114
115         if (aaiUserName != null) {
116             // add basic authentication header
117             LOG.info("Setting A&AI authentication headers with username: {}", aaiUserName);
118             final String aaiUserPassword = aaiHttpClientConfig.getAaiUserPassword();
119             final String auth = aaiUserName + ":" + aaiUserPassword;
120             final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
121             final String authHeader = "Basic " + new String(encodedAuth);
122             final BasicHeader basicAuthHeader = new BasicHeader(HttpHeaders.AUTHORIZATION, authHeader);
123             httpClientBuilder.setDefaultHeaders(Arrays.asList(basicAuthHeader));
124         } else {
125             LOG.warn("A&AI userName not present. No credentials set for A&AI authentication");
126         }
127
128         final URL aaiProxyURL = aaiHttpClientConfig.getAaiProxyURL();
129
130         if (aaiProxyURL != null) {
131             final String aaiProxyHost = aaiProxyURL.getHost();
132             final Integer aaiProxyPortNumber = aaiProxyURL.getPort();
133             final String aaiProxyProtocol = aaiProxyURL.getProtocol();
134             final HttpHost proxy = new HttpHost(aaiProxyHost, aaiProxyPortNumber, aaiProxyProtocol);
135             LOG.info("Setting A&AI Http Client default proxy as: {}", proxy);
136             final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
137             httpClientBuilder.setRoutePlanner(routePlanner);
138
139             final String userInfo = aaiProxyURL.getUserInfo();
140             if (StringUtils.isNotBlank(userInfo)) {
141                 final String[] userInfoArray = userInfo.split(":");
142                 final String aaiProxyUsername = userInfoArray[0];
143                 String aaiProxyPassword = null;
144                 if (userInfoArray.length > 1) {
145                     aaiProxyPassword = userInfoArray[1];
146                 }
147                 LOG.info("Setting A&AI Http Client proxy credentials with username: {}", aaiProxyUsername);
148                 final AuthScope aaiProxyAuthScope = new AuthScope(aaiProxyHost, aaiProxyPortNumber);
149                 final Credentials aaiProxyCredentials = new UsernamePasswordCredentials(aaiProxyUsername,
150                         aaiProxyPassword);
151                 credentialsProvider.setCredentials(aaiProxyAuthScope, aaiProxyCredentials);
152             } else {
153                 LOG.debug("NO A&AI Proxy Username present.Bypassing setting up A&AI Proxy authentication credentials");
154             }
155         } else {
156             LOG.debug("A&AI proxy not Enabled - bypassing setting A&AI Proxy settings");
157         }
158
159         // setup credentials provider
160         httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
161
162         return httpClientBuilder.build();
163     }
164
165 }