Changes to RestApiCall plugin
[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             }
135             r = sendHttpRequest(req, p);
136             setResponseStatus(ctx, p.responsePrefix, r);
137
138             if (p.dumpHeaders && r.headers != null) {
139                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
140                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
141                 }
142             }
143
144             if (r.body != null && r.body.trim().length() > 0) {
145                 ctx.setAttribute(pp + "httpResponse", r.body);
146
147                 if (p.convertResponse) {
148                     Map<String, String> mm = null;
149                     if (p.format == Format.XML)
150                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
151                     else if (p.format == Format.JSON)
152                         mm = JsonParser.convertToProperties(r.body);
153
154                     if (mm != null)
155                         for (Map.Entry<String,String> entry : mm.entrySet())
156                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
157                 }
158             }
159         } catch (SvcLogicException e) {
160             boolean shouldRetry = false;
161             if (e.getCause().getCause() instanceof SocketException) {
162                 shouldRetry = true;
163             }
164
165             log.error("Error sending the request: " + e.getMessage(), e);
166             String prefix = parseParam(paramMap, "responsePrefix", false, null);
167             if (retryPolicy == null || shouldRetry == false) {
168                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
169             } else {
170                 if (retryCount == null) {
171                     retryCount = 0;
172                 }
173                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
174                         " maximum retries.";
175                 log.debug(retryMessage);
176                 try {
177                     retryCount = retryCount + 1;
178                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
179                         URI uri = new URI(paramMap.get("restapiUrl"));
180                         String hostname = uri.getHost();
181                         String retryString = retryPolicy.getNextHostName(uri.toString());
182                         URI uriTwo = new URI(retryString);
183                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
184                                 uriTwo.getScheme()).build();
185                         paramMap.put("restapiUrl", retryUri.toString());
186                         log.debug("URL was set to {}", retryUri.toString());
187                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
188                             hostname, retryString);
189                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
190                         sendRequest(paramMap, ctx, retryCount);
191                     } else {
192                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
193                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
194                     }
195                 } catch (Exception ex) {
196                     log.error("Could not attempt retry.", ex);
197                     String retryErrorMessage =
198                             "Retry attempt has failed. No further retry shall be attempted, calling " +
199                                 "setFailureResponseStatus.";
200                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
201                 }
202             }
203         }
204
205         if (r != null && r.code >= 300)
206             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
207     }
208
209     protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
210         Parameters p = new Parameters();
211         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
212         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
213         validateUrl(p.restapiUrl);
214         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
215         p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
216         p.contentType = parseParam(paramMap, "contentType", false, null);
217         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
218         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
219         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
220         p.listNameList = getListNameList(paramMap);
221         String skipSendingStr = paramMap.get("skipSending");
222         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
223         p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
224         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
225         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
226         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
227         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
228         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
229                 p.keyStorePassword != null;
230         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
231         p.partner = parseParam(paramMap, "partner", false, null);
232         p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
233         return p;
234     }
235
236     private void validateUrl(String restapiUrl) throws SvcLogicException {
237         try {
238             URI.create(restapiUrl);
239         } catch (IllegalArgumentException e) {
240             throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
241         }
242     }
243
244     protected Set<String> getListNameList(Map<String, String> paramMap) {
245         Set<String> ll = new HashSet<>();
246         for (Map.Entry<String,String> entry : paramMap.entrySet())
247             if (entry.getKey().startsWith("listName"))
248                 ll.add(entry.getValue());
249         return ll;
250     }
251
252     protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
253             throws SvcLogicException {
254         String s = paramMap.get(name);
255
256         if (s == null || s.trim().length() == 0) {
257             if (!required)
258                 return def;
259             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
260         }
261
262         s = s.trim();
263         StringBuilder value = new StringBuilder();
264         int i = 0;
265         int i1 = s.indexOf('%');
266         while (i1 >= 0) {
267             int i2 = s.indexOf('%', i1 + 1);
268             if (i2 < 0)
269                 break;
270
271             String varName = s.substring(i1 + 1, i2);
272             String varValue = System.getenv(varName);
273             if (varValue == null)
274                 varValue = "%" + varName + "%";
275
276             value.append(s.substring(i, i1));
277             value.append(varValue);
278
279             i = i2 + 1;
280             i1 = s.indexOf('%', i);
281         }
282         value.append(s.substring(i));
283
284         log.info("Parameter {}: [{}]", name, value);
285         return value.toString();
286     }
287
288     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
289         throws SvcLogicException {
290         log.info("Building {} started", format);
291         long t1 = System.currentTimeMillis();
292
293         template = expandRepeats(ctx, template, 1);
294
295         Map<String, String> mm = new HashMap<>();
296         for (String s : ctx.getAttributeKeySet())
297             mm.put(s, ctx.getAttribute(s));
298
299         StringBuilder ss = new StringBuilder();
300         int i = 0;
301         while (i < template.length()) {
302             int i1 = template.indexOf("${", i);
303             if (i1 < 0) {
304                 ss.append(template.substring(i));
305                 break;
306             }
307
308             int i2 = template.indexOf('}', i1 + 2);
309             if (i2 < 0)
310                 throw new SvcLogicException("Template error: Matching } not found");
311
312             String var1 = template.substring(i1 + 2, i2);
313             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
314             // log.info(" " + var1 + ": " + value1);
315             if (value1 == null || value1.trim().length() == 0) {
316                 // delete the whole element (line)
317                 int i3 = template.lastIndexOf('\n', i1);
318                 if (i3 < 0)
319                     i3 = 0;
320                 int i4 = template.indexOf('\n', i1);
321                 if (i4 < 0)
322                     i4 = template.length();
323
324                 if (i < i3)
325                     ss.append(template.substring(i, i3));
326                 i = i4;
327             } else {
328                 ss.append(template.substring(i, i1)).append(value1);
329                 i = i2 + 1;
330             }
331         }
332
333         String req = format == Format.XML
334                 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
335
336         if (format == Format.JSON)
337             req = XmlJsonUtil.removeLastCommaJson(req);
338
339         long t2 = System.currentTimeMillis();
340         log.info("Building {} completed. Time: {}", format, (t2 - t1));
341
342         return req;
343     }
344
345     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
346         StringBuilder newTemplate = new StringBuilder();
347         int k = 0;
348         while (k < template.length()) {
349             int i1 = template.indexOf("${repeat:", k);
350             if (i1 < 0) {
351                 newTemplate.append(template.substring(k));
352                 break;
353             }
354
355             int i2 = template.indexOf(':', i1 + 9);
356             if (i2 < 0)
357                 throw new SvcLogicException(
358                         "Template error: Context variable name followed by : is required after repeat");
359
360             // Find the closing }, store in i3
361             int nn = 1;
362             int i3 = -1;
363             int i = i2;
364             while (nn > 0 && i < template.length()) {
365                 i3 = template.indexOf('}', i);
366                 if (i3 < 0)
367                     throw new SvcLogicException("Template error: Matching } not found");
368                 int i32 = template.indexOf('{', i);
369                 if (i32 >= 0 && i32 < i3) {
370                     nn++;
371                     i = i32 + 1;
372                 } else {
373                     nn--;
374                     i = i3 + 1;
375                 }
376             }
377
378             String var1 = template.substring(i1 + 9, i2);
379             String value1 = ctx.getAttribute(var1);
380             log.info("     {}:{}", var1, value1);
381             int n = 0;
382             try {
383                 n = Integer.parseInt(value1);
384             } catch (NumberFormatException e) {
385                 throw new SvcLogicException("Invalid input of repeat interval, should be an integer value " +
386                     e.getLocalizedMessage(), e);
387             }
388
389             newTemplate.append(template.substring(k, i1));
390
391             String rpt = template.substring(i2 + 1, i3);
392
393             for (int ii = 0; ii < n; ii++) {
394                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
395                 if (ii == n - 1 && ss.trim().endsWith(",")) {
396                     int i4 = ss.lastIndexOf(',');
397                     if (i4 > 0)
398                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
399                 }
400                 newTemplate.append(ss);
401             }
402
403             k = i3 + 1;
404         }
405
406         if (k == 0)
407             return newTemplate.toString();
408
409         return expandRepeats(ctx, newTemplate.toString(), level + 1);
410     }
411
412     protected String readFile(String fileName) throws SvcLogicException {
413         try {
414             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
415             return new String(encoded, "UTF-8");
416         } catch (IOException | SecurityException e) {
417             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
418         }
419     }
420
421     protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
422
423         ClientConfig config = new DefaultClientConfig();
424         SSLContext ssl = null;
425         if (p.ssl && p.restapiUrl.startsWith("https"))
426             ssl = createSSLContext(p);
427         if (ssl != null) {
428             HostnameVerifier hostnameVerifier = (hostname, session) -> true;
429
430             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
431                     new HTTPSProperties(hostnameVerifier, ssl));
432         }
433
434         logProperties(config.getProperties());
435
436         Client client = Client.create(config);
437         client.setConnectTimeout(5000);
438         if (p.restapiUser != null)
439             client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
440         WebResource webResource = client.resource(p.restapiUrl);
441
442         log.info("Sending request:");
443         log.info(request);
444         long t1 = System.currentTimeMillis();
445
446         HttpResponse r = new HttpResponse();
447         r.code = 200;
448
449         if (!p.skipSending) {
450             String tt = p.format == Format.XML ? "application/xml" : "application/json";
451             String tt1 = tt + ";charset=UTF-8";
452             if (p.contentType != null) {
453                 tt = p.contentType;
454                 tt1 = p.contentType;
455             }
456
457             WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
458
459             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
460                 String[] keyValuePairs = p.customHttpHeaders.split(",");
461                 for (String singlePair : keyValuePairs) {
462                     int equalPosition = singlePair.indexOf('=');
463                     webResourceBuilder.header(singlePair.substring(0, equalPosition),
464                             singlePair.substring(equalPosition + 1, singlePair.length()));
465                 }
466             }
467
468             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
469
470             ClientResponse response;
471
472             try {
473                 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
474             } catch (UniformInterfaceException | ClientHandlerException e) {
475                 throw new SvcLogicException("Exception while sending http request to client "
476                     + e.getLocalizedMessage(), e);
477             }
478
479             r.code = response.getStatus();
480             r.headers = response.getHeaders();
481             EntityTag etag = response.getEntityTag();
482             if (etag != null)
483                 r.message = etag.getValue();
484             if (response.hasEntity() && r.code != 204)
485                 r.body = response.getEntity(String.class);
486         }
487
488         long t2 = System.currentTimeMillis();
489         log.info("Response received. Time: {}", (t2 - t1));
490         log.info("HTTP response code: {}", r.code);
491         log.info("HTTP response message: {}", r.message);
492         logHeaders(r.headers);
493         log.info("HTTP response: {}", r.body);
494
495         return r;
496     }
497
498     protected SSLContext createSSLContext(Parameters p) {
499         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
500             System.setProperty("jsse.enableSNIExtension", "false");
501             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
502             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
503
504             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
505
506             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
507             KeyStore ks = KeyStore.getInstance("PKCS12");
508             char[] pwd = p.keyStorePassword.toCharArray();
509             ks.load(in, pwd);
510             kmf.init(ks, pwd);
511
512             SSLContext ctx = SSLContext.getInstance("TLS");
513             ctx.init(kmf.getKeyManagers(), null, null);
514             return ctx;
515         } catch (Exception e) {
516             log.error("Error creating SSLContext: {}", e.getMessage(), e);
517         }
518         return null;
519     }
520
521     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
522         HttpResponse resp) {
523         resp.code = 500;
524         resp.message = errorMessage;
525         String pp = prefix != null ? prefix + '.' : "";
526         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
527         ctx.setAttribute(pp + "response-message", resp.message);
528     }
529
530     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
531         String pp = prefix != null ? prefix + '.' : "";
532         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
533         ctx.setAttribute(pp + "response-message", r.message);
534     }
535
536     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
537         HttpResponse r = null;
538         try {
539             FileParam p = getFileParameters(paramMap);
540             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
541
542             r = sendHttpData(data, p);
543             setResponseStatus(ctx, p.responsePrefix, r);
544
545         } catch (SvcLogicException | IOException e) {
546             log.error("Error sending the request: {}", e.getMessage(), e);
547
548             r = new HttpResponse();
549             r.code = 500;
550             r.message = e.getMessage();
551             String prefix = parseParam(paramMap, "responsePrefix", false, null);
552             setResponseStatus(ctx, prefix, r);
553         }
554
555         if (r != null && r.code >= 300)
556             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
557     }
558
559     private static class FileParam {
560
561         public String fileName;
562         public String url;
563         public String user;
564         public String password;
565         public HttpMethod httpMethod;
566         public String responsePrefix;
567         public boolean skipSending;
568     }
569
570     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
571         FileParam p = new FileParam();
572         p.fileName = parseParam(paramMap, "fileName", true, null);
573         p.url = parseParam(paramMap, "url", true, null);
574         p.user = parseParam(paramMap, "user", false, null);
575         p.password = parseParam(paramMap, "password", false, null);
576         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
577         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
578         String skipSendingStr = paramMap.get("skipSending");
579         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
580         return p;
581     }
582
583     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
584         Client client = Client.create();
585         client.setConnectTimeout(5000);
586         client.setFollowRedirects(true);
587         if (p.user != null)
588             client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
589         WebResource webResource = client.resource(p.url);
590
591         log.info("Sending file");
592         long t1 = System.currentTimeMillis();
593
594         HttpResponse r = new HttpResponse();
595         r.code = 200;
596
597         if (!p.skipSending) {
598             String tt = "application/octet-stream";
599
600             ClientResponse response;
601             try {
602                 if (p.httpMethod == HttpMethod.POST)
603                     response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
604                 else if (p.httpMethod == HttpMethod.PUT)
605                     response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
606                 else
607                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
608             } catch (UniformInterfaceException | ClientHandlerException e) {
609                 throw new SvcLogicException("Exception while sending http request to client " +
610                     e.getLocalizedMessage(), e);
611             }
612
613             r.code = response.getStatus();
614             r.headers = response.getHeaders();
615             EntityTag etag = response.getEntityTag();
616             if (etag != null)
617                 r.message = etag.getValue();
618             if (response.hasEntity() && r.code != 204)
619                 r.body = response.getEntity(String.class);
620
621             if (r.code == 301) {
622                 String newUrl = response.getHeaders().getFirst("Location");
623
624                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
625
626                 webResource = client.resource(newUrl);
627
628                 try {
629                     if (p.httpMethod == HttpMethod.POST)
630                         response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
631                     else if (p.httpMethod == HttpMethod.PUT)
632                         response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
633                     else
634                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
635                 } catch (UniformInterfaceException | ClientHandlerException e) {
636                     throw new SvcLogicException("Exception while sending http request to client " +
637                         e.getLocalizedMessage(), e);
638                 }
639
640                 r.code = response.getStatus();
641                 etag = response.getEntityTag();
642                 if (etag != null)
643                     r.message = etag.getValue();
644                 if (response.hasEntity() && r.code != 204)
645                     r.body = response.getEntity(String.class);
646             }
647         }
648
649         long t2 = System.currentTimeMillis();
650         log.info("Response received. Time: {}", (t2 - t1));
651         log.info("HTTP response code: {}", r.code);
652         log.info("HTTP response message: {}", r.message);
653         logHeaders(r.headers);
654         log.info("HTTP response: {}", r.body);
655
656         return r;
657     }
658
659     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
660         HttpResponse r;
661         try {
662             UebParam p = getUebParameters(paramMap);
663
664             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
665
666             String req;
667
668             if (p.templateFileName == null) {
669                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
670                 p.templateFileName = defaultUebTemplateFileName;
671             }
672
673             String reqTemplate = readFile(p.templateFileName);
674             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
675             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
676
677             r = postOnUeb(req, p);
678             setResponseStatus(ctx, p.responsePrefix, r);
679             if (r.body != null)
680                 ctx.setAttribute(pp + "httpResponse", r.body);
681
682         } catch (SvcLogicException e) {
683             log.error("Error sending the request: {}", e.getMessage(), e);
684
685             r = new HttpResponse();
686             r.code = 500;
687             r.message = e.getMessage();
688             String prefix = parseParam(paramMap, "responsePrefix", false, null);
689             setResponseStatus(ctx, prefix, r);
690         }
691
692         if (r.code >= 300)
693             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
694     }
695
696     private static class UebParam {
697
698         public String topic;
699         public String templateFileName;
700         public String rootVarName;
701         public String responsePrefix;
702         public boolean skipSending;
703     }
704
705     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
706         UebParam p = new UebParam();
707         p.topic = parseParam(paramMap, "topic", true, null);
708         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
709         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
710         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
711         String skipSendingStr = paramMap.get("skipSending");
712         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
713         return p;
714     }
715
716     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
717         String[] urls = uebServers.split(" ");
718         for (int i = 0; i < urls.length; i++) {
719             if (!urls[i].endsWith("/"))
720                 urls[i] += "/";
721             urls[i] += "events/" + p.topic;
722         }
723
724         Client client = Client.create();
725         client.setConnectTimeout(5000);
726         WebResource webResource = client.resource(urls[0]);
727
728         log.info("UEB URL: {}", urls[0]);
729         log.info("Sending request:");
730         log.info(request);
731         long t1 = System.currentTimeMillis();
732
733         HttpResponse r = new HttpResponse();
734         r.code = 200;
735
736         if (!p.skipSending) {
737             String tt = "application/json";
738             String tt1 = tt + ";charset=UTF-8";
739
740             ClientResponse response;
741
742             try {
743                 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
744             } catch (UniformInterfaceException | ClientHandlerException e) {
745                 throw new SvcLogicException("Exception while posting http request to client " +
746                     e.getLocalizedMessage(), e);
747             }
748
749             r.code = response.getStatus();
750             r.headers = response.getHeaders();
751             if (response.hasEntity())
752                 r.body = response.getEntity(String.class);
753         }
754
755         long t2 = System.currentTimeMillis();
756         log.info("Response received. Time: {}", (t2 - t1));
757         log.info("HTTP response code: {}", r.code);
758         logHeaders(r.headers);
759         log.info("HTTP response:\n {}", r.body);
760
761         return r;
762     }
763
764     protected void logProperties(Map<String, Object> mm) {
765         List<String> ll = new ArrayList<>();
766         for (Object o : mm.keySet())
767             ll.add((String) o);
768         Collections.sort(ll);
769
770         log.info("Properties:");
771         for (String name : ll)
772             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
773     }
774
775     protected void logHeaders(MultivaluedMap<String, String> mm) {
776         log.info("HTTP response headers:");
777
778         if (mm == null)
779             return;
780
781         List<String> ll = new ArrayList<>();
782         for (Object o : mm.keySet())
783             ll.add((String) o);
784         Collections.sort(ll);
785
786         for (String name : ll)
787             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
788     }
789
790     public void setUebServers(String uebServers) {
791         this.uebServers = uebServers;
792     }
793
794     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
795         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
796     }
797 }