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