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