Add authorization header in SSE request
[ccsdk/sli/plugins.git] / restapi-call-node / provider / src / main / java / org / onap / ccsdk / sli / plugins / restapicall / RestapiCallNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-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.onap.ccsdk.sli.plugins.restapicall;
23
24 import static java.lang.Boolean.valueOf;
25 import static javax.ws.rs.client.Entity.entity;
26 import static org.onap.ccsdk.sli.plugins.restapicall.AuthType.fromString;
27
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.net.SocketException;
31 import java.net.URI;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.security.KeyStore;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Map.Entry;
42 import java.util.Properties;
43 import java.util.Set;
44 import javax.net.ssl.HttpsURLConnection;
45 import javax.net.ssl.KeyManagerFactory;
46 import javax.net.ssl.SSLContext;
47 import javax.ws.rs.ProcessingException;
48 import javax.ws.rs.client.Client;
49 import javax.ws.rs.client.ClientBuilder;
50 import javax.ws.rs.client.Entity;
51 import javax.ws.rs.client.Invocation;
52 import javax.ws.rs.client.WebTarget;
53 import javax.ws.rs.core.EntityTag;
54 import javax.ws.rs.core.Feature;
55 import javax.ws.rs.core.MultivaluedMap;
56 import javax.ws.rs.core.Response;
57 import javax.ws.rs.core.UriBuilder;
58 import org.apache.commons.lang3.StringUtils;
59 import org.glassfish.jersey.client.ClientProperties;
60 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
61 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
62 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
63 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
64 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
65 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public class RestapiCallNode implements SvcLogicJavaPlugin {
70
71     protected static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties";
72     protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
73     protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
74     protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
75
76     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
77     protected RetryPolicyStore retryPolicyStore;
78     private String uebServers;
79     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
80
81     public RestapiCallNode() {
82         String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
83
84         try (FileInputStream in = new FileInputStream(configDir + "/" + DME2_PROPERTIES_FILE_NAME)) {
85             Properties props = new Properties();
86             props.load(in);
87             this.retryPolicyStore = new RetryPolicyStore();
88             this.retryPolicyStore.setProxyServers(props.getProperty("proxyUrl"));
89             log.info("DME2 support enabled");
90         } catch (Exception e) {
91             log.warn("DME2 properties could not be read, DME2 support will not be enabled.", e);
92         }
93
94         try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
95             Properties props = new Properties();
96             props.load(in);
97             this.uebServers = props.getProperty("servers");
98             log.info("UEB support enabled");
99         } catch (Exception e) {
100             log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
101         }
102     }
103
104     /**
105      * Returns parameters from the parameter map.
106      *
107      * @param paramMap parameter map
108      * @param p        parameters instance
109      * @return parameters filed instance
110      * @throws SvcLogicException when svc logic exception occurs
111      */
112     public static Parameters getParameters(Map<String, String> paramMap,
113         Parameters p)
114         throws SvcLogicException {
115         p.templateFileName = parseParam(paramMap, "templateFileName",
116             false, null);
117         p.requestBody = parseParam(paramMap, "requestBody", false, null);
118         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
119         validateUrl(p.restapiUrl);
120         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
121         p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
122             null);
123         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey",
124             false, null);
125         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret",
126             false, null);
127         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod",
128             false, null);
129         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
130         p.contentType = parseParam(paramMap, "contentType", false, null);
131         p.format = Format.fromString(parseParam(paramMap, "format", false,
132             "json"));
133         p.authtype = fromString(parseParam(paramMap, "authType", false,
134             "unspecified"));
135         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
136             false, "post"));
137         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
138         p.listNameList = getListNameList(paramMap);
139         String skipSendingStr = paramMap.get("skipSending");
140         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
141         p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
142             false, "true"));
143         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName",
144             false, null);
145         p.trustStorePassword = parseParam(paramMap, "trustStorePassword",
146             false, null);
147         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName",
148             false, null);
149         p.keyStorePassword = parseParam(paramMap, "keyStorePassword",
150             false, null);
151         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null
152             && p.keyStoreFileName != null && p.keyStorePassword != null;
153         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders",
154             false, null);
155         p.partner = parseParam(paramMap, "partner", false, null);
156         p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders",
157             false, null));
158         p.returnRequestPayload = valueOf(parseParam(
159             paramMap, "returnRequestPayload", false, null));
160         return p;
161     }
162
163     /**
164      * Validates the given URL in the parameters.
165      *
166      * @param restapiUrl rest api URL
167      * @throws SvcLogicException when URL validation fails
168      */
169     private static void validateUrl(String restapiUrl)
170         throws SvcLogicException {
171         try {
172             URI.create(restapiUrl);
173         } catch (IllegalArgumentException e) {
174             throw new SvcLogicException("Invalid input of url "
175                 + e.getLocalizedMessage(), e);
176         }
177     }
178
179     /**
180      * Returns the list of list name.
181      *
182      * @param paramMap parameters map
183      * @return list of list name
184      */
185     private static Set<String> getListNameList(Map<String, String> paramMap) {
186         Set<String> ll = new HashSet<>();
187         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
188             if (entry.getKey().startsWith("listName")) {
189                 ll.add(entry.getValue());
190             }
191         }
192         return ll;
193     }
194
195     /**
196      * Parses the parameter string map of property, validates if required,
197      * assigns default value if present and returns the value.
198      *
199      * @param paramMap string param map
200      * @param name     name of the property
201      * @param required if value required
202      * @param def      default value
203      * @return value of the property
204      * @throws SvcLogicException if required parameter value is empty
205      */
206     public static String parseParam(Map<String, String> paramMap, String name,
207         boolean required, String def)
208         throws SvcLogicException {
209         String s = paramMap.get(name);
210
211         if (s == null || s.trim().length() == 0) {
212             if (!required) {
213                 return def;
214             }
215             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
216         }
217
218         s = s.trim();
219         StringBuilder value = new StringBuilder();
220         int i = 0;
221         int i1 = s.indexOf('%');
222         while (i1 >= 0) {
223             int i2 = s.indexOf('%', i1 + 1);
224             if (i2 < 0) {
225                 break;
226             }
227
228             String varName = s.substring(i1 + 1, i2);
229             String varValue = System.getenv(varName);
230             if (varValue == null) {
231                 varValue = "%" + varName + "%";
232             }
233
234             value.append(s.substring(i, i1));
235             value.append(varValue);
236
237             i = i2 + 1;
238             i1 = s.indexOf('%', i);
239         }
240         value.append(s.substring(i));
241
242         log.info("Parameter {}: [{}]", name, value);
243         return value.toString();
244     }
245
246     public RetryPolicyStore getRetryPolicyStore() {
247         return retryPolicyStore;
248     }
249
250     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
251         this.retryPolicyStore = retryPolicyStore;
252     }
253
254     /**
255      * Allows Directed Graphs  the ability to interact with REST APIs.
256      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
257      * <table border="1">
258      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
259      *  <tbody>
260      *      <tr><td>templateFileName</td><td>Optional</td><td>full path to template file that can be used to build a request</td><td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td></tr>
261      *      <tr><td>restapiUrl</td><td>Mandatory</td><td>url to send the request to</td><td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td></tr>
262      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
263      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
264      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
265      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
266      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
267      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
268      *      <tr><td>contentType</td><td>Optional</td><td>http content type to set in the http header</td><td>usually application/json or application/xml</td></tr>
269      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
270      *      <tr><td>httpMethod</td><td>Optional</td><td>http method to use when sending the request</td><td>get post put delete patch</td></tr>
271      *      <tr><td>responsePrefix</td><td>Optional</td><td>location the response will be written to in context memory</td><td>tmp.restapi.result</td></tr>
272      *      <tr><td>listName[i]</td><td>Optional</td><td>Used for processing XML responses with repeating elements.</td>vpn-information.vrf-details<td></td></tr>
273      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
274      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
275      *      <tr><td>customHttpHeaders</td><td>Optional</td><td>a list additional http headers to be passed in, follow the format in the example</td><td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td></tr>
276      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
277      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
278      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
279      *  </tbody>
280      * </table>
281      * @param ctx Reference to context memory
282      * @throws SvcLogicException
283      * @since 11.0.2
284      * @see String#split(String, int)
285      */
286     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
287         sendRequest(paramMap, ctx, null);
288     }
289
290     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
291         throws SvcLogicException {
292
293         RetryPolicy retryPolicy = null;
294         HttpResponse r = new HttpResponse();
295         try {
296             Parameters p = getParameters(paramMap, new Parameters());
297             if (p.partner != null) {
298                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
299             }
300             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
301
302             String req = null;
303             if (p.templateFileName != null) {
304                 String reqTemplate = readFile(p.templateFileName);
305                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
306             } else if (p.requestBody != null) {
307                 req = p.requestBody;
308             }
309             r = sendHttpRequest(req, p);
310             setResponseStatus(ctx, p.responsePrefix, r);
311
312             if (p.dumpHeaders && r.headers != null) {
313                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
314                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
315                 }
316             }
317
318             if (p.returnRequestPayload && req != null) {
319                 ctx.setAttribute(pp + "httpRequest", req);
320             }
321
322             if (r.body != null && r.body.trim().length() > 0) {
323                 ctx.setAttribute(pp + "httpResponse", r.body);
324
325                 if (p.convertResponse) {
326                     Map<String, String> mm = null;
327                     if (p.format == Format.XML) {
328                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
329                     } else if (p.format == Format.JSON) {
330                         mm = JsonParser.convertToProperties(r.body);
331                     }
332
333                     if (mm != null) {
334                         for (Map.Entry<String, String> entry : mm.entrySet()) {
335                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
336                         }
337                     }
338                 }
339             }
340         } catch (SvcLogicException e) {
341             boolean shouldRetry = false;
342             if (e.getCause().getCause() instanceof SocketException) {
343                 shouldRetry = true;
344             }
345
346             log.error("Error sending the request: " + e.getMessage(), e);
347             String prefix = parseParam(paramMap, "responsePrefix", false, null);
348             if (retryPolicy == null || shouldRetry == false) {
349                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
350             } else {
351                 if (retryCount == null) {
352                     retryCount = 0;
353                 }
354                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
355                     " maximum retries.";
356                 log.debug(retryMessage);
357                 try {
358                     retryCount = retryCount + 1;
359                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
360                         URI uri = new URI(paramMap.get("restapiUrl"));
361                         String hostname = uri.getHost();
362                         String retryString = retryPolicy.getNextHostName(uri.toString());
363                         URI uriTwo = new URI(retryString);
364                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
365                             uriTwo.getScheme()).build();
366                         paramMap.put("restapiUrl", retryUri.toString());
367                         log.debug("URL was set to {}", retryUri.toString());
368                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
369                             hostname, retryString);
370                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
371                         sendRequest(paramMap, ctx, retryCount);
372                     } else {
373                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
374                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
375                     }
376                 } catch (Exception ex) {
377                     log.error("Could not attempt retry.", ex);
378                     String retryErrorMessage =
379                         "Retry attempt has failed. No further retry shall be attempted, calling " +
380                             "setFailureResponseStatus.";
381                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
382                 }
383             }
384         }
385
386         if (r != null && r.code >= 300) {
387             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
388         }
389     }
390
391     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
392         throws SvcLogicException {
393         log.info("Building {} started", format);
394         long t1 = System.currentTimeMillis();
395         String originalTemplate = template;
396
397         template = expandRepeats(ctx, template, 1);
398
399         Map<String, String> mm = new HashMap<>();
400         for (String s : ctx.getAttributeKeySet()) {
401             mm.put(s, ctx.getAttribute(s));
402         }
403
404         StringBuilder ss = new StringBuilder();
405         int i = 0;
406         while (i < template.length()) {
407             int i1 = template.indexOf("${", i);
408             if (i1 < 0) {
409                 ss.append(template.substring(i));
410                 break;
411             }
412
413             int i2 = template.indexOf('}', i1 + 2);
414             if (i2 < 0) {
415                 throw new SvcLogicException("Template error: Matching } not found");
416             }
417
418             String var1 = template.substring(i1 + 2, i2);
419             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
420             // log.info(" " + var1 + ": " + value1);
421             if (value1 == null || value1.trim().length() == 0) {
422                 // delete the whole element (line)
423                 int i3 = template.lastIndexOf('\n', i1);
424                 if (i3 < 0) {
425                     i3 = 0;
426                 }
427                 int i4 = template.indexOf('\n', i1);
428                 if (i4 < 0) {
429                     i4 = template.length();
430                 }
431
432                 if (i < i3) {
433                     ss.append(template.substring(i, i3));
434                 }
435                 i = i4;
436             } else {
437                 ss.append(template.substring(i, i1)).append(value1);
438                 i = i2 + 1;
439             }
440         }
441
442         String req = format == Format.XML
443             ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
444
445         if (format == Format.JSON) {
446             req = XmlJsonUtil.removeLastCommaJson(req);
447         }
448
449         long t2 = System.currentTimeMillis();
450         log.info("Building {} completed. Time: {}", format, (t2 - t1));
451
452         return req;
453     }
454
455     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
456         StringBuilder newTemplate = new StringBuilder();
457         int k = 0;
458         while (k < template.length()) {
459             int i1 = template.indexOf("${repeat:", k);
460             if (i1 < 0) {
461                 newTemplate.append(template.substring(k));
462                 break;
463             }
464
465             int i2 = template.indexOf(':', i1 + 9);
466             if (i2 < 0) {
467                 throw new SvcLogicException(
468                     "Template error: Context variable name followed by : is required after repeat");
469             }
470
471             // Find the closing }, store in i3
472             int nn = 1;
473             int i3 = -1;
474             int i = i2;
475             while (nn > 0 && i < template.length()) {
476                 i3 = template.indexOf('}', i);
477                 if (i3 < 0) {
478                     throw new SvcLogicException("Template error: Matching } not found");
479                 }
480                 int i32 = template.indexOf('{', i);
481                 if (i32 >= 0 && i32 < i3) {
482                     nn++;
483                     i = i32 + 1;
484                 } else {
485                     nn--;
486                     i = i3 + 1;
487                 }
488             }
489
490             String var1 = template.substring(i1 + 9, i2);
491             String value1 = ctx.getAttribute(var1);
492             log.info("     {}:{}", var1, value1);
493             int n = 0;
494             try {
495                 n = Integer.parseInt(value1);
496             } catch (NumberFormatException e) {
497                 log.info("value1 not set or not a number, n will remain set at zero");
498             }
499
500             newTemplate.append(template.substring(k, i1));
501
502             String rpt = template.substring(i2 + 1, i3);
503
504             for (int ii = 0; ii < n; ii++) {
505                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
506                 if (ii == n - 1 && ss.trim().endsWith(",")) {
507                     int i4 = ss.lastIndexOf(',');
508                     if (i4 > 0) {
509                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
510                     }
511                 }
512                 newTemplate.append(ss);
513             }
514
515             k = i3 + 1;
516         }
517
518         if (k == 0) {
519             return newTemplate.toString();
520         }
521
522         return expandRepeats(ctx, newTemplate.toString(), level + 1);
523     }
524
525     protected String readFile(String fileName) throws SvcLogicException {
526         try {
527             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
528             return new String(encoded, "UTF-8");
529         } catch (IOException | SecurityException e) {
530             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
531         }
532     }
533
534     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
535         Parameters p = new Parameters();
536         p.restapiUser = fp.user;
537         p.restapiPassword = fp.password;
538         p.oAuthConsumerKey = fp.oAuthConsumerKey;
539         p.oAuthVersion = fp.oAuthVersion;
540         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
541         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
542         p.authtype = fp.authtype;
543         return addAuthType(c, p);
544     }
545
546     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
547         if (p.authtype == AuthType.Unspecified) {
548             if (p.restapiUser != null && p.restapiPassword != null) {
549                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
550             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
551                 && p.oAuthSignatureMethod != null) {
552                 Feature oAuth1Feature = OAuth1ClientSupport
553                     .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
554                     .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
555                 client.register(oAuth1Feature);
556             }
557         } else {
558             if (p.authtype == AuthType.DIGEST) {
559                 if (p.restapiUser != null && p.restapiPassword != null) {
560                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
561                 } else {
562                     throw new SvcLogicException(
563                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
564                             "parameters doesn't exist", new Throwable());
565                 }
566             } else if (p.authtype == AuthType.BASIC) {
567                 if (p.restapiUser != null && p.restapiPassword != null) {
568                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
569                 } else {
570                     throw new SvcLogicException(
571                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
572                             "parameters doesn't exist", new Throwable());
573                 }
574             } else if (p.authtype == AuthType.OAUTH) {
575                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
576                     Feature oAuth1Feature = OAuth1ClientSupport
577                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
578                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
579                     client.register(oAuth1Feature);
580                 } else {
581                     throw new SvcLogicException(
582                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
583                             "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
584                 }
585             }
586         }
587         return client;
588     }
589
590     /**
591      * Receives the http response for the http request sent.
592      *
593      * @param request request msg
594      * @param p       parameters
595      * @return HTTP response
596      * @throws SvcLogicException when sending http request fails
597      */
598     public HttpResponse sendHttpRequest(String request, Parameters p)
599         throws SvcLogicException {
600
601         SSLContext ssl = null;
602         if (p.ssl && p.restapiUrl.startsWith("https")) {
603             ssl = createSSLContext(p);
604         }
605         Client client;
606
607         if (ssl != null) {
608             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
609             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
610                 .build();
611         } else {
612             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
613                 .build();
614         }
615         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
616
617         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
618
619         log.info("Sending request:");
620         log.info(request);
621         long t1 = System.currentTimeMillis();
622
623         HttpResponse r = new HttpResponse();
624         r.code = 200;
625
626         if (!p.skipSending) {
627             String tt = p.format == Format.XML ? "application/xml" : "application/json";
628             String tt1 = tt + ";charset=UTF-8";
629             if (p.contentType != null) {
630                 tt = p.contentType;
631                 tt1 = p.contentType;
632             }
633
634             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
635
636             if (p.format == Format.NONE) {
637                 invocationBuilder.header("", "");
638             }
639
640             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
641                 String[] keyValuePairs = p.customHttpHeaders.split(",");
642                 for (String singlePair : keyValuePairs) {
643                     int equalPosition = singlePair.indexOf('=');
644                     invocationBuilder.header(singlePair.substring(0, equalPosition),
645                         singlePair.substring(equalPosition + 1, singlePair.length()));
646                 }
647             }
648
649             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
650
651             Response response;
652
653             try {
654                 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
655             } catch (ProcessingException | IllegalStateException e) {
656                 throw new SvcLogicException("Exception while posting http request to client " +
657                     e.getLocalizedMessage(), e);
658             }
659
660             r.code = response.getStatus();
661             r.headers = response.getStringHeaders();
662             EntityTag etag = response.getEntityTag();
663             if (etag != null) {
664                 r.message = etag.getValue();
665             }
666             if (response.hasEntity() && r.code != 204) {
667                 r.body = response.readEntity(String.class);
668             }
669         }
670
671         long t2 = System.currentTimeMillis();
672         log.info("Response received. Time: {}", (t2 - t1));
673         log.info("HTTP response code: {}", r.code);
674         log.info("HTTP response message: {}", r.message);
675         logHeaders(r.headers);
676         log.info("HTTP response: {}", r.body);
677
678         return r;
679     }
680
681     protected SSLContext createSSLContext(Parameters p) {
682         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
683             System.setProperty("jsse.enableSNIExtension", "false");
684             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
685             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
686
687             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
688
689             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
690             KeyStore ks = KeyStore.getInstance("PKCS12");
691             char[] pwd = p.keyStorePassword.toCharArray();
692             ks.load(in, pwd);
693             kmf.init(ks, pwd);
694
695             SSLContext ctx = SSLContext.getInstance("TLS");
696             ctx.init(kmf.getKeyManagers(), null, null);
697             return ctx;
698         } catch (Exception e) {
699             log.error("Error creating SSLContext: {}", e.getMessage(), e);
700         }
701         return null;
702     }
703
704     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
705         HttpResponse resp) {
706         resp.code = 500;
707         resp.message = errorMessage;
708         String pp = prefix != null ? prefix + '.' : "";
709         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
710         ctx.setAttribute(pp + "response-message", resp.message);
711     }
712
713     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
714         String pp = prefix != null ? prefix + '.' : "";
715         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
716         ctx.setAttribute(pp + "response-message", r.message);
717     }
718
719     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
720         HttpResponse r = null;
721         try {
722             FileParam p = getFileParameters(paramMap);
723             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
724
725             r = sendHttpData(data, p);
726             setResponseStatus(ctx, p.responsePrefix, r);
727
728         } catch (SvcLogicException | IOException e) {
729             log.error("Error sending the request: {}", e.getMessage(), e);
730
731             r = new HttpResponse();
732             r.code = 500;
733             r.message = e.getMessage();
734             String prefix = parseParam(paramMap, "responsePrefix", false, null);
735             setResponseStatus(ctx, prefix, r);
736         }
737
738         if (r != null && r.code >= 300) {
739             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
740         }
741     }
742
743     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
744         FileParam p = new FileParam();
745         p.fileName = parseParam(paramMap, "fileName", true, null);
746         p.url = parseParam(paramMap, "url", true, null);
747         p.user = parseParam(paramMap, "user", false, null);
748         p.password = parseParam(paramMap, "password", false, null);
749         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
750         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
751         String skipSendingStr = paramMap.get("skipSending");
752         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
753         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
754         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
755         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
756         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
757         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
758         return p;
759     }
760
761     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
762         HttpResponse r;
763         try {
764             UebParam p = getUebParameters(paramMap);
765
766             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
767
768             String req;
769
770             if (p.templateFileName == null) {
771                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
772                 p.templateFileName = defaultUebTemplateFileName;
773             }
774
775             String reqTemplate = readFile(p.templateFileName);
776             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
777             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
778
779             r = postOnUeb(req, p);
780             setResponseStatus(ctx, p.responsePrefix, r);
781             if (r.body != null) {
782                 ctx.setAttribute(pp + "httpResponse", r.body);
783             }
784
785         } catch (SvcLogicException e) {
786             log.error("Error sending the request: {}", e.getMessage(), e);
787
788             r = new HttpResponse();
789             r.code = 500;
790             r.message = e.getMessage();
791             String prefix = parseParam(paramMap, "responsePrefix", false, null);
792             setResponseStatus(ctx, prefix, r);
793         }
794
795         if (r.code >= 300) {
796             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
797         }
798     }
799
800     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
801
802         Client client = ClientBuilder.newBuilder().build();
803         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
804         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
805         WebTarget webTarget = addAuthType(client, p).target(p.url);
806
807         log.info("Sending file");
808         long t1 = System.currentTimeMillis();
809
810         HttpResponse r = new HttpResponse();
811         r.code = 200;
812
813         if (!p.skipSending) {
814             String tt = "application/octet-stream";
815             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
816
817             Response response;
818
819             try {
820                 if (p.httpMethod == HttpMethod.POST) {
821                     response = invocationBuilder.post(Entity.entity(data, tt));
822                 } else if (p.httpMethod == HttpMethod.PUT) {
823                     response = invocationBuilder.put(Entity.entity(data, tt));
824                 } else {
825                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
826                 }
827             } catch (ProcessingException e) {
828                 throw new SvcLogicException("Exception while posting http request to client " +
829                     e.getLocalizedMessage(), e);
830             }
831
832             r.code = response.getStatus();
833             r.headers = response.getStringHeaders();
834             EntityTag etag = response.getEntityTag();
835             if (etag != null) {
836                 r.message = etag.getValue();
837             }
838             if (response.hasEntity() && r.code != 204) {
839                 r.body = response.readEntity(String.class);
840             }
841
842             if (r.code == 301) {
843                 String newUrl = response.getStringHeaders().getFirst("Location");
844
845                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
846
847                 webTarget = client.target(newUrl);
848                 invocationBuilder = webTarget.request(tt).accept(tt);
849
850                 try {
851                     if (p.httpMethod == HttpMethod.POST) {
852                         response = invocationBuilder.post(Entity.entity(data, tt));
853                     } else if (p.httpMethod == HttpMethod.PUT) {
854                         response = invocationBuilder.put(Entity.entity(data, tt));
855                     } else {
856                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
857                     }
858                 } catch (ProcessingException e) {
859                     throw new SvcLogicException("Exception while posting http request to client " +
860                         e.getLocalizedMessage(), e);
861                 }
862
863                 r.code = response.getStatus();
864                 etag = response.getEntityTag();
865                 if (etag != null) {
866                     r.message = etag.getValue();
867                 }
868                 if (response.hasEntity() && r.code != 204) {
869                     r.body = response.readEntity(String.class);
870                 }
871             }
872         }
873
874         long t2 = System.currentTimeMillis();
875         log.info("Response received. Time: {}", (t2 - t1));
876         log.info("HTTP response code: {}", r.code);
877         log.info("HTTP response message: {}", r.message);
878         logHeaders(r.headers);
879         log.info("HTTP response: {}", r.body);
880
881         return r;
882     }
883
884     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
885         UebParam p = new UebParam();
886         p.topic = parseParam(paramMap, "topic", true, null);
887         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
888         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
889         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
890         String skipSendingStr = paramMap.get("skipSending");
891         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
892         return p;
893     }
894
895     protected void logProperties(Map<String, Object> mm) {
896         List<String> ll = new ArrayList<>();
897         for (Object o : mm.keySet()) {
898             ll.add((String) o);
899         }
900         Collections.sort(ll);
901
902         log.info("Properties:");
903         for (String name : ll) {
904             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
905         }
906     }
907
908     protected void logHeaders(MultivaluedMap<String, String> mm) {
909         log.info("HTTP response headers:");
910
911         if (mm == null) {
912             return;
913         }
914
915         List<String> ll = new ArrayList<>();
916         for (Object o : mm.keySet()) {
917             ll.add((String) o);
918         }
919         Collections.sort(ll);
920
921         for (String name : ll) {
922             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
923         }
924     }
925
926     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
927         String[] urls = uebServers.split(" ");
928         for (int i = 0; i < urls.length; i++) {
929             if (!urls[i].endsWith("/")) {
930                 urls[i] += "/";
931             }
932             urls[i] += "events/" + p.topic;
933         }
934
935         Client client = ClientBuilder.newBuilder().build();
936         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
937         WebTarget webTarget = client.target(urls[0]);
938
939         log.info("UEB URL: {}", urls[0]);
940         log.info("Sending request:");
941         log.info(request);
942         long t1 = System.currentTimeMillis();
943
944         HttpResponse r = new HttpResponse();
945         r.code = 200;
946
947         if (!p.skipSending) {
948             String tt = "application/json";
949             String tt1 = tt + ";charset=UTF-8";
950
951             Response response;
952             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
953
954             try {
955                 response = invocationBuilder.post(Entity.entity(request, tt1));
956             } catch (ProcessingException e) {
957                 throw new SvcLogicException("Exception while posting http request to client " +
958                     e.getLocalizedMessage(), e);
959             }
960             r.code = response.getStatus();
961             r.headers = response.getStringHeaders();
962             if (response.hasEntity()) {
963                 r.body = response.readEntity(String.class);
964             }
965         }
966
967         long t2 = System.currentTimeMillis();
968         log.info("Response received. Time: {}", (t2 - t1));
969         log.info("HTTP response code: {}", r.code);
970         logHeaders(r.headers);
971         log.info("HTTP response:\n {}", r.body);
972
973         return r;
974     }
975
976     public void setUebServers(String uebServers) {
977         this.uebServers = uebServers;
978     }
979
980     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
981         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
982     }
983
984     private static class FileParam {
985
986         public String fileName;
987         public String url;
988         public String user;
989         public String password;
990         public HttpMethod httpMethod;
991         public String responsePrefix;
992         public boolean skipSending;
993         public String oAuthConsumerKey;
994         public String oAuthConsumerSecret;
995         public String oAuthSignatureMethod;
996         public String oAuthVersion;
997         public AuthType authtype;
998     }
999
1000     private static class UebParam {
1001
1002         public String topic;
1003         public String templateFileName;
1004         public String rootVarName;
1005         public String responsePrefix;
1006         public boolean skipSending;
1007     }
1008 }