Change nexus values to properties
[appc.git] / appc-event-listener / appc-event-listener-bundle / src / main / java / org / openecomp / appc / listener / LCM / operation / ProviderOperations.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.listener.LCM.operation;
23
24 import com.fasterxml.jackson.databind.JsonNode;
25 import org.apache.commons.codec.binary.Base64;
26 import org.apache.commons.io.IOUtils;
27 import org.apache.http.HttpHeaders;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.HttpVersion;
30 import org.apache.http.client.HttpClient;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.conn.ClientConnectionManager;
33 import org.apache.http.conn.scheme.PlainSocketFactory;
34 import org.apache.http.conn.scheme.Scheme;
35 import org.apache.http.conn.scheme.SchemeRegistry;
36 import org.apache.http.conn.ssl.SSLSocketFactory;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.DefaultHttpClient;
39 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
40 import org.apache.http.params.BasicHttpParams;
41 import org.apache.http.params.HttpParams;
42 import org.apache.http.params.HttpProtocolParams;
43 import org.apache.http.protocol.HTTP;
44 import org.openecomp.appc.exceptions.APPCException;
45 import org.openecomp.appc.listener.LCM.model.ResponseStatus;
46 import org.openecomp.appc.listener.util.Mapper;
47
48 import com.att.eelf.configuration.EELFLogger;
49 import com.att.eelf.configuration.EELFManager;
50
51 import javax.net.ssl.SSLContext;
52 import javax.net.ssl.TrustManager;
53 import javax.net.ssl.X509TrustManager;
54 import java.io.IOException;
55 import java.io.UnsupportedEncodingException;
56 import java.net.MalformedURLException;
57 import java.net.Socket;
58 import java.net.URL;
59 import java.net.UnknownHostException;
60 import java.security.*;
61 import java.security.cert.CertificateException;
62 import java.security.cert.X509Certificate;
63
64 public class ProviderOperations {
65
66     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
67
68     private static URL url;
69     private static String basic_auth;
70
71     private static ProviderOperationRequestFormatter requestFormatter = new GenericProviderOperationRequestFormatter();
72
73     /**
74      * Calls the AppcProvider to run a topology directed graph
75      *
76      * @param msg The incoming message to be run
77      * @return True if the result is success. Never returns false and throws an exception instead.
78      * @throws UnsupportedEncodingException
79      * @throws Exception                    if there was a failure processing the request. The exception message is the failure reason.
80      */
81     @SuppressWarnings("nls")
82     public static JsonNode topologyDG(String rpcName, JsonNode msg) throws APPCException {
83         if (msg == null) {
84             throw new APPCException("Provided message was null");
85         }
86
87         HttpPost post = null;
88         try {
89
90             // Concatenate the "action" on the end of the URL
91             String path = requestFormatter.buildPath(url, rpcName);
92             URL serviceUrl = new URL(url.getProtocol(), url.getHost(), url.getPort(), path);
93
94             post = new HttpPost(serviceUrl.toExternalForm());
95             post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
96             post.setHeader(HttpHeaders.ACCEPT, "application/json");
97
98             // Set Auth
99             if (basic_auth != null) {
100                 post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + basic_auth);
101             }
102
103             String body = Mapper.toJsonString(msg);
104             StringEntity entity = new StringEntity(body);
105             entity.setContentType("application/json");
106             post.setEntity(new StringEntity(body));
107         } catch (UnsupportedEncodingException | MalformedURLException e) {
108             throw new APPCException(e);
109         }
110
111         HttpClient client = getHttpClient();
112
113         int httpCode = 0;
114         String respBody = null;
115         try {
116             HttpResponse response = client.execute(post);
117             httpCode = response.getStatusLine().getStatusCode();
118             respBody = IOUtils.toString(response.getEntity().getContent());
119         } catch (IOException e) {
120             throw new APPCException(e);
121         }
122
123         if (httpCode >= 200 && httpCode < 300 && respBody != null) {
124             JsonNode json;
125             try {
126                 json = Mapper.toJsonNodeFromJsonString(respBody);
127             } catch (Exception e) {
128                 LOG.error("Error processing response from provider. Could not map response to json", e);
129                 throw new APPCException("APPC has an unknown RPC error");
130             }
131
132             ResponseStatus responseStatus = requestFormatter.getResponseStatus(json);
133
134             if (!isSucceeded(responseStatus.getCode())) {
135                 LOG.warn(String.format("Operation failed [%s]", msg.toString()));
136             }
137
138             return json;
139         }
140
141         throw new APPCException(String.format("Unexpected response from endpoint: [%d] - %s ", httpCode, respBody));
142     }
143
144     /**
145      * Updates the static var URL and returns the value;
146      *
147      * @return The new value of URL
148      */
149     public static String getUrl() {
150         return url.toExternalForm();
151     }
152
153     public static void setUrl(String newUrl) {
154         try {
155             url = new URL(newUrl);
156         } catch (MalformedURLException e) {
157             e.printStackTrace();
158         }
159     }
160
161     /**
162      * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
163      * to null
164      *
165      * @param user     The user with optional domain name
166      * @param password The password for the user
167      * @return The new value of the basic auth string that will be used in the request headers
168      */
169     public static String setAuthentication(String user, String password) {
170         if (user != null && password != null) {
171             String authStr = user + ":" + password;
172             basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
173         } else {
174             basic_auth = null;
175         }
176         return basic_auth;
177     }
178
179     @SuppressWarnings("deprecation")
180     private static HttpClient getHttpClient() throws APPCException {
181         HttpClient client;
182         if (url.getProtocol().equals("https")) {
183             try {
184                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
185                 trustStore.load(null, null);
186                 MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
187                 sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
188
189                 HttpParams params = new BasicHttpParams();
190                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
191                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
192
193                 SchemeRegistry registry = new SchemeRegistry();
194                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
195                 registry.register(new Scheme("https", sf, 443));
196                 registry.register(new Scheme("https", sf, 8443));
197                 registry.register(new Scheme("http", sf, 8181));
198
199                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
200                 client = new DefaultHttpClient(ccm, params);
201             } catch (Exception e) {
202                 client = new DefaultHttpClient();
203             }
204         } else if (url.getProtocol().equals("http")) {
205             client = new DefaultHttpClient();
206         } else {
207             throw new APPCException(
208                     "The provider.topology.url property is invalid. The url did not start with http[s]");
209         }
210         return client;
211     }
212
213     @SuppressWarnings("deprecation")
214     public static class MySSLSocketFactory extends SSLSocketFactory {
215         private SSLContext sslContext = SSLContext.getInstance("TLS");
216
217         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
218                 KeyStoreException, UnrecoverableKeyException {
219             super(truststore);
220
221             TrustManager tm = new X509TrustManager() {
222                 @Override
223                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
224                 }
225
226                 @Override
227                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
228                 }
229
230                 @Override
231                 public X509Certificate[] getAcceptedIssuers() {
232                     return null;
233                 }
234             };
235
236             sslContext.init(null, new TrustManager[]{
237                     tm
238             }, null);
239         }
240
241         @Override
242         public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
243                 throws IOException, UnknownHostException {
244             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
245         }
246
247         @Override
248         public Socket createSocket() throws IOException {
249             return sslContext.getSocketFactory().createSocket();
250         }
251     }
252
253     public static boolean isSucceeded(Integer code) {
254         if (code == null) {
255             return false;
256         }
257         return ((code == 100) || (code == 400)); // only 100 & 400 statuses are success
258     }
259
260 }