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