add request body param
[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  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.ccsdk.sli.plugins.restapicall;
23
24 import com.sun.jersey.api.client.ClientHandlerException;
25 import com.sun.jersey.api.client.UniformInterfaceException;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.net.SocketException;
29 import java.net.URI;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.security.KeyStore;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Map.Entry;
40 import java.util.Set;
41
42 import javax.net.ssl.HostnameVerifier;
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.net.ssl.KeyManagerFactory;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.SSLSession;
47 import javax.ws.rs.core.EntityTag;
48 import javax.ws.rs.core.MultivaluedMap;
49 import javax.ws.rs.core.UriBuilder;
50
51 import org.apache.commons.lang3.StringUtils;
52 import org.codehaus.jettison.json.JSONException;
53 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
54 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.sun.jersey.api.client.Client;
60 import com.sun.jersey.api.client.ClientResponse;
61 import com.sun.jersey.api.client.WebResource;
62 import com.sun.jersey.api.client.config.ClientConfig;
63 import com.sun.jersey.api.client.config.DefaultClientConfig;
64 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
65 import com.sun.jersey.client.urlconnection.HTTPSProperties;
66
67 public class RestapiCallNode implements SvcLogicJavaPlugin {
68
69     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
70
71     private String uebServers;
72     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
73     protected RetryPolicyStore retryPolicyStore;
74
75     protected RetryPolicyStore getRetryPolicyStore() {
76         return retryPolicyStore;
77     }
78
79     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
80         this.retryPolicyStore = retryPolicyStore;
81     }
82
83     public RestapiCallNode() {
84
85     }
86
87      /**
88      * Allows Directed Graphs  the ability to interact with REST APIs.
89      * @param parameters HashMap<String,String> of parameters passed by the DG to this function
90      * <table border="1">
91      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
92      *  <tbody>
93      *      <tr><td>templateFileName</td><td>Optional</td><td>full path to template file that can be used to build a request</td><td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td></tr>
94      *      <tr><td>restapiUrl</td><td>Mandatory</td><td>url to send the request to</td><td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td></tr>
95      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
96      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
97      *      <tr><td>contentType</td><td>Optional</td><td>http content type to set in the http header</td><td>usually application/json or application/xml</td></tr>
98      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
99      *      <tr><td>httpMethod</td><td>Optional</td><td>http method to use when sending the request</td><td>get post put delete patch</td></tr>
100      *      <tr><td>responsePrefix</td><td>Optional</td><td>location the response will be written to in context memory</td><td>tmp.restapi.result</td></tr>
101      *      <tr><td>listName[i]</td><td>Optional</td><td>Used for processing XML responses with repeating elements.</td>vpn-information.vrf-details<td></td></tr>
102      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
103      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
104      *      <tr><td>customHttpHeaders</td><td>Optional</td><td>a list additional http headers to be passed in, follow the format in the example</td><td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td></tr>
105      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
106      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
107      *  </tbody>
108      * </table>
109      * @param ctx Reference to context memory
110      * @throws SvcLogicException
111      * @since 11.0.2
112      * @see String#split(String, int)
113      */
114     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
115         sendRequest(paramMap, ctx, null);
116     }
117
118     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
119             throws SvcLogicException {
120
121         RetryPolicy retryPolicy = null;
122         HttpResponse r = new HttpResponse();
123         try {
124             Parameters p = getParameters(paramMap);
125             if (p.partner != null) {
126                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
127             }
128             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
129
130             String req = null;
131             if (p.templateFileName != null) {
132                 String reqTemplate = readFile(p.templateFileName);
133                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
134             } else if (p.requestBody != null) {
135                 req = p.requestBody;
136             }
137             r = sendHttpRequest(req, p);
138             setResponseStatus(ctx, p.responsePrefix, r);
139
140             if (p.dumpHeaders && r.headers != null) {
141                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
142                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
143                 }
144             }
145
146             if (r.body != null && r.body.trim().length() > 0) {
147                 ctx.setAttribute(pp + "httpResponse", r.body);
148
149                 if (p.convertResponse) {
150                     Map<String, String> mm = null;
151                     if (p.format == Format.XML)
152                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
153                     else if (p.format == Format.JSON)
154                         mm = JsonParser.convertToProperties(r.body);
155
156                     if (mm != null)
157                         for (Map.Entry<String,String> entry : mm.entrySet())
158                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
159                 }
160             }
161         } catch (SvcLogicException e) {
162             boolean shouldRetry = false;
163             if (e.getCause().getCause() instanceof SocketException) {
164                 shouldRetry = true;
165             }
166
167             log.error("Error sending the request: " + e.getMessage(), e);
168             String prefix = parseParam(paramMap, "responsePrefix", false, null);
169             if (retryPolicy == null || shouldRetry == false) {
170                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
171             } else {
172                 if (retryCount == null) {
173                     retryCount = 0;
174                 }
175                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
176                         " maximum retries.";
177                 log.debug(retryMessage);
178                 try {
179                     retryCount = retryCount + 1;
180                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
181                         URI uri = new URI(paramMap.get("restapiUrl"));
182                         String hostname = uri.getHost();
183                         String retryString = retryPolicy.getNextHostName(uri.toString());
184                         URI uriTwo = new URI(retryString);
185                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
186                                 uriTwo.getScheme()).build();
187                         paramMap.put("restapiUrl", retryUri.toString());
188                         log.debug("URL was set to {}", retryUri.toString());
189                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
190                             hostname, retryString);
191                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
192                         sendRequest(paramMap, ctx, retryCount);
193                     } else {
194                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
195                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
196                     }
197                 } catch (Exception ex) {
198                     log.error("Could not attempt retry.", ex);
199                     String retryErrorMessage =
200                             "Retry attempt has failed. No further retry shall be attempted, calling " +
201                                 "setFailureResponseStatus.";
202                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
203                 }
204             }
205         }
206
207         if (r != null && r.code >= 300)
208             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
209     }
210
211     protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
212         Parameters p = new Parameters();
213         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
214         p.requestBody = parseParam(paramMap, "requestBody", false, null);
215         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
216         validateUrl(p.restapiUrl);
217         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
218         p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
219         p.contentType = parseParam(paramMap, "contentType", false, null);
220         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
221         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
222         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
223         p.listNameList = getListNameList(paramMap);
224         String skipSendingStr = paramMap.get("skipSending");
225         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
226         p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
227         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
228         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
229         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
230         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
231         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
232                 p.keyStorePassword != null;
233         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
234         p.partner = parseParam(paramMap, "partner", false, null);
235         p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
236         return p;
237     }
238
239     private void validateUrl(String restapiUrl) throws SvcLogicException {
240         try {
241             URI.create(restapiUrl);
242         } catch (IllegalArgumentException e) {
243             throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
244         }
245     }
246
247     protected Set<String> getListNameList(Map<String, String> paramMap) {
248         Set<String> ll = new HashSet<>();
249         for (Map.Entry<String,String> entry : paramMap.entrySet())
250             if (entry.getKey().startsWith("listName"))
251                 ll.add(entry.getValue());
252         return ll;
253     }
254
255     protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
256             throws SvcLogicException {
257         String s = paramMap.get(name);
258
259         if (s == null || s.trim().length() == 0) {
260             if (!required)
261                 return def;
262             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
263         }
264
265         s = s.trim();
266         StringBuilder value = new StringBuilder();
267         int i = 0;
268         int i1 = s.indexOf('%');
269         while (i1 >= 0) {
270             int i2 = s.indexOf('%', i1 + 1);
271             if (i2 < 0)
272                 break;
273
274             String varName = s.substring(i1 + 1, i2);
275             String varValue = System.getenv(varName);
276             if (varValue == null)
277                 varValue = "%" + varName + "%";
278
279             value.append(s.substring(i, i1));
280             value.append(varValue);
281
282             i = i2 + 1;
283             i1 = s.indexOf('%', i);
284         }
285         value.append(s.substring(i));
286
287         log.info("Parameter {}: [{}]", name, value);
288         return value.toString();
289     }
290
291     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
292         throws SvcLogicException {
293         log.info("Building {} started", format);
294         long t1 = System.currentTimeMillis();
295
296         template = expandRepeats(ctx, template, 1);
297
298         Map<String, String> mm = new HashMap<>();
299         for (String s : ctx.getAttributeKeySet())
300             mm.put(s, ctx.getAttribute(s));
301
302         StringBuilder ss = new StringBuilder();
303         int i = 0;
304         while (i < template.length()) {
305             int i1 = template.indexOf("${", i);
306             if (i1 < 0) {
307                 ss.append(template.substring(i));
308                 break;
309             }
310
311             int i2 = template.indexOf('}', i1 + 2);
312             if (i2 < 0)
313                 throw new SvcLogicException("Template error: Matching } not found");
314
315             String var1 = template.substring(i1 + 2, i2);
316             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
317             // log.info(" " + var1 + ": " + value1);
318             if (value1 == null || value1.trim().length() == 0) {
319                 // delete the whole element (line)
320                 int i3 = template.lastIndexOf('\n', i1);
321                 if (i3 < 0)
322                     i3 = 0;
323                 int i4 = template.indexOf('\n', i1);
324                 if (i4 < 0)
325                     i4 = template.length();
326
327                 if (i < i3)
328                     ss.append(template.substring(i, i3));
329                 i = i4;
330             } else {
331                 ss.append(template.substring(i, i1)).append(value1);
332                 i = i2 + 1;
333             }
334         }
335
336         String req = format == Format.XML
337                 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
338
339         if (format == Format.JSON)
340             req = XmlJsonUtil.removeLastCommaJson(req);
341
342         long t2 = System.currentTimeMillis();
343         log.info("Building {} completed. Time: {}", format, (t2 - t1));
344
345         return req;
346     }
347
348     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
349         StringBuilder newTemplate = new StringBuilder();
350         int k = 0;
351         while (k < template.length()) {
352             int i1 = template.indexOf("${repeat:", k);
353             if (i1 < 0) {
354                 newTemplate.append(template.substring(k));
355                 break;
356             }
357
358             int i2 = template.indexOf(':', i1 + 9);
359             if (i2 < 0)
360                 throw new SvcLogicException(
361                         "Template error: Context variable name followed by : is required after repeat");
362
363             // Find the closing }, store in i3
364             int nn = 1;
365             int i3 = -1;
366             int i = i2;
367             while (nn > 0 && i < template.length()) {
368                 i3 = template.indexOf('}', i);
369                 if (i3 < 0)
370                     throw new SvcLogicException("Template error: Matching } not found");
371                 int i32 = template.indexOf('{', i);
372                 if (i32 >= 0 && i32 < i3) {
373                     nn++;
374                     i = i32 + 1;
375                 } else {
376                     nn--;
377                     i = i3 + 1;
378                 }
379             }
380
381             String var1 = template.substring(i1 + 9, i2);
382             String value1 = ctx.getAttribute(var1);
383             log.info("     {}:{}", var1, value1);
384             int n = 0;
385             try {
386                 n = Integer.parseInt(value1);
387             } catch (NumberFormatException e) {
388                 log.info("value1 not set or not a number, n will remain set at zero");
389             }
390
391             newTemplate.append(template.substring(k, i1));
392
393             String rpt = template.substring(i2 + 1, i3);
394
395             for (int ii = 0; ii < n; ii++) {
396                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
397                 if (ii == n - 1 && ss.trim().endsWith(",")) {
398                     int i4 = ss.lastIndexOf(',');
399                     if (i4 > 0)
400                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
401                 }
402                 newTemplate.append(ss);
403             }
404
405             k = i3 + 1;
406         }
407
408         if (k == 0)
409             return newTemplate.toString();
410
411         return expandRepeats(ctx, newTemplate.toString(), level + 1);
412     }
413
414     protected String readFile(String fileName) throws SvcLogicException {
415         try {
416             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
417             return new String(encoded, "UTF-8");
418         } catch (IOException | SecurityException e) {
419             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
420         }
421     }
422
423     protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
424
425         ClientConfig config = new DefaultClientConfig();
426         SSLContext ssl = null;
427         if (p.ssl && p.restapiUrl.startsWith("https"))
428             ssl = createSSLContext(p);
429         if (ssl != null) {
430             HostnameVerifier hostnameVerifier = (hostname, session) -> true;
431
432             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
433                     new HTTPSProperties(hostnameVerifier, ssl));
434         }
435
436         logProperties(config.getProperties());
437
438         Client client = Client.create(config);
439         client.setConnectTimeout(5000);
440         if (p.restapiUser != null)
441             client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
442         WebResource webResource = client.resource(p.restapiUrl);
443
444         log.info("Sending request:");
445         log.info(request);
446         long t1 = System.currentTimeMillis();
447
448         HttpResponse r = new HttpResponse();
449         r.code = 200;
450
451         if (!p.skipSending) {
452             String tt = p.format == Format.XML ? "application/xml" : "application/json";
453             String tt1 = tt + ";charset=UTF-8";
454             if (p.contentType != null) {
455                 tt = p.contentType;
456                 tt1 = p.contentType;
457             }
458
459             WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
460
461             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
462                 String[] keyValuePairs = p.customHttpHeaders.split(",");
463                 for (String singlePair : keyValuePairs) {
464                     int equalPosition = singlePair.indexOf('=');
465                     webResourceBuilder.header(singlePair.substring(0, equalPosition),
466                             singlePair.substring(equalPosition + 1, singlePair.length()));
467                 }
468             }
469
470             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
471
472             ClientResponse response;
473
474             try {
475                 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
476             } catch (UniformInterfaceException | ClientHandlerException e) {
477                 throw new SvcLogicException("Exception while sending http request to client "
478                     + e.getLocalizedMessage(), e);
479             }
480
481             r.code = response.getStatus();
482             r.headers = response.getHeaders();
483             EntityTag etag = response.getEntityTag();
484             if (etag != null)
485                 r.message = etag.getValue();
486             if (response.hasEntity() && r.code != 204)
487                 r.body = response.getEntity(String.class);
488         }
489
490         long t2 = System.currentTimeMillis();
491         log.info("Response received. Time: {}", (t2 - t1));
492         log.info("HTTP response code: {}", r.code);
493         log.info("HTTP response message: {}", r.message);
494         logHeaders(r.headers);
495         log.info("HTTP response: {}", r.body);
496
497         return r;
498     }
499
500     protected SSLContext createSSLContext(Parameters p) {
501         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
502             System.setProperty("jsse.enableSNIExtension", "false");
503             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
504             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
505
506             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
507
508             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
509             KeyStore ks = KeyStore.getInstance("PKCS12");
510             char[] pwd = p.keyStorePassword.toCharArray();
511             ks.load(in, pwd);
512             kmf.init(ks, pwd);
513
514             SSLContext ctx = SSLContext.getInstance("TLS");
515             ctx.init(kmf.getKeyManagers(), null, null);
516             return ctx;
517         } catch (Exception e) {
518             log.error("Error creating SSLContext: {}", e.getMessage(), e);
519         }
520         return null;
521     }
522
523     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
524         HttpResponse resp) {
525         resp.code = 500;
526         resp.message = errorMessage;
527         String pp = prefix != null ? prefix + '.' : "";
528         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
529         ctx.setAttribute(pp + "response-message", resp.message);
530     }
531
532     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
533         String pp = prefix != null ? prefix + '.' : "";
534         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
535         ctx.setAttribute(pp + "response-message", r.message);
536     }
537
538     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
539         HttpResponse r = null;
540         try {
541             FileParam p = getFileParameters(paramMap);
542             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
543
544             r = sendHttpData(data, p);
545             setResponseStatus(ctx, p.responsePrefix, r);
546
547         } catch (SvcLogicException | IOException e) {
548             log.error("Error sending the request: {}", e.getMessage(), e);
549
550             r = new HttpResponse();
551             r.code = 500;
552             r.message = e.getMessage();
553             String prefix = parseParam(paramMap, "responsePrefix", false, null);
554             setResponseStatus(ctx, prefix, r);
555         }
556
557         if (r != null && r.code >= 300)
558             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
559     }
560
561     private static class FileParam {
562
563         public String fileName;
564         public String url;
565         public String user;
566         public String password;
567         public HttpMethod httpMethod;
568         public String responsePrefix;
569         public boolean skipSending;
570     }
571
572     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
573         FileParam p = new FileParam();
574         p.fileName = parseParam(paramMap, "fileName", true, null);
575         p.url = parseParam(paramMap, "url", true, null);
576         p.user = parseParam(paramMap, "user", false, null);
577         p.password = parseParam(paramMap, "password", false, null);
578         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
579         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
580         String skipSendingStr = paramMap.get("skipSending");
581         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
582         return p;
583     }
584
585     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
586         Client client = Client.create();
587         client.setConnectTimeout(5000);
588         client.setFollowRedirects(true);
589         if (p.user != null)
590             client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
591         WebResource webResource = client.resource(p.url);
592
593         log.info("Sending file");
594         long t1 = System.currentTimeMillis();
595
596         HttpResponse r = new HttpResponse();
597         r.code = 200;
598
599         if (!p.skipSending) {
600             String tt = "application/octet-stream";
601
602             ClientResponse response;
603             try {
604                 if (p.httpMethod == HttpMethod.POST)
605                     response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
606                 else if (p.httpMethod == HttpMethod.PUT)
607                     response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
608                 else
609                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
610             } catch (UniformInterfaceException | ClientHandlerException e) {
611                 throw new SvcLogicException("Exception while sending http request to client " +
612                     e.getLocalizedMessage(), e);
613             }
614
615             r.code = response.getStatus();
616             r.headers = response.getHeaders();
617             EntityTag etag = response.getEntityTag();
618             if (etag != null)
619                 r.message = etag.getValue();
620             if (response.hasEntity() && r.code != 204)
621                 r.body = response.getEntity(String.class);
622
623             if (r.code == 301) {
624                 String newUrl = response.getHeaders().getFirst("Location");
625
626                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
627
628                 webResource = client.resource(newUrl);
629
630                 try {
631                     if (p.httpMethod == HttpMethod.POST)
632                         response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
633                     else if (p.httpMethod == HttpMethod.PUT)
634                         response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
635                     else
636                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
637                 } catch (UniformInterfaceException | ClientHandlerException e) {
638                     throw new SvcLogicException("Exception while sending http request to client " +
639                         e.getLocalizedMessage(), e);
640                 }
641
642                 r.code = response.getStatus();
643                 etag = response.getEntityTag();
644                 if (etag != null)
645                     r.message = etag.getValue();
646                 if (response.hasEntity() && r.code != 204)
647                     r.body = response.getEntity(String.class);
648             }
649         }
650
651         long t2 = System.currentTimeMillis();
652         log.info("Response received. Time: {}", (t2 - t1));
653         log.info("HTTP response code: {}", r.code);
654         log.info("HTTP response message: {}", r.message);
655         logHeaders(r.headers);
656         log.info("HTTP response: {}", r.body);
657
658         return r;
659     }
660
661     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
662         HttpResponse r;
663         try {
664             UebParam p = getUebParameters(paramMap);
665
666             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
667
668             String req;
669
670             if (p.templateFileName == null) {
671                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
672                 p.templateFileName = defaultUebTemplateFileName;
673             }
674
675             String reqTemplate = readFile(p.templateFileName);
676             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
677             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
678
679             r = postOnUeb(req, p);
680             setResponseStatus(ctx, p.responsePrefix, r);
681             if (r.body != null)
682                 ctx.setAttribute(pp + "httpResponse", r.body);
683
684         } catch (SvcLogicException e) {
685             log.error("Error sending the request: {}", e.getMessage(), e);
686
687             r = new HttpResponse();
688             r.code = 500;
689             r.message = e.getMessage();
690             String prefix = parseParam(paramMap, "responsePrefix", false, null);
691             setResponseStatus(ctx, prefix, r);
692         }
693
694         if (r.code >= 300)
695             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
696     }
697
698     private static class UebParam {
699
700         public String topic;
701         public String templateFileName;
702         public String rootVarName;
703         public String responsePrefix;
704         public boolean skipSending;
705     }
706
707     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
708         UebParam p = new UebParam();
709         p.topic = parseParam(paramMap, "topic", true, null);
710         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
711         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
712         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
713         String skipSendingStr = paramMap.get("skipSending");
714         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
715         return p;
716     }
717
718     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
719         String[] urls = uebServers.split(" ");
720         for (int i = 0; i < urls.length; i++) {
721             if (!urls[i].endsWith("/"))
722                 urls[i] += "/";
723             urls[i] += "events/" + p.topic;
724         }
725
726         Client client = Client.create();
727         client.setConnectTimeout(5000);
728         WebResource webResource = client.resource(urls[0]);
729
730         log.info("UEB URL: {}", urls[0]);
731         log.info("Sending request:");
732         log.info(request);
733         long t1 = System.currentTimeMillis();
734
735         HttpResponse r = new HttpResponse();
736         r.code = 200;
737
738         if (!p.skipSending) {
739             String tt = "application/json";
740             String tt1 = tt + ";charset=UTF-8";
741
742             ClientResponse response;
743
744             try {
745                 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
746             } catch (UniformInterfaceException | ClientHandlerException e) {
747                 throw new SvcLogicException("Exception while posting http request to client " +
748                     e.getLocalizedMessage(), e);
749             }
750
751             r.code = response.getStatus();
752             r.headers = response.getHeaders();
753             if (response.hasEntity())
754                 r.body = response.getEntity(String.class);
755         }
756
757         long t2 = System.currentTimeMillis();
758         log.info("Response received. Time: {}", (t2 - t1));
759         log.info("HTTP response code: {}", r.code);
760         logHeaders(r.headers);
761         log.info("HTTP response:\n {}", r.body);
762
763         return r;
764     }
765
766     protected void logProperties(Map<String, Object> mm) {
767         List<String> ll = new ArrayList<>();
768         for (Object o : mm.keySet())
769             ll.add((String) o);
770         Collections.sort(ll);
771
772         log.info("Properties:");
773         for (String name : ll)
774             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
775     }
776
777     protected void logHeaders(MultivaluedMap<String, String> mm) {
778         log.info("HTTP response headers:");
779
780         if (mm == null)
781             return;
782
783         List<String> ll = new ArrayList<>();
784         for (Object o : mm.keySet())
785             ll.add((String) o);
786         Collections.sort(ll);
787
788         for (String name : ll)
789             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
790     }
791
792     public void setUebServers(String uebServers) {
793         this.uebServers = uebServers;
794     }
795
796     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
797         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
798     }
799 }