5756d4e582fd1a92698990f2408da5e8be95cb82
[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             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
617             if (value1 == null) {
618                 // delete the whole element (line)
619                 int i3 = template.lastIndexOf('\n', i1);
620                 if (i3 < 0) {
621                     i3 = 0;
622                 }
623                 int i4 = template.indexOf('\n', i1);
624                 if (i4 < 0) {
625                     i4 = template.length();
626                 }
627
628                 if (i < i3) {
629                     ss.append(template.substring(i, i3));
630                 }
631                 i = i4;
632             } else {
633                 ss.append(template.substring(i, i1)).append(value1);
634                 i = i2 + 1;
635             }
636         }
637
638         String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
639             : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
640
641         if (format == Format.JSON) {
642             req = XmlJsonUtil.removeLastCommaJson(req);
643         }
644
645         long t2 = System.currentTimeMillis();
646         log.info("Building {} completed. Time: {}", format, t2 - t1);
647
648         return req;
649     }
650
651     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
652         StringBuilder newTemplate = new StringBuilder();
653         int k = 0;
654         while (k < template.length()) {
655             int i1 = template.indexOf("${repeat:", k);
656             if (i1 < 0) {
657                 newTemplate.append(template.substring(k));
658                 break;
659             }
660
661             int i2 = template.indexOf(':', i1 + 9);
662             if (i2 < 0) {
663                 throw new SvcLogicException(
664                     "Template error: Context variable name followed by : is required after repeat");
665             }
666
667             // Find the closing }, store in i3
668             int nn = 1;
669             int i3 = -1;
670             int i = i2;
671             while (nn > 0 && i < template.length()) {
672                 i3 = template.indexOf('}', i);
673                 if (i3 < 0) {
674                     throw new SvcLogicException("Template error: Matching } not found");
675                 }
676                 int i32 = template.indexOf('{', i);
677                 if (i32 >= 0 && i32 < i3) {
678                     nn++;
679                     i = i32 + 1;
680                 } else {
681                     nn--;
682                     i = i3 + 1;
683                 }
684             }
685
686             String var1 = template.substring(i1 + 9, i2);
687             String value1 = ctx.getAttribute(var1);
688             log.info("     {}:{}", var1, value1);
689             int n = 0;
690             try {
691                 n = Integer.parseInt(value1);
692             } catch (NumberFormatException e) {
693                 log.info("value1 not set or not a number, n will remain set at zero");
694             }
695
696             newTemplate.append(template.substring(k, i1));
697
698             String rpt = template.substring(i2 + 1, i3);
699
700             for (int ii = 0; ii < n; ii++) {
701                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
702                 if (ii == n - 1 && ss.trim().endsWith(",")) {
703                     int i4 = ss.lastIndexOf(',');
704                     if (i4 > 0) {
705                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
706                     }
707                 }
708                 newTemplate.append(ss);
709             }
710
711             k = i3 + 1;
712         }
713
714         if (k == 0) {
715             return newTemplate.toString();
716         }
717
718         return expandRepeats(ctx, newTemplate.toString(), level + 1);
719     }
720
721     protected String readFile(String fileName) throws SvcLogicException {
722         try {
723             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
724             return new String(encoded, "UTF-8");
725         } catch (IOException | SecurityException e) {
726             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
727         }
728     }
729
730     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
731         Parameters p = new Parameters();
732         p.restapiUser = fp.user;
733         p.restapiPassword = fp.password;
734         p.oAuthConsumerKey = fp.oAuthConsumerKey;
735         p.oAuthVersion = fp.oAuthVersion;
736         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
737         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
738         p.authtype = fp.authtype;
739         return addAuthType(c, p);
740     }
741
742     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
743         if (p.authtype == AuthType.Unspecified) {
744             if (p.restapiUser != null && p.restapiPassword != null) {
745                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
746             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
747                 Feature oAuth1Feature =
748                     OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
749                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
750                 client.register(oAuth1Feature);
751
752             }
753         } else {
754             if (p.authtype == AuthType.DIGEST) {
755                 if (p.restapiUser != null && p.restapiPassword != null) {
756                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
757                 } else {
758                     throw new SvcLogicException(
759                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
760                             + "parameters doesn't exist",
761                         new Throwable());
762                 }
763             } else if (p.authtype == AuthType.BASIC) {
764                 if (p.restapiUser != null && p.restapiPassword != null) {
765                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
766                 } else {
767                     throw new SvcLogicException(
768                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
769                             + "parameters doesn't exist",
770                         new Throwable());
771                 }
772             } else if (p.authtype == AuthType.OAUTH) {
773                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
774                     Feature oAuth1Feature = OAuth1ClientSupport
775                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
776                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
777                     client.register(oAuth1Feature);
778                 } else {
779                     throw new SvcLogicException(
780                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
781                             + "and oAuthSignatureMethod parameters doesn't exist",
782                         new Throwable());
783                 }
784             }
785         }
786         return client;
787     }
788
789     /**
790      * Receives the http response for the http request sent.
791      *
792      * @param request request msg
793      * @param p parameters
794      * @return HTTP response
795      * @throws SvcLogicException when sending http request fails
796      */
797     public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
798
799         ClientConfig config = new ClientConfig();
800         if(!StringUtils.isEmpty(p.proxyUrl)) {
801             try {
802                 URL proxyUrl = new URL(p.proxyUrl);
803                 HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
804                 config.connectorProvider(cp);
805                 final Proxy proxy = 
806                     new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()));
807
808                 cp.connectionFactory(new ConnectionFactory() {
809                     @Override
810                     public HttpURLConnection getConnection(URL url) throws IOException {
811                         return (HttpURLConnection) url.openConnection(proxy);
812                     }
813                 });
814             } catch (MalformedURLException e) {
815                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
816             }
817         }
818
819         SSLContext ssl = null;
820         if (p.ssl && p.restapiUrl.startsWith("https")) {
821             ssl = createSSLContext(p);
822         }
823
824         ClientBuilder builder = 
825             ClientBuilder.newBuilder().hostnameVerifier(new AcceptIpAddressHostNameVerifier());
826
827         if (ssl != null) { 
828             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
829             builder = builder.sslContext(ssl);  
830         }
831         if (config != null) {
832             builder = builder.withConfig(config);
833         }
834
835         Client client = builder.build();
836
837         setClientTimeouts(client);
838         // Needed to support additional HTTP methods such as PATCH
839         client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
840         client.register(new MetricLogClientFilter());
841         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
842
843         long t1 = System.currentTimeMillis();
844
845         HttpResponse r = new HttpResponse();
846         r.code = 200;
847         String accept = p.accept;
848         if (accept == null) {
849             accept = p.format == Format.XML ? "application/xml" : "application/json";
850         }
851
852         String contentType = p.contentType;
853         if (contentType == null) {
854             contentType = accept + ";charset=UTF-8";
855         }
856
857         if (!p.skipSending && !p.multipartFormData) {
858             Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
859
860             if (p.format == Format.NONE) {
861                 invocationBuilder.header("", "");
862             }
863
864             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
865                 String[] keyValuePairs = p.customHttpHeaders.split(",");
866                 for (String singlePair : keyValuePairs) {
867                     int equalPosition = singlePair.indexOf('=');
868                     invocationBuilder.header(singlePair.substring(0, equalPosition),
869                         singlePair.substring(equalPosition + 1, singlePair.length()));
870                 }
871             }
872
873             invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
874
875             Response response;
876
877             try {
878                 // When the HTTP operation has no body do not set the content-type
879                 //setting content-type has caused errors with some servers when no body is present
880                 if (request == null) {
881                     response = invocationBuilder.method(p.httpMethod.toString());
882                 } else {
883                     log.info(request);
884                     response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
885                 }
886             } catch (ProcessingException | IllegalStateException e) {
887                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
888             }
889
890             r.code = response.getStatus();
891             r.headers = response.getStringHeaders();
892             EntityTag etag = response.getEntityTag();
893             if (etag != null) {
894                 r.message = etag.getValue();
895             }
896             if (response.hasEntity() && r.code != 204) {
897                 r.body = response.readEntity(String.class);
898             }
899         } else if (!p.skipSending && p.multipartFormData) {
900             WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
901
902             MultiPart multiPart = new MultiPart();
903             multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
904
905             FileDataBodyPart fileDataBodyPart =
906                 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
907             multiPart.bodyPart(fileDataBodyPart);
908
909
910             Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
911
912             if (p.format == Format.NONE) {
913                 invocationBuilder.header("", "");
914             }
915
916             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
917                 String[] keyValuePairs = p.customHttpHeaders.split(",");
918                 for (String singlePair : keyValuePairs) {
919                     int equalPosition = singlePair.indexOf('=');
920                     invocationBuilder.header(singlePair.substring(0, equalPosition),
921                         singlePair.substring(equalPosition + 1, singlePair.length()));
922                 }
923             }
924
925             Response response;
926
927             try {
928                 response =
929                     invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
930             } catch (ProcessingException | IllegalStateException e) {
931                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
932             }
933
934             r.code = response.getStatus();
935             r.headers = response.getStringHeaders();
936             EntityTag etag = response.getEntityTag();
937             if (etag != null) {
938                 r.message = etag.getValue();
939             }
940             if (response.hasEntity() && r.code != 204) {
941                 r.body = response.readEntity(String.class);
942             }
943
944         }
945
946         long t2 = System.currentTimeMillis();
947         log.info(responseReceivedMessage, t2 - t1);
948         log.info(responseHttpCodeMessage, r.code);
949         log.info("HTTP response message: {}", r.message);
950         logHeaders(r.headers);
951         log.info("HTTP response: {}", r.body);
952
953         return r;
954     }
955
956     protected SSLContext createSSLContext(Parameters p) {
957         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
958             HttpsURLConnection.setDefaultHostnameVerifier(new AcceptIpAddressHostNameVerifier(p.disableHostVerification));
959             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
960             KeyStore ks = KeyStore.getInstance("PKCS12");
961             char[] pwd = p.keyStorePassword.toCharArray();
962             ks.load(in, pwd);
963             kmf.init(ks, pwd);
964             SSLContext ctx = SSLContext.getInstance("TLS");
965             ctx.init(kmf.getKeyManagers(), null, null);
966             return ctx;
967         } catch (Exception e) {
968             log.error("Error creating SSLContext: {}", e.getMessage(), e);
969         }
970         return null;
971     }
972
973     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
974         HttpResponse resp) {
975         resp.code = 500;
976         resp.message = errorMessage;
977         String pp = prefix != null ? prefix + '.' : "";
978         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
979         ctx.setAttribute(pp + "response-message", resp.message);
980     }
981
982     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
983         String pp = prefix != null ? prefix + '.' : "";
984         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
985         ctx.setAttribute(pp + "response-message", r.message);
986     }
987
988     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
989         HttpResponse r = null;
990         try {
991             FileParam p = getFileParameters(paramMap);
992             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
993
994             r = sendHttpData(data, p);
995
996             for (int i = 0; i < 10 && r.code == 301; i++) {
997                 String newUrl = r.headers2.get("Location").get(0);
998
999                 log.info("Got response code 301. Sending same request to URL: " + newUrl);
1000
1001                 p.url = newUrl;
1002                 r = sendHttpData(data, p);
1003             }
1004
1005             setResponseStatus(ctx, p.responsePrefix, r);
1006
1007         } catch (SvcLogicException | IOException e) {
1008             log.error("Error sending the request: {}", e.getMessage(), e);
1009
1010             r = new HttpResponse();
1011             r.code = 500;
1012             r.message = e.getMessage();
1013             String prefix = parseParam(paramMap, responsePrefix, false, null);
1014             setResponseStatus(ctx, prefix, r);
1015         }
1016
1017         if (r != null && r.code >= 300) {
1018             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1019         }
1020     }
1021
1022     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
1023         FileParam p = new FileParam();
1024         p.fileName = parseParam(paramMap, "fileName", true, null);
1025         p.url = parseParam(paramMap, "url", true, null);
1026         p.user = parseParam(paramMap, "user", false, null);
1027         p.password = parseParam(paramMap, "password", false, null);
1028         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1029         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1030         String skipSendingStr = paramMap.get(skipSendingMessage);
1031         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1032         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1033         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1034         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1035         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1036         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1037         return p;
1038     }
1039
1040     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1041         HttpResponse r;
1042         try {
1043             UebParam p = getUebParameters(paramMap);
1044
1045             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1046
1047             String req;
1048
1049             if (p.templateFileName == null) {
1050                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1051                 p.templateFileName = defaultUebTemplateFileName;
1052             }
1053
1054             String reqTemplate = readFile(p.templateFileName);
1055             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1056             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1057
1058             r = postOnUeb(req, p);
1059             setResponseStatus(ctx, p.responsePrefix, r);
1060             if (r.body != null) {
1061                 ctx.setAttribute(pp + "httpResponse", r.body);
1062             }
1063
1064         } catch (SvcLogicException e) {
1065             log.error("Error sending the request: {}", e.getMessage(), e);
1066
1067             r = new HttpResponse();
1068             r.code = 500;
1069             r.message = e.getMessage();
1070             String prefix = parseParam(paramMap, responsePrefix, false, null);
1071             setResponseStatus(ctx, prefix, r);
1072         }
1073
1074         if (r.code >= 300) {
1075             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1076         }
1077     }
1078
1079     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1080         URL url = new URL(p.url);
1081         HttpURLConnection con = (HttpURLConnection) url.openConnection();
1082
1083         log.info("Connection: " + con.getClass().getName());
1084
1085         con.setRequestMethod(p.httpMethod.toString());
1086         con.setRequestProperty("Content-Type", "application/octet-stream");
1087         con.setRequestProperty("Accept", "*/*");
1088         con.setRequestProperty("Expect", "100-continue");
1089         con.setFixedLengthStreamingMode(data.length);
1090         con.setInstanceFollowRedirects(false);
1091
1092         if (p.user != null && p.password != null) {
1093             String authString = p.user + ":" + p.password;
1094             String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1095             con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1096         }
1097
1098         con.setDoInput(true);
1099         con.setDoOutput(true);
1100
1101         log.info("Sending file");
1102         long t1 = System.currentTimeMillis();
1103
1104         HttpResponse r = new HttpResponse();
1105         r.code = 200;
1106
1107         if (!p.skipSending) {
1108             HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1109             util.logBefore(con, ONAPComponents.DMAAP);
1110
1111             con.connect();
1112
1113             boolean continue100failed = false;
1114             try {
1115                 OutputStream os = con.getOutputStream();
1116                 os.write(data);
1117                 os.flush();
1118                 os.close();
1119             } catch (ProtocolException e) {
1120                 continue100failed = true;
1121             }
1122
1123             r.code = con.getResponseCode();
1124             r.headers2 = con.getHeaderFields();
1125
1126             if (r.code != 204 && !continue100failed) {
1127                 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1128                 String inputLine;
1129                 StringBuffer response = new StringBuffer();
1130                 while ((inputLine = in.readLine()) != null) {
1131                     response.append(inputLine);
1132                 }
1133                 in.close();
1134
1135                 r.body = response.toString();
1136             }
1137
1138             util.logAfter(con);
1139
1140             con.disconnect();
1141         }
1142
1143         long t2 = System.currentTimeMillis();
1144         log.info("Response received. Time: {}", t2 - t1);
1145         log.info("HTTP response code: {}", r.code);
1146         log.info("HTTP response message: {}", r.message);
1147         logHeaders(r.headers2);
1148         log.info("HTTP response: {}", r.body);
1149
1150         return r;
1151     }
1152
1153     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1154         UebParam p = new UebParam();
1155         p.topic = parseParam(paramMap, "topic", true, null);
1156         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1157         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1158         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1159         String skipSendingStr = paramMap.get(skipSendingMessage);
1160         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1161         return p;
1162     }
1163
1164     protected void logProperties(Map<String, Object> mm) {
1165         List<String> ll = new ArrayList<>();
1166         for (Object o : mm.keySet()) {
1167             ll.add((String) o);
1168         }
1169         Collections.sort(ll);
1170
1171         log.info("Properties:");
1172         for (String name : ll) {
1173             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1174         }
1175     }
1176
1177     protected void logHeaders(MultivaluedMap<String, String> mm) {
1178         log.info("HTTP response headers:");
1179
1180         if (mm == null) {
1181             return;
1182         }
1183
1184         List<String> ll = new ArrayList<>();
1185         for (Object o : mm.keySet()) {
1186             ll.add((String) o);
1187         }
1188         Collections.sort(ll);
1189
1190         for (String name : ll) {
1191             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1192         }
1193     }
1194
1195     private void logHeaders(Map<String, List<String>> mm) {
1196         if (mm == null || mm.isEmpty()) {
1197             return;
1198         }
1199
1200         List<String> ll = new ArrayList<>();
1201         for (String s : mm.keySet()) {
1202             if (s != null) {
1203                 ll.add(s);
1204             }
1205         }
1206         Collections.sort(ll);
1207
1208         for (String name : ll) {
1209             List<String> v = mm.get(name);
1210             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1211             log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1212         }
1213     }
1214
1215     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1216         String[] urls = uebServers.split(" ");
1217         for (int i = 0; i < urls.length; i++) {
1218             if (!urls[i].endsWith("/")) {
1219                 urls[i] += "/";
1220             }
1221             urls[i] += "events/" + p.topic;
1222         }
1223
1224         Client client = ClientBuilder.newBuilder().build();
1225         setClientTimeouts(client);
1226         WebTarget webTarget = client.target(urls[0]);
1227
1228         log.info("UEB URL: {}", urls[0]);
1229         log.info("Sending request:");
1230         log.info(request);
1231         long t1 = System.currentTimeMillis();
1232
1233         HttpResponse r = new HttpResponse();
1234         r.code = 200;
1235
1236         if (!p.skipSending) {
1237             String tt = "application/json";
1238             String tt1 = tt + ";charset=UTF-8";
1239
1240             Response response;
1241             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1242
1243             try {
1244                 response = invocationBuilder.post(Entity.entity(request, tt1));
1245             } catch (ProcessingException e) {
1246                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1247             }
1248             r.code = response.getStatus();
1249             r.headers = response.getStringHeaders();
1250             if (response.hasEntity()) {
1251                 r.body = response.readEntity(String.class);
1252             }
1253         }
1254
1255         long t2 = System.currentTimeMillis();
1256         log.info(responseReceivedMessage, t2 - t1);
1257         log.info(responseHttpCodeMessage, r.code);
1258         logHeaders(r.headers);
1259         log.info("HTTP response:\n {}", r.body);
1260
1261         return r;
1262     }
1263
1264     public void setUebServers(String uebServers) {
1265         this.uebServers = uebServers;
1266     }
1267
1268     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1269         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1270     }
1271
1272     protected void setClientTimeouts(Client client) {
1273         client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1274         client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1275     }
1276
1277     protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1278         String stringValue = System.getProperty(propertyName);
1279         if (stringValue != null && stringValue.length() > 0) {
1280             try {
1281                 return Integer.valueOf(stringValue);
1282             } catch (NumberFormatException e) {
1283                 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1284             }
1285         }
1286         return defaultValue;
1287     }
1288
1289     protected static String[] getMultipleUrls(String restapiUrl) {
1290         List<String> urls = new ArrayList<>();
1291         int start = 0;
1292         for (int i = 0; i < restapiUrl.length(); i++) {
1293             if (restapiUrl.charAt(i) == ',') {
1294                 if (i + 9 < restapiUrl.length()) {
1295                     String part = restapiUrl.substring(i + 1, i + 9);
1296                     if (part.equals("https://") || part.startsWith("http://")) {
1297                         urls.add(restapiUrl.substring(start, i));
1298                         start = i + 1;
1299                     }
1300                 }
1301             } else if (i == restapiUrl.length() - 1) {
1302                 urls.add(restapiUrl.substring(start, i + 1));
1303             }
1304         }
1305         String[] arr = new String[urls.size()];
1306         return urls.toArray(arr);
1307     }
1308
1309     protected static boolean containsMultipleUrls(String restapiUrl) {
1310         Matcher m = retryPattern.matcher(restapiUrl);
1311         return m.matches();
1312     }
1313
1314     private static class FileParam {
1315
1316         public String fileName;
1317         public String url;
1318         public String user;
1319         public String password;
1320         public HttpMethod httpMethod;
1321         public String responsePrefix;
1322         public boolean skipSending;
1323         public String oAuthConsumerKey;
1324         public String oAuthConsumerSecret;
1325         public String oAuthSignatureMethod;
1326         public String oAuthVersion;
1327         public AuthType authtype;
1328     }
1329
1330     private static class UebParam {
1331
1332         public String topic;
1333         public String templateFileName;
1334         public String rootVarName;
1335         public String responsePrefix;
1336         public boolean skipSending;
1337     }
1338 }