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