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