6295a255791350f466c6c67d1fdf743bc8b315fe
[ccsdk/sli/adaptors.git] / ansible-adapter / ansible-adapter-bundle / src / main / java / org / onap / ccsdk / sli / adaptors / ansible / impl / ConnectionBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
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.
22  *
23  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24  * ============LICENSE_END=========================================================
25  */
26
27 package org.onap.ccsdk.sli.adaptors.ansible.impl;
28
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 com.att.eelf.configuration.EELFLogger;
57 import com.att.eelf.configuration.EELFManager;
58
59 /**
60  * Returns a custom http client
61  * - based on options
62  * - can create one with ssl using an X509 certificate that does NOT have a known CA
63  * - create one which trusts ALL SSL certificates
64  * - return default httpclient (which only trusts known CAs from default cacerts file for process) this is the default
65  * option
66  **/
67
68 public class ConnectionBuilder {
69
70     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
71
72     private CloseableHttpClient httpClient = null;
73     private HttpClientContext httpContext = new HttpClientContext();
74
75     /**
76      * Constructor that initializes an http client based on certificate
77      **/
78     public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException,
79             KeyManagementException, NoSuchAlgorithmException {
80
81         /* Point to the certificate */
82         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);
86
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);
91
92                 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
93                 SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
94                         SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
95
96                 httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
97         }
98     }
99
100     /**
101      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
102      * file)
103      **/
104     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
105             KeyManagementException, NoSuchAlgorithmException, CertificateException {
106
107         /* Load the specified trustStore */
108         KeyStore keystore = KeyStore.getInstance("JKS");
109         FileInputStream readStream = new FileInputStream(trustStoreFile);
110         keystore.load(readStream, trustStorePasswd);
111
112         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
113         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
114                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
115
116         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
117     }
118
119     /**
120      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
121      * Default if Mode == 0
122      */
123     public ConnectionBuilder(int mode)
124             throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
125         if (mode == 1) {
126             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
127             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
128                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
129
130             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
131         } else {
132             httpClient = HttpClients.createDefault();
133         }
134     }
135
136     // Use to create an http context with auth headers
137     public void setHttpContext(String user, String myPassword) {
138
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);
146         }
147     }
148
149     // Method posts to the ansible server and writes out response to
150     // Ansible result object
151     public AnsibleResult post(String agentUrl, String payload) {
152
153         AnsibleResult result = new AnsibleResult();
154         try {
155
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");
160
161             HttpResponse response = httpClient.execute(postObj, httpContext);
162
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());
172         }
173         return result;
174     }
175
176     // Method gets information from an Ansible server and writes out response to
177     // Ansible result object
178
179     public AnsibleResult get(String agentUrl) {
180
181         AnsibleResult result = new AnsibleResult();
182
183         try {
184             HttpGet getObj = new HttpGet(agentUrl);
185             HttpResponse response = httpClient.execute(getObj, httpContext);
186
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);
196         }
197         return result;
198     }
199 }