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