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