39ad7b4542ec3ae715557698cfd581adb4c67b8f
[appc.git] / appc-event-listener / appc-event-listener-bundle / src / main / java / org / onap / appc / listener / LCM / operation / ProviderOperations.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.listener.LCM.operation;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.JsonNode;
29 import java.io.IOException;
30 import java.io.UnsupportedEncodingException;
31 import java.net.MalformedURLException;
32 import java.net.Socket;
33 import java.net.URL;
34 import java.security.KeyManagementException;
35 import java.security.KeyStore;
36 import java.security.KeyStoreException;
37 import java.security.NoSuchAlgorithmException;
38 import java.security.UnrecoverableKeyException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import javax.net.ssl.SSLContext;
42 import javax.net.ssl.TrustManager;
43 import javax.net.ssl.X509TrustManager;
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.commons.io.IOUtils;
46 import org.apache.http.HttpHeaders;
47 import org.apache.http.HttpResponse;
48 import org.apache.http.HttpVersion;
49 import org.apache.http.client.HttpClient;
50 import org.apache.http.client.methods.HttpPost;
51 import org.apache.http.conn.ClientConnectionManager;
52 import org.apache.http.conn.scheme.PlainSocketFactory;
53 import org.apache.http.conn.scheme.Scheme;
54 import org.apache.http.conn.scheme.SchemeRegistry;
55 import org.apache.http.conn.ssl.SSLSocketFactory;
56 import org.apache.http.entity.StringEntity;
57 import org.apache.http.impl.client.DefaultHttpClient;
58 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
59 import org.apache.http.params.BasicHttpParams;
60 import org.apache.http.params.HttpParams;
61 import org.apache.http.params.HttpProtocolParams;
62 import org.apache.http.protocol.HTTP;
63 import org.onap.appc.exceptions.APPCException;
64 import org.onap.appc.listener.LCM.model.ResponseStatus;
65 import org.onap.appc.listener.util.Mapper;
66
67 public class ProviderOperations {
68
69     private final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
70
71     private URL url;
72     private String basicAuth;
73
74     private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
75
76
77     public ProviderOperations(String url, String username, String password){
78         setAuthentication(username, password);
79         try {
80             this.url = new URL(url);
81         } catch (MalformedURLException e) {
82             LOG.error("An error occurred while building url", e);
83         }
84     }
85
86     /**
87      * Calls the AppcProvider to run a topology directed graph
88      *
89      * @param message The incoming message to be run
90      * @return True if the result is success. Never returns false and throws an exception instead.
91      * @throws UnsupportedEncodingException
92      * @throws Exception                    if there was a failure processing the request. The exception message is the failure reason.
93      */
94     @SuppressWarnings("nls")
95     public JsonNode topologyDG(String rpcName, JsonNode message) throws APPCException {
96         if (message == null) {
97             throw new APPCException("Provided message was null");
98         }
99
100         HttpPost postRequest = buildPostRequest(rpcName, message);
101         return getJsonNode(message, postRequest);
102     }
103
104     private HttpPost buildPostRequest(String rpcName, JsonNode message) throws APPCException {
105         HttpPost post;
106         try {
107
108             // Concatenate the "action" on the end of the URL
109             String path = requestFormatter.buildPath(url, rpcName);
110             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
111
112             post = new HttpPost(serviceUrl.toExternalForm());
113             post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
114             post.setHeader(HttpHeaders.ACCEPT, "application/json");
115
116             // Set Auth
117             if (basicAuth != null) {
118                 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth);
119             }
120
121             String body = Mapper.toJsonString(message);
122             StringEntity entity = new StringEntity(body);
123             entity.setContentType("application/json");
124             post.setEntity(entity);
125         } catch (UnsupportedEncodingException | MalformedURLException e) {
126             throw new APPCException(e);
127         }
128         return post;
129     }
130
131     private JsonNode getJsonNode(JsonNode message, HttpPost post) throws APPCException {
132         HttpClient client = getHttpClient();
133
134         int httpCode;
135         String respBody;
136         try {
137             HttpResponse response = client.execute(post);
138             httpCode = response.getStatusLine().getStatusCode();
139             respBody = IOUtils.toString(response.getEntity().getContent());
140         } catch (IOException e) {
141             throw new APPCException(e);
142         }
143
144         if (httpCode >= 200 && httpCode < 300 && respBody != null) {
145             JsonNode json;
146             try {
147                 json = Mapper.toJsonNodeFromJsonString(respBody);
148             } catch (Exception e) {
149                 LOG.error("Error processing response from provider. Could not map response to json", e);
150                 throw new APPCException("APPC has an unknown RPC error");
151             }
152             ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
153             if (!isSucceeded(responseStatus.getCode())) {
154                 LOG.warn(String.format("Operation failed [%s]", message.toString()));
155             }
156             return json;
157         }
158         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
159     }
160
161     /**
162      * Updates the static var URL and returns the value;
163      *
164      * @return The new value of URL
165      */
166     public String getUrl() {
167         return url.toExternalForm();
168     }
169
170     public void setUrl(String newUrl) {
171         try {
172             url = new URL(newUrl);
173         } catch (MalformedURLException e) {
174             LOG.error("An error occurred while building url", e);
175         }
176     }
177
178     /**
179      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
180      * to null
181      *
182      * @param user     The user with optional domain name
183      * @param password The password for the user
184      * @return The new value of the basic auth string that will be used in the request headers
185      */
186     public String setAuthentication(String user, String password) {
187         if (user != null && password != null) {
188             String authStr = user + ":" + password;
189             basicAuth = new String(Base64.encodeBase64(authStr.getBytes()));
190         } else {
191             basicAuth = null;
192         }
193         return basicAuth;
194     }
195
196     @SuppressWarnings("deprecation")
197     private HttpClient getHttpClient() throws APPCException {
198         HttpClient client;
199         switch (url.getProtocol()) {
200             case "https":
201                 try {
202                     KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
203                     trustStore.load(null, null);
204                     MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
205                     sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
206
207                     HttpParams params = new BasicHttpParams();
208                     HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
209                     HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
210
211                     SchemeRegistry registry = new SchemeRegistry();
212                     registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
213                     registry.register(new Scheme("https", sf, 443));
214                     registry.register(new Scheme("https", sf, 8443));
215                     registry.register(new Scheme("http", sf, 8181));
216
217                     ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
218                     client = new DefaultHttpClient(ccm, params);
219                 } catch (Exception e) {
220                     client = new DefaultHttpClient();
221                 }
222                 break;
223             case "http":
224                 client = new DefaultHttpClient();
225                 break;
226             default:
227                 throw new APPCException(
228                     "The provider.topology.url property is invalid. The url did not start with http[s]");
229         }
230         return client;
231     }
232
233     @SuppressWarnings("deprecation")
234     public static class MySSLSocketFactory extends SSLSocketFactory {
235         private SSLContext sslContext = SSLContext.getInstance("TLS");
236
237         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
238             KeyStoreException, UnrecoverableKeyException {
239             super(truststore);
240
241             TrustManager tm = new X509TrustManager() {
242                 @Override
243                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
244                 }
245
246                 @Override
247                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
248                 }
249
250                 @Override
251                 public X509Certificate[] getAcceptedIssuers() {
252                     return null;
253                 }
254             };
255
256             sslContext.init(null, new TrustManager[]{
257                 tm
258             }, null);
259         }
260
261         @Override
262         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
263             throws IOException {
264             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
265         }
266
267         @Override
268         public Socket createSocket() throws IOException {
269             return sslContext.getSocketFactory().createSocket();
270         }
271     }
272
273     public static boolean isSucceeded(Integer code) {
274
275         //FIXME is it working as intended?
276         return code != null && ((code == 100) || (code == 400));
277     }
278 }