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