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