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