2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.openecomp.appc.adapter.ansible.impl;
27 import org.apache.http.HttpEntity;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.ClientProtocolException;
30 import org.apache.http.client.ResponseHandler;
31 import org.apache.http.client.methods.HttpGet;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.client.protocol.HttpClientContext;
34 import org.apache.http.impl.client.CloseableHttpClient;
35 import org.apache.http.impl.client.BasicCredentialsProvider;
36 import org.apache.http.impl.client.HttpClients;
37 import org.apache.http.util.EntityUtils;
38 import org.apache.http.auth.UsernamePasswordCredentials;
39 import org.apache.http.auth.AuthScope;
40 import org.apache.http.entity.StringEntity;
42 import java.security.KeyStore;
43 import java.security.KeyStoreException;
44 import java.security.cert.CertificateException;
45 import java.security.KeyManagementException;
46 import java.security.cert.CertificateFactory;
47 import java.security.cert.X509Certificate;
48 import java.security.NoSuchAlgorithmException;
49 import javax.net.ssl.SSLException;
50 import javax.net.ssl.SSLContext;
51 import javax.net.ssl.X509TrustManager;
53 import java.io.FileInputStream;
54 import java.io.IOException;
57 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
58 import org.apache.http.conn.ssl.SSLContexts;
59 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
62 import org.openecomp.appc.exceptions.APPCException;
63 import org.openecomp.appc.adapter.ansible.model.AnsibleResult;
64 import org.openecomp.appc.adapter.ansible.model.AnsibleResultCodes;
68 * Returns custom http client
70 - can create one with ssl using an X509 certificate that does NOT have a known CA
71 - create one which trusts ALL SSL certificates
72 - return default httpclient (which only trusts known CAs from default cacerts file for process) -- this is the default option
77 public class ConnectionBuilder {
81 private CloseableHttpClient http_client = null;
82 private HttpClientContext http_context = new HttpClientContext();
87 // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance
91 * Constructor that initializes an http client based on certificate
93 public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{
96 /* Point to the certificate */
97 FileInputStream fs = new FileInputStream(CertFile);
99 /* Generate a certificate from the X509 */
100 CertificateFactory cf = CertificateFactory.getInstance("X.509");
101 X509Certificate cert = (X509Certificate)cf.generateCertificate(fs);
103 /* Create a keystore object and load the certificate there */
104 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
105 keystore.load(null, null);
106 keystore.setCertificateEntry("cacert", cert);
109 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
110 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
112 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
117 * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file)
119 public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException {
122 /* Load the specified trustStore */
123 KeyStore keystore = KeyStore.getInstance("JKS");
124 FileInputStream readStream = new FileInputStream(trustStoreFile);
125 keystore.load(readStream,trustStorePasswd);
127 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
128 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
130 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
134 * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1
135 or Default if Mode == 0
137 public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{
139 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
140 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
142 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
146 http_client = HttpClients.createDefault();
152 // Use to create an http context with auth headers
153 public void setHttpContext(String User, String MyPassword){
155 // Are credential provided ? If so, set the context to be used
156 if (User != null && ! User.isEmpty() && MyPassword != null && ! MyPassword.isEmpty()){
157 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(User, MyPassword);
158 AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
159 BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
160 credsprovider.setCredentials(authscope, credentials);
161 http_context.setCredentialsProvider(credsprovider);
168 // Method posts to the ansible server and writes out response to
169 // Ansible result object
170 public AnsibleResult Post(String AgentUrl, String Payload){
172 AnsibleResult result = new AnsibleResult();
175 HttpPost postObj = new HttpPost(AgentUrl);
176 StringEntity bodyParams = new StringEntity(Payload, "UTF-8");
177 postObj.setEntity(bodyParams);
178 postObj.addHeader("Content-type", "application/json");
180 HttpResponse response = http_client.execute(postObj, http_context);
182 HttpEntity entity = response.getEntity();
183 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
184 int responseCode = response.getStatusLine().getStatusCode();
185 result.setStatusCode(responseCode);
186 result.setStatusMessage(responseOutput);
189 catch(IOException io){
190 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
191 result.setStatusMessage(io.getMessage());
200 // Method gets information from an Ansible server and writes out response to
201 // Ansible result object
203 public AnsibleResult Get(String AgentUrl){
205 AnsibleResult result = new AnsibleResult();
208 HttpGet getObj = new HttpGet(AgentUrl );
209 HttpResponse response = http_client.execute(getObj, http_context);
212 HttpEntity entity = response.getEntity();
213 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
214 int responseCode = response.getStatusLine().getStatusCode();
215 result.setStatusCode(responseCode);
216 result.setStatusMessage(responseOutput);
219 catch(IOException io){
220 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
221 result.setStatusMessage(io.getMessage());