2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * ================================================================================
9 * Modifications Copyright © 2018 IBM.
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 * ============LICENSE_END=========================================================
27 package org.onap.ccsdk.sli.adaptors.ansible.impl;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.security.KeyManagementException;
32 import java.security.KeyStore;
33 import java.security.KeyStoreException;
34 import java.security.NoSuchAlgorithmException;
35 import java.security.cert.CertificateException;
36 import java.security.cert.CertificateFactory;
37 import java.security.cert.X509Certificate;
38 import javax.net.ssl.SSLContext;
39 import org.apache.http.HttpEntity;
40 import org.apache.http.HttpResponse;
41 import org.apache.http.auth.AuthScope;
42 import org.apache.http.auth.UsernamePasswordCredentials;
43 import org.apache.http.client.methods.HttpGet;
44 import org.apache.http.client.methods.HttpPost;
45 import org.apache.http.client.protocol.HttpClientContext;
46 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
47 import org.apache.http.conn.ssl.SSLContexts;
48 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
49 import org.apache.http.entity.StringEntity;
50 import org.apache.http.impl.client.BasicCredentialsProvider;
51 import org.apache.http.impl.client.CloseableHttpClient;
52 import org.apache.http.impl.client.HttpClients;
53 import org.apache.http.util.EntityUtils;
54 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult;
55 import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes;
56 import org.onap.ccsdk.sli.core.utils.PathValidator;
58 import com.att.eelf.configuration.EELFLogger;
59 import com.att.eelf.configuration.EELFManager;
62 * Returns a custom http client
64 * - can create one with ssl using an X509 certificate that does NOT have a known CA
65 * - create one which trusts ALL SSL certificates
66 * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
70 public class ConnectionBuilder {
72 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
74 private CloseableHttpClient httpClient = null;
75 private HttpClientContext httpContext = new HttpClientContext();
78 * Constructor that initializes an http client based on certificate
80 public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException,
81 KeyManagementException, NoSuchAlgorithmException {
83 /* Point to the certificate */
84 try(FileInputStream fs = new FileInputStream(certFile)){
85 /* Generate a certificate from the X509 */
86 CertificateFactory cf = CertificateFactory.getInstance("X.509");
87 X509Certificate cert = (X509Certificate) cf.generateCertificate(fs);
89 /* Create a keystore object and load the certificate there */
90 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
91 keystore.load(null, null);
92 keystore.setCertificateEntry("cacert", cert);
94 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
95 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
96 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
98 httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
103 * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
106 public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
107 KeyManagementException, NoSuchAlgorithmException, CertificateException {
109 if (!PathValidator.isValidFilePath(trustStoreFile)) {
110 throw new IOException("Invalid trust store file path");
113 /* Load the specified trustStore */
114 KeyStore keystore = KeyStore.getInstance("JKS");
115 FileInputStream readStream = new FileInputStream(trustStoreFile);
116 keystore.load(readStream, trustStorePasswd);
118 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
119 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
120 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
122 httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
126 * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
127 * Default if Mode == 0
129 public ConnectionBuilder(int mode)
130 throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
132 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
133 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
134 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
136 httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
138 httpClient = HttpClients.createDefault();
142 // Use to create an http context with auth headers
143 public void setHttpContext(String user, String myPassword) {
145 // Are credential provided ? If so, set the context to be used
146 if (user != null && !user.isEmpty() && myPassword != null && !myPassword.isEmpty()) {
147 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, myPassword);
148 AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
149 BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
150 credsprovider.setCredentials(authscope, credentials);
151 httpContext.setCredentialsProvider(credsprovider);
155 // Method posts to the ansible server and writes out response to
156 // Ansible result object
157 public AnsibleResult post(String agentUrl, String payload) {
159 AnsibleResult result = new AnsibleResult();
162 HttpPost postObj = new HttpPost(agentUrl);
163 StringEntity bodyParams = new StringEntity(payload, "UTF-8");
164 postObj.setEntity(bodyParams);
165 postObj.addHeader("Content-type", "application/json");
167 HttpResponse response = httpClient.execute(postObj, httpContext);
169 HttpEntity entity = response.getEntity();
170 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
171 int responseCode = response.getStatusLine().getStatusCode();
172 result.setStatusCode(responseCode);
173 result.setStatusMessage(responseOutput);
174 } catch (IOException io) {
175 logger.error("Caught IOException", io);
176 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
177 result.setStatusMessage(io.getMessage());
182 // Method gets information from an Ansible server and writes out response to
183 // Ansible result object
185 public AnsibleResult get(String agentUrl) {
187 AnsibleResult result = new AnsibleResult();
190 HttpGet getObj = new HttpGet(agentUrl);
191 HttpResponse response = httpClient.execute(getObj, httpContext);
193 HttpEntity entity = response.getEntity();
194 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
195 int responseCode = response.getStatusLine().getStatusCode();
196 result.setStatusCode(responseCode);
197 result.setStatusMessage(responseOutput);
198 } catch (IOException io) {
199 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
200 result.setStatusMessage(io.getMessage());
201 logger.error("Caught IOException", io);