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.onap.appc.adapter.ansible.impl;
27 import org.apache.http.HttpEntity;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.methods.HttpGet;
30 import org.apache.http.client.methods.HttpPost;
31 import org.apache.http.client.protocol.HttpClientContext;
32 import org.apache.http.impl.client.CloseableHttpClient;
33 import org.apache.http.impl.client.BasicCredentialsProvider;
34 import org.apache.http.impl.client.HttpClients;
35 import org.apache.http.util.EntityUtils;
36 import org.apache.http.auth.UsernamePasswordCredentials;
37 import org.apache.http.auth.AuthScope;
38 import org.apache.http.entity.StringEntity;
40 import java.security.KeyStore;
41 import java.security.KeyStoreException;
42 import java.security.cert.CertificateException;
43 import java.security.KeyManagementException;
44 import java.security.cert.CertificateFactory;
45 import java.security.cert.X509Certificate;
46 import java.security.NoSuchAlgorithmException;
47 import javax.net.ssl.SSLException;
48 import javax.net.ssl.SSLContext;
50 import java.io.FileInputStream;
51 import java.io.IOException;
54 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
55 import org.apache.http.conn.ssl.SSLContexts;
56 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
59 import org.onap.appc.exceptions.APPCException;
60 import org.onap.appc.adapter.ansible.model.AnsibleResult;
61 import org.onap.appc.adapter.ansible.model.AnsibleResultCodes;
65 * Returns custom http client
67 - can create one with ssl using an X509 certificate that does NOT have a known CA
68 - create one which trusts ALL SSL certificates
69 - return default httpclient (which only trusts known CAs from default cacerts file for process) -- this is the default option
74 public class ConnectionBuilder {
78 private CloseableHttpClient http_client = null;
79 private HttpClientContext http_context = new HttpClientContext();
84 // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance
88 * Constructor that initializes an http client based on certificate
90 public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{
93 /* Point to the certificate */
94 FileInputStream fs = new FileInputStream(CertFile);
96 /* Generate a certificate from the X509 */
97 CertificateFactory cf = CertificateFactory.getInstance("X.509");
98 X509Certificate cert = (X509Certificate)cf.generateCertificate(fs);
100 /* Create a keystore object and load the certificate there */
101 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
102 keystore.load(null, null);
103 keystore.setCertificateEntry("cacert", cert);
106 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
107 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
109 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
114 * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file)
116 public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException {
119 /* Load the specified trustStore */
120 KeyStore keystore = KeyStore.getInstance("JKS");
121 FileInputStream readStream = new FileInputStream(trustStoreFile);
122 keystore.load(readStream,trustStorePasswd);
124 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
125 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
127 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
131 * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1
132 or Default if Mode == 0
134 public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{
136 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
137 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
139 http_client = HttpClients.custom().setSSLSocketFactory(factory).build();
143 http_client = HttpClients.createDefault();
149 // Use to create an http context with auth headers
150 public void setHttpContext(String User, String MyPassword){
152 // Are credential provided ? If so, set the context to be used
153 if (User != null && ! User.isEmpty() && MyPassword != null && ! MyPassword.isEmpty()){
154 UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(User, MyPassword);
155 AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
156 BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
157 credsprovider.setCredentials(authscope, credentials);
158 http_context.setCredentialsProvider(credsprovider);
165 // Method posts to the ansible server and writes out response to
166 // Ansible result object
167 public AnsibleResult Post(String AgentUrl, String Payload){
169 AnsibleResult result = new AnsibleResult();
172 HttpPost postObj = new HttpPost(AgentUrl);
173 StringEntity bodyParams = new StringEntity(Payload, "UTF-8");
174 postObj.setEntity(bodyParams);
175 postObj.addHeader("Content-type", "application/json");
177 HttpResponse response = http_client.execute(postObj, http_context);
179 HttpEntity entity = response.getEntity();
180 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
181 int responseCode = response.getStatusLine().getStatusCode();
182 result.setStatusCode(responseCode);
183 result.setStatusMessage(responseOutput);
186 catch(IOException io){
187 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
188 result.setStatusMessage(io.getMessage());
197 // Method gets information from an Ansible server and writes out response to
198 // Ansible result object
200 public AnsibleResult Get(String AgentUrl){
202 AnsibleResult result = new AnsibleResult();
205 HttpGet getObj = new HttpGet(AgentUrl );
206 HttpResponse response = http_client.execute(getObj, http_context);
209 HttpEntity entity = response.getEntity();
210 String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
211 int responseCode = response.getStatusLine().getStatusCode();
212 result.setStatusCode(responseCode);
213 result.setStatusMessage(responseOutput);
216 catch(IOException io){
217 result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
218 result.setStatusMessage(io.getMessage());