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