Update missing License Headers
[appc.git] / appc-adapters / appc-ansible-adapter / appc-ansible-adapter-bundle / src / main / java / org / onap / appc / adapter / ansible / impl / ConnectionBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.ansible.impl;
25
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;
57
58 /**
59  * Returns a custom http client
60  * - based on options
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
64  * option
65  **/
66
67 public class ConnectionBuilder {
68
69     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConnectionBuilder.class);
70
71     private CloseableHttpClient httpClient = null;
72     private HttpClientContext httpContext = new HttpClientContext();
73
74     /**
75      * Constructor that initializes an http client based on certificate
76      **/
77     public ConnectionBuilder(String certFile) throws KeyStoreException, CertificateException, IOException,
78             KeyManagementException, NoSuchAlgorithmException, APPCException {
79
80         /* Point to the certificate */
81         FileInputStream fs = new FileInputStream(certFile);
82
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      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS
101      * file)
102      **/
103     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException,
104             KeyManagementException, NoSuchAlgorithmException, CertificateException {
105
106         /* Load the specified trustStore */
107         KeyStore keystore = KeyStore.getInstance("JKS");
108         FileInputStream readStream = new FileInputStream(trustStoreFile);
109         keystore.load(readStream, trustStorePasswd);
110
111         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
112         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
113                 SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
114
115         httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
116     }
117
118     /**
119      * Constructor that trusts ALL SSl certificates (NOTE : ONLY FOR DEV TESTING) if Mode == 1 or
120      * Default if Mode == 0
121      */
122     public ConnectionBuilder(int mode)
123             throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
124         if (mode == 1) {
125             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
126             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
127                     SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
128
129             httpClient = HttpClients.custom().setSSLSocketFactory(factory).build();
130         } else {
131             httpClient = HttpClients.createDefault();
132         }
133     }
134
135     // Use to create an http context with auth headers
136     public void setHttpContext(String user, String myPassword) {
137
138         // Are credential provided ? If so, set the context to be used
139         if (user != null && !user.isEmpty() && myPassword != null && !myPassword.isEmpty()) {
140             UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, myPassword);
141             AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
142             BasicCredentialsProvider credsprovider = new BasicCredentialsProvider();
143             credsprovider.setCredentials(authscope, credentials);
144             httpContext.setCredentialsProvider(credsprovider);
145         }
146     }
147
148     // Method posts to the ansible server and writes out response to
149     // Ansible result object
150     public AnsibleResult post(String agentUrl, String payload) {
151
152         AnsibleResult result = new AnsibleResult();
153         try {
154
155             HttpPost postObj = new HttpPost(agentUrl);
156             StringEntity bodyParams = new StringEntity(payload, "UTF-8");
157             postObj.setEntity(bodyParams);
158             postObj.addHeader("Content-type", "application/json");
159
160             HttpResponse response = httpClient.execute(postObj, httpContext);
161
162             HttpEntity entity = response.getEntity();
163             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
164             int responseCode = response.getStatusLine().getStatusCode();
165             result.setStatusCode(responseCode);
166             result.setStatusMessage(responseOutput);
167         } catch (IOException io) {
168             logger.error("Caught IOException", io);
169             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
170             result.setStatusMessage(io.getMessage());
171         }
172         return result;
173     }
174
175     // Method gets information from an Ansible server and writes out response to
176     // Ansible result object
177
178     public AnsibleResult get(String agentUrl) {
179
180         AnsibleResult result = new AnsibleResult();
181
182         try {
183             HttpGet getObj = new HttpGet(agentUrl);
184             HttpResponse response = httpClient.execute(getObj, httpContext);
185
186             HttpEntity entity = response.getEntity();
187             String responseOutput = entity != null ? EntityUtils.toString(entity) : null;
188             int responseCode = response.getStatusLine().getStatusCode();
189             result.setStatusCode(responseCode);
190             result.setStatusMessage(responseOutput);
191         } catch (IOException io) {
192             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
193             result.setStatusMessage(io.getMessage());
194             logger.error("Caught IOException", io);
195         }
196         return result;
197     }
198 }