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