Applying license changes to all files
[appc.git] / appc-adapters / appc-ansible-adapter / appc-ansible-adapter-bundle / src / main / java / org / openecomp / appc / adapter / 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  * 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.adapter.ansible.impl;
26
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;
41
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;
52
53 import java.io.FileInputStream;
54 import java.io.IOException;
55
56
57 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
58 import org.apache.http.conn.ssl.SSLContexts;
59 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
60
61
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;
65
66
67 /** 
68      * Returns custom http client 
69      - based on options
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
73      
74 **/
75
76
77 public class ConnectionBuilder {
78
79
80
81     private   CloseableHttpClient http_client = null;
82     private HttpClientContext http_context  = new HttpClientContext();
83
84
85
86
87     // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance
88
89
90     /**
91      * Constructor that initializes an http client based on certificate
92      **/
93     public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{
94         
95         
96         /* Point to the certificate */
97         FileInputStream fs = new FileInputStream(CertFile);
98         
99         /* Generate a certificate from the X509 */
100         CertificateFactory cf = CertificateFactory.getInstance("X.509");
101         X509Certificate cert = (X509Certificate)cf.generateCertificate(fs);
102         
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);
107         
108         
109         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
110         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
111         
112         http_client  = HttpClients.custom().setSSLSocketFactory(factory).build();
113     };
114
115
116     /**
117      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file)
118      **/
119     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException {
120         
121         
122         /* Load the specified trustStore */
123         KeyStore keystore = KeyStore.getInstance("JKS");
124         FileInputStream readStream = new FileInputStream(trustStoreFile);
125         keystore.load(readStream,trustStorePasswd);
126         
127         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
128         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
129         
130         http_client  = HttpClients.custom().setSSLSocketFactory(factory).build();
131     };
132
133     /**
134      * Constructor that trusts ALL SSl certificates  (NOTE : ONLY FOR DEV TESTING) if Mode == 1
135      or Default if Mode == 0
136     */
137     public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{
138         if (Mode == 1){
139             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,  new TrustSelfSignedStrategy()).build();
140             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
141             
142             http_client = HttpClients.custom().setSSLSocketFactory(factory).build();                
143         }
144
145         else{
146             http_client = HttpClients.createDefault();
147         }
148         
149     };
150
151    
152     // Use to create an http context with auth headers
153     public  void  setHttpContext(String User, String MyPassword){
154         
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);
162         }
163
164         
165     };
166
167
168     // Method posts to the ansible server and writes out response to 
169     // Ansible result object 
170     public AnsibleResult Post(String AgentUrl, String Payload){
171
172         AnsibleResult result = new AnsibleResult();
173         try{
174             
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");
179             
180             HttpResponse response = http_client.execute(postObj, http_context);
181             
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);
187         }
188         
189         catch(IOException io){
190             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
191             result.setStatusMessage(io.getMessage());
192         }
193         
194         
195
196         return result;
197
198     }
199     
200     // Method gets information from an Ansible server and writes out response to
201     // Ansible result object
202
203     public AnsibleResult Get(String AgentUrl){
204
205         AnsibleResult result = new AnsibleResult();
206
207         try{
208             HttpGet getObj = new HttpGet(AgentUrl );
209             HttpResponse response =  http_client.execute(getObj, http_context);
210             
211             
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);
217
218         }
219         catch(IOException io){
220             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
221             result.setStatusMessage(io.getMessage());
222         }
223         
224         return result;
225     };
226
227 }