Merge "Issue fixes for Restconf discovery node"
[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
396         template = expandRepeats(ctx, template, 1);
397
398         Map<String, String> mm = new HashMap<>();
399         for (String s : ctx.getAttributeKeySet()) {
400             mm.put(s, ctx.getAttribute(s));
401         }
402
403         StringBuilder ss = new StringBuilder();
404         int i = 0;
405         while (i < template.length()) {
406             int i1 = template.indexOf("${", i);
407             if (i1 < 0) {
408                 ss.append(template.substring(i));
409                 break;
410             }
411
412             int i2 = template.indexOf('}', i1 + 2);
413             if (i2 < 0) {
414                 throw new SvcLogicException("Template error: Matching } not found");
415             }
416
417             String var1 = template.substring(i1 + 2, i2);
418             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
419             // log.info(" " + var1 + ": " + value1);
420             if (value1 == null || value1.trim().length() == 0) {
421                 // delete the whole element (line)
422                 int i3 = template.lastIndexOf('\n', i1);
423                 if (i3 < 0) {
424                     i3 = 0;
425                 }
426                 int i4 = template.indexOf('\n', i1);
427                 if (i4 < 0) {
428                     i4 = template.length();
429                 }
430
431                 if (i < i3) {
432                     ss.append(template.substring(i, i3));
433                 }
434                 i = i4;
435             } else {
436                 ss.append(template.substring(i, i1)).append(value1);
437                 i = i2 + 1;
438             }
439         }
440
441         String req = format == Format.XML
442             ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
443
444         if (format == Format.JSON) {
445             req = XmlJsonUtil.removeLastCommaJson(req);
446         }
447
448         long t2 = System.currentTimeMillis();
449         log.info("Building {} completed. Time: {}", format, (t2 - t1));
450
451         return req;
452     }
453
454     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
455         StringBuilder newTemplate = new StringBuilder();
456         int k = 0;
457         while (k < template.length()) {
458             int i1 = template.indexOf("${repeat:", k);
459             if (i1 < 0) {
460                 newTemplate.append(template.substring(k));
461                 break;
462             }
463
464             int i2 = template.indexOf(':', i1 + 9);
465             if (i2 < 0) {
466                 throw new SvcLogicException(
467                     "Template error: Context variable name followed by : is required after repeat");
468             }
469
470             // Find the closing }, store in i3
471             int nn = 1;
472             int i3 = -1;
473             int i = i2;
474             while (nn > 0 && i < template.length()) {
475                 i3 = template.indexOf('}', i);
476                 if (i3 < 0) {
477                     throw new SvcLogicException("Template error: Matching } not found");
478                 }
479                 int i32 = template.indexOf('{', i);
480                 if (i32 >= 0 && i32 < i3) {
481                     nn++;
482                     i = i32 + 1;
483                 } else {
484                     nn--;
485                     i = i3 + 1;
486                 }
487             }
488
489             String var1 = template.substring(i1 + 9, i2);
490             String value1 = ctx.getAttribute(var1);
491             log.info("     {}:{}", var1, value1);
492             int n = 0;
493             try {
494                 n = Integer.parseInt(value1);
495             } catch (NumberFormatException e) {
496                 log.info("value1 not set or not a number, n will remain set at zero");
497             }
498
499             newTemplate.append(template.substring(k, i1));
500
501             String rpt = template.substring(i2 + 1, i3);
502
503             for (int ii = 0; ii < n; ii++) {
504                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
505                 if (ii == n - 1 && ss.trim().endsWith(",")) {
506                     int i4 = ss.lastIndexOf(',');
507                     if (i4 > 0) {
508                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
509                     }
510                 }
511                 newTemplate.append(ss);
512             }
513
514             k = i3 + 1;
515         }
516
517         if (k == 0) {
518             return newTemplate.toString();
519         }
520
521         return expandRepeats(ctx, newTemplate.toString(), level + 1);
522     }
523
524     protected String readFile(String fileName) throws SvcLogicException {
525         try {
526             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
527             return new String(encoded, "UTF-8");
528         } catch (IOException | SecurityException e) {
529             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
530         }
531     }
532
533     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
534         Parameters p = new Parameters();
535         p.restapiUser = fp.user;
536         p.restapiPassword = fp.password;
537         p.oAuthConsumerKey = fp.oAuthConsumerKey;
538         p.oAuthVersion = fp.oAuthVersion;
539         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
540         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
541         p.authtype = fp.authtype;
542         return addAuthType(c, p);
543     }
544
545     protected Client addAuthType(Client client, Parameters p) throws SvcLogicException {
546         if (p.authtype == AuthType.Unspecified) {
547             if (p.restapiUser != null && p.restapiPassword != null) {
548                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
549             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
550                 && p.oAuthSignatureMethod != null) {
551                 Feature oAuth1Feature = OAuth1ClientSupport
552                     .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
553                     .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
554                 client.register(oAuth1Feature);
555             }
556         } else {
557             if (p.authtype == AuthType.DIGEST) {
558                 if (p.restapiUser != null && p.restapiPassword != null) {
559                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
560                 } else {
561                     throw new SvcLogicException(
562                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
563                             "parameters doesn't exist", new Throwable());
564                 }
565             } else if (p.authtype == AuthType.BASIC) {
566                 if (p.restapiUser != null && p.restapiPassword != null) {
567                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
568                 } else {
569                     throw new SvcLogicException(
570                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
571                             "parameters doesn't exist", new Throwable());
572                 }
573             } else if (p.authtype == AuthType.OAUTH) {
574                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
575                     Feature oAuth1Feature = OAuth1ClientSupport
576                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
577                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
578                     client.register(oAuth1Feature);
579                 } else {
580                     throw new SvcLogicException(
581                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
582                             "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
583                 }
584             }
585         }
586         return client;
587     }
588
589     /**
590      * Receives the http response for the http request sent.
591      *
592      * @param request request msg
593      * @param p       parameters
594      * @return HTTP response
595      * @throws SvcLogicException when sending http request fails
596      */
597     public HttpResponse sendHttpRequest(String request, Parameters p)
598         throws SvcLogicException {
599
600         SSLContext ssl = null;
601         if (p.ssl && p.restapiUrl.startsWith("https")) {
602             ssl = createSSLContext(p);
603         }
604         Client client;
605
606         if (ssl != null) {
607             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
608             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
609                 .build();
610         } else {
611             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
612                 .build();
613         }
614         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
615
616         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
617
618         log.info("Sending request:");
619         log.info(request);
620         long t1 = System.currentTimeMillis();
621
622         HttpResponse r = new HttpResponse();
623         r.code = 200;
624
625         if (!p.skipSending) {
626             String tt = p.format == Format.XML ? "application/xml" : "application/json";
627             String tt1 = tt + ";charset=UTF-8";
628             if (p.contentType != null) {
629                 tt = p.contentType;
630                 tt1 = p.contentType;
631             }
632
633             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
634
635             if (p.format == Format.NONE) {
636                 invocationBuilder.header("", "");
637             }
638
639             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
640                 String[] keyValuePairs = p.customHttpHeaders.split(",");
641                 for (String singlePair : keyValuePairs) {
642                     int equalPosition = singlePair.indexOf('=');
643                     invocationBuilder.header(singlePair.substring(0, equalPosition),
644                         singlePair.substring(equalPosition + 1, singlePair.length()));
645                 }
646             }
647
648             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
649
650             Response response;
651
652             try {
653                 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
654             } catch (ProcessingException | IllegalStateException e) {
655                 throw new SvcLogicException("Exception while posting http request to client " +
656                     e.getLocalizedMessage(), e);
657             }
658
659             r.code = response.getStatus();
660             r.headers = response.getStringHeaders();
661             EntityTag etag = response.getEntityTag();
662             if (etag != null) {
663                 r.message = etag.getValue();
664             }
665             if (response.hasEntity() && r.code != 204) {
666                 r.body = response.readEntity(String.class);
667             }
668         }
669
670         long t2 = System.currentTimeMillis();
671         log.info("Response received. Time: {}", (t2 - t1));
672         log.info("HTTP response code: {}", r.code);
673         log.info("HTTP response message: {}", r.message);
674         logHeaders(r.headers);
675         log.info("HTTP response: {}", r.body);
676
677         return r;
678     }
679
680     protected SSLContext createSSLContext(Parameters p) {
681         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
682             System.setProperty("jsse.enableSNIExtension", "false");
683             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
684             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
685
686             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
687
688             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
689             KeyStore ks = KeyStore.getInstance("PKCS12");
690             char[] pwd = p.keyStorePassword.toCharArray();
691             ks.load(in, pwd);
692             kmf.init(ks, pwd);
693
694             SSLContext ctx = SSLContext.getInstance("TLS");
695             ctx.init(kmf.getKeyManagers(), null, null);
696             return ctx;
697         } catch (Exception e) {
698             log.error("Error creating SSLContext: {}", e.getMessage(), e);
699         }
700         return null;
701     }
702
703     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
704         HttpResponse resp) {
705         resp.code = 500;
706         resp.message = errorMessage;
707         String pp = prefix != null ? prefix + '.' : "";
708         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
709         ctx.setAttribute(pp + "response-message", resp.message);
710     }
711
712     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
713         String pp = prefix != null ? prefix + '.' : "";
714         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
715         ctx.setAttribute(pp + "response-message", r.message);
716     }
717
718     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
719         HttpResponse r = null;
720         try {
721             FileParam p = getFileParameters(paramMap);
722             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
723
724             r = sendHttpData(data, p);
725             setResponseStatus(ctx, p.responsePrefix, r);
726
727         } catch (SvcLogicException | IOException e) {
728             log.error("Error sending the request: {}", e.getMessage(), e);
729
730             r = new HttpResponse();
731             r.code = 500;
732             r.message = e.getMessage();
733             String prefix = parseParam(paramMap, "responsePrefix", false, null);
734             setResponseStatus(ctx, prefix, r);
735         }
736
737         if (r != null && r.code >= 300) {
738             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
739         }
740     }
741
742     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
743         FileParam p = new FileParam();
744         p.fileName = parseParam(paramMap, "fileName", true, null);
745         p.url = parseParam(paramMap, "url", true, null);
746         p.user = parseParam(paramMap, "user", false, null);
747         p.password = parseParam(paramMap, "password", false, null);
748         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
749         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
750         String skipSendingStr = paramMap.get("skipSending");
751         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
752         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
753         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
754         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
755         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
756         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
757         return p;
758     }
759
760     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
761         HttpResponse r;
762         try {
763             UebParam p = getUebParameters(paramMap);
764
765             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
766
767             String req;
768
769             if (p.templateFileName == null) {
770                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
771                 p.templateFileName = defaultUebTemplateFileName;
772             }
773
774             String reqTemplate = readFile(p.templateFileName);
775             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
776             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
777
778             r = postOnUeb(req, p);
779             setResponseStatus(ctx, p.responsePrefix, r);
780             if (r.body != null) {
781                 ctx.setAttribute(pp + "httpResponse", r.body);
782             }
783
784         } catch (SvcLogicException e) {
785             log.error("Error sending the request: {}", e.getMessage(), e);
786
787             r = new HttpResponse();
788             r.code = 500;
789             r.message = e.getMessage();
790             String prefix = parseParam(paramMap, "responsePrefix", false, null);
791             setResponseStatus(ctx, prefix, r);
792         }
793
794         if (r.code >= 300) {
795             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
796         }
797     }
798
799     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
800
801         Client client = ClientBuilder.newBuilder().build();
802         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
803         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
804         WebTarget webTarget = addAuthType(client, p).target(p.url);
805
806         log.info("Sending file");
807         long t1 = System.currentTimeMillis();
808
809         HttpResponse r = new HttpResponse();
810         r.code = 200;
811
812         if (!p.skipSending) {
813             String tt = "application/octet-stream";
814             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
815
816             Response response;
817
818             try {
819                 if (p.httpMethod == HttpMethod.POST) {
820                     response = invocationBuilder.post(Entity.entity(data, tt));
821                 } else if (p.httpMethod == HttpMethod.PUT) {
822                     response = invocationBuilder.put(Entity.entity(data, tt));
823                 } else {
824                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
825                 }
826             } catch (ProcessingException e) {
827                 throw new SvcLogicException("Exception while posting http request to client " +
828                     e.getLocalizedMessage(), e);
829             }
830
831             r.code = response.getStatus();
832             r.headers = response.getStringHeaders();
833             EntityTag etag = response.getEntityTag();
834             if (etag != null) {
835                 r.message = etag.getValue();
836             }
837             if (response.hasEntity() && r.code != 204) {
838                 r.body = response.readEntity(String.class);
839             }
840
841             if (r.code == 301) {
842                 String newUrl = response.getStringHeaders().getFirst("Location");
843
844                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
845
846                 webTarget = client.target(newUrl);
847                 invocationBuilder = webTarget.request(tt).accept(tt);
848
849                 try {
850                     if (p.httpMethod == HttpMethod.POST) {
851                         response = invocationBuilder.post(Entity.entity(data, tt));
852                     } else if (p.httpMethod == HttpMethod.PUT) {
853                         response = invocationBuilder.put(Entity.entity(data, tt));
854                     } else {
855                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
856                     }
857                 } catch (ProcessingException e) {
858                     throw new SvcLogicException("Exception while posting http request to client " +
859                         e.getLocalizedMessage(), e);
860                 }
861
862                 r.code = response.getStatus();
863                 etag = response.getEntityTag();
864                 if (etag != null) {
865                     r.message = etag.getValue();
866                 }
867                 if (response.hasEntity() && r.code != 204) {
868                     r.body = response.readEntity(String.class);
869                 }
870             }
871         }
872
873         long t2 = System.currentTimeMillis();
874         log.info("Response received. Time: {}", (t2 - t1));
875         log.info("HTTP response code: {}", r.code);
876         log.info("HTTP response message: {}", r.message);
877         logHeaders(r.headers);
878         log.info("HTTP response: {}", r.body);
879
880         return r;
881     }
882
883     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
884         UebParam p = new UebParam();
885         p.topic = parseParam(paramMap, "topic", true, null);
886         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
887         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
888         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
889         String skipSendingStr = paramMap.get("skipSending");
890         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
891         return p;
892     }
893
894     protected void logProperties(Map<String, Object> mm) {
895         List<String> ll = new ArrayList<>();
896         for (Object o : mm.keySet()) {
897             ll.add((String) o);
898         }
899         Collections.sort(ll);
900
901         log.info("Properties:");
902         for (String name : ll) {
903             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
904         }
905     }
906
907     protected void logHeaders(MultivaluedMap<String, String> mm) {
908         log.info("HTTP response headers:");
909
910         if (mm == null) {
911             return;
912         }
913
914         List<String> ll = new ArrayList<>();
915         for (Object o : mm.keySet()) {
916             ll.add((String) o);
917         }
918         Collections.sort(ll);
919
920         for (String name : ll) {
921             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
922         }
923     }
924
925     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
926         String[] urls = uebServers.split(" ");
927         for (int i = 0; i < urls.length; i++) {
928             if (!urls[i].endsWith("/")) {
929                 urls[i] += "/";
930             }
931             urls[i] += "events/" + p.topic;
932         }
933
934         Client client = ClientBuilder.newBuilder().build();
935         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
936         WebTarget webTarget = client.target(urls[0]);
937
938         log.info("UEB URL: {}", urls[0]);
939         log.info("Sending request:");
940         log.info(request);
941         long t1 = System.currentTimeMillis();
942
943         HttpResponse r = new HttpResponse();
944         r.code = 200;
945
946         if (!p.skipSending) {
947             String tt = "application/json";
948             String tt1 = tt + ";charset=UTF-8";
949
950             Response response;
951             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
952
953             try {
954                 response = invocationBuilder.post(Entity.entity(request, tt1));
955             } catch (ProcessingException e) {
956                 throw new SvcLogicException("Exception while posting http request to client " +
957                     e.getLocalizedMessage(), e);
958             }
959             r.code = response.getStatus();
960             r.headers = response.getStringHeaders();
961             if (response.hasEntity()) {
962                 r.body = response.readEntity(String.class);
963             }
964         }
965
966         long t2 = System.currentTimeMillis();
967         log.info("Response received. Time: {}", (t2 - t1));
968         log.info("HTTP response code: {}", r.code);
969         logHeaders(r.headers);
970         log.info("HTTP response:\n {}", r.body);
971
972         return r;
973     }
974
975     public void setUebServers(String uebServers) {
976         this.uebServers = uebServers;
977     }
978
979     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
980         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
981     }
982
983     private static class FileParam {
984
985         public String fileName;
986         public String url;
987         public String user;
988         public String password;
989         public HttpMethod httpMethod;
990         public String responsePrefix;
991         public boolean skipSending;
992         public String oAuthConsumerKey;
993         public String oAuthConsumerSecret;
994         public String oAuthSignatureMethod;
995         public String oAuthVersion;
996         public AuthType authtype;
997     }
998
999     private static class UebParam {
1000
1001         public String topic;
1002         public String templateFileName;
1003         public String rootVarName;
1004         public String responsePrefix;
1005         public boolean skipSending;
1006     }
1007 }