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