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