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