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