e84a85a0c4aca6ee1463c0c5ba8511aa0558b9f5
[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.onap.appc.adapter.ansible.impl;
26
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;
39
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;
49
50 import java.io.FileInputStream;
51 import java.io.IOException;
52
53
54 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
55 import org.apache.http.conn.ssl.SSLContexts;
56 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
57
58
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;
62
63
64 /** 
65      * Returns custom http client 
66      - based on options
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
70      
71 **/
72
73
74 public class ConnectionBuilder {
75
76
77
78     private   CloseableHttpClient http_client = null;
79     private HttpClientContext http_context  = new HttpClientContext();
80
81
82
83
84     // Various constructors depending on how we want to instantiate the http ConnectionBuilder instance
85
86
87     /**
88      * Constructor that initializes an http client based on certificate
89      **/
90     public ConnectionBuilder(String CertFile) throws KeyStoreException, CertificateException, IOException, KeyManagementException, NoSuchAlgorithmException, APPCException{
91         
92         
93         /* Point to the certificate */
94         FileInputStream fs = new FileInputStream(CertFile);
95         
96         /* Generate a certificate from the X509 */
97         CertificateFactory cf = CertificateFactory.getInstance("X.509");
98         X509Certificate cert = (X509Certificate)cf.generateCertificate(fs);
99         
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);
104         
105         
106         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
107         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
108         
109         http_client  = HttpClients.custom().setSSLSocketFactory(factory).build();
110     };
111
112
113     /**
114      * Constructor which trusts all certificates in a specific java keystore file (assumes a JKS file)
115      **/
116     public ConnectionBuilder(String trustStoreFile, char[] trustStorePasswd) throws KeyStoreException, IOException, KeyManagementException, NoSuchAlgorithmException, CertificateException {
117         
118         
119         /* Load the specified trustStore */
120         KeyStore keystore = KeyStore.getInstance("JKS");
121         FileInputStream readStream = new FileInputStream(trustStoreFile);
122         keystore.load(readStream,trustStorePasswd);
123         
124         SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keystore).build();
125         SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
126         
127         http_client  = HttpClients.custom().setSSLSocketFactory(factory).build();
128     };
129
130     /**
131      * Constructor that trusts ALL SSl certificates  (NOTE : ONLY FOR DEV TESTING) if Mode == 1
132      or Default if Mode == 0
133     */
134     public ConnectionBuilder(int Mode) throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException{
135         if (Mode == 1){
136             SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,  new TrustSelfSignedStrategy()).build();
137             SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
138             
139             http_client = HttpClients.custom().setSSLSocketFactory(factory).build();                
140         }
141
142         else{
143             http_client = HttpClients.createDefault();
144         }
145         
146     };
147
148    
149     // Use to create an http context with auth headers
150     public  void  setHttpContext(String User, String MyPassword){
151         
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);
159         }
160
161         
162     };
163
164
165     // Method posts to the ansible server and writes out response to 
166     // Ansible result object 
167     public AnsibleResult Post(String AgentUrl, String Payload){
168
169         AnsibleResult result = new AnsibleResult();
170         try{
171             
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");
176             
177             HttpResponse response = http_client.execute(postObj, http_context);
178             
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);
184         }
185         
186         catch(IOException io){
187             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
188             result.setStatusMessage(io.getMessage());
189         }
190         
191         
192
193         return result;
194
195     }
196     
197     // Method gets information from an Ansible server and writes out response to
198     // Ansible result object
199
200     public AnsibleResult Get(String AgentUrl){
201
202         AnsibleResult result = new AnsibleResult();
203
204         try{
205             HttpGet getObj = new HttpGet(AgentUrl );
206             HttpResponse response =  http_client.execute(getObj, http_context);
207             
208             
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);
214
215         }
216         catch(IOException io){
217             result.setStatusCode(AnsibleResultCodes.IO_EXCEPTION.getValue());
218             result.setStatusMessage(io.getMessage());
219         }
220         
221         return result;
222     };
223
224 }