Conform ccsdk/sli/plugins to ONAP Style
[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),
448                             singlePair.substring(equalPosition + 1, singlePair.length()));
449                 }
450             }
451
452             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
453
454             ClientResponse response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
455
456             r.code = response.getStatus();
457             r.headers = response.getHeaders();
458             EntityTag etag = response.getEntityTag();
459             if (etag != null)
460                 r.message = etag.getValue();
461             if (response.hasEntity() && r.code != 204)
462                 r.body = response.getEntity(String.class);
463         }
464
465         long t2 = System.currentTimeMillis();
466         log.info("Response received. Time: " + (t2 - t1));
467         log.info("HTTP response code: " + r.code);
468         log.info("HTTP response message: " + r.message);
469         logHeaders(r.headers);
470         log.info("HTTP response: " + r.body);
471
472         return r;
473     }
474
475     protected SSLContext createSSLContext(Parameters p) {
476         try {
477             System.setProperty("jsse.enableSNIExtension", "false");
478             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
479             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
480
481             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
482
483                 @Override
484                 public boolean verify(String string, SSLSession ssls) {
485                     return true;
486                 }
487             });
488
489             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
490             FileInputStream in = new FileInputStream(p.keyStoreFileName);
491             KeyStore ks = KeyStore.getInstance("PKCS12");
492             char[] pwd = p.keyStorePassword.toCharArray();
493             ks.load(in, pwd);
494             kmf.init(ks, pwd);
495
496             SSLContext ctx = SSLContext.getInstance("TLS");
497             ctx.init(kmf.getKeyManagers(), null, null);
498             return ctx;
499         } catch (Exception e) {
500             log.error("Error creating SSLContext: " + e.getMessage(), e);
501         }
502         return null;
503     }
504
505     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage, HttpResponse r) {
506         r = new HttpResponse();
507         r.code = 500;
508         r.message = errorMessage;
509         String pp = prefix != null ? prefix + '.' : "";
510         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
511         ctx.setAttribute(pp + "response-message", r.message);
512     }
513
514     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
515         String pp = prefix != null ? prefix + '.' : "";
516         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
517         ctx.setAttribute(pp + "response-message", r.message);
518     }
519
520     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
521         HttpResponse r = null;
522         try {
523             FileParam p = getFileParameters(paramMap);
524             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
525
526             r = sendHttpData(data, p);
527             setResponseStatus(ctx, p.responsePrefix, r);
528
529         } catch (Exception e) {
530             log.error("Error sending the request: " + e.getMessage(), e);
531
532             r = new HttpResponse();
533             r.code = 500;
534             r.message = e.getMessage();
535             String prefix = parseParam(paramMap, "responsePrefix", false, null);
536             setResponseStatus(ctx, prefix, r);
537         }
538
539         if (r != null && r.code >= 300)
540             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
541     }
542
543     private static class FileParam {
544
545         public String fileName;
546         public String url;
547         public String user;
548         public String password;
549         public HttpMethod httpMethod;
550         public String responsePrefix;
551         public boolean skipSending;
552     }
553
554     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
555         FileParam p = new FileParam();
556         p.fileName = parseParam(paramMap, "fileName", true, null);
557         p.url = parseParam(paramMap, "url", true, null);
558         p.user = parseParam(paramMap, "user", false, null);
559         p.password = parseParam(paramMap, "password", false, null);
560         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
561         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
562         String skipSendingStr = paramMap.get("skipSending");
563         p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
564         return p;
565     }
566
567     protected HttpResponse sendHttpData(byte[] data, FileParam p) {
568         Client client = Client.create();
569         client.setConnectTimeout(5000);
570         client.setFollowRedirects(true);
571         if (p.user != null)
572             client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
573         WebResource webResource = client.resource(p.url);
574
575         log.info("Sending file");
576         long t1 = System.currentTimeMillis();
577
578         HttpResponse r = new HttpResponse();
579         r.code = 200;
580
581         if (!p.skipSending) {
582             String tt = "application/octet-stream";
583
584             ClientResponse response = null;
585             if (p.httpMethod == HttpMethod.POST)
586                 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
587             else if (p.httpMethod == HttpMethod.PUT)
588                 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
589
590             r.code = response.getStatus();
591             r.headers = response.getHeaders();
592             EntityTag etag = response.getEntityTag();
593             if (etag != null)
594                 r.message = etag.getValue();
595             if (response.hasEntity() && r.code != 204)
596                 r.body = response.getEntity(String.class);
597
598             if (r.code == 301) {
599                 String newUrl = response.getHeaders().getFirst("Location");
600
601                 log.info("Got response code 301. Sending same request to URL: " + newUrl);
602
603                 webResource = client.resource(newUrl);
604
605                 if (p.httpMethod == HttpMethod.POST)
606                     response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
607                 else if (p.httpMethod == HttpMethod.PUT)
608                     response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
609
610                 r.code = response.getStatus();
611                 etag = response.getEntityTag();
612                 if (etag != null)
613                     r.message = etag.getValue();
614                 if (response.hasEntity() && r.code != 204)
615                     r.body = response.getEntity(String.class);
616             }
617         }
618
619         long t2 = System.currentTimeMillis();
620         log.info("Response received. Time: " + (t2 - t1));
621         log.info("HTTP response code: " + r.code);
622         log.info("HTTP response message: " + r.message);
623         logHeaders(r.headers);
624         log.info("HTTP response: " + r.body);
625
626         return r;
627     }
628
629     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
630         HttpResponse r = null;
631         try {
632             UebParam p = getUebParameters(paramMap);
633
634             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
635
636             String req = null;
637
638             if (p.templateFileName == null) {
639                 log.info("No template file name specified. Using default UEB template: " + defaultUebTemplateFileName);
640                 p.templateFileName = defaultUebTemplateFileName;
641             }
642
643             String reqTemplate = readFile(p.templateFileName);
644             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
645             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
646
647             r = postOnUeb(req, p);
648             setResponseStatus(ctx, p.responsePrefix, r);
649             if (r.body != null)
650                 ctx.setAttribute(pp + "httpResponse", r.body);
651
652         } catch (Exception e) {
653             log.error("Error sending the request: " + e.getMessage(), e);
654
655             r = new HttpResponse();
656             r.code = 500;
657             r.message = e.getMessage();
658             String prefix = parseParam(paramMap, "responsePrefix", false, null);
659             setResponseStatus(ctx, prefix, r);
660         }
661
662         if (r != null && r.code >= 300)
663             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
664     }
665
666     private static class UebParam {
667
668         public String topic;
669         public String templateFileName;
670         public String rootVarName;
671         public String responsePrefix;
672         public boolean skipSending;
673     }
674
675     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
676         UebParam p = new UebParam();
677         p.topic = parseParam(paramMap, "topic", true, null);
678         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
679         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
680         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
681         String skipSendingStr = paramMap.get("skipSending");
682         p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
683         return p;
684     }
685
686     protected HttpResponse postOnUeb(String request, UebParam p) throws Exception {
687         String[] urls = uebServers.split(" ");
688         for (int i = 0; i < urls.length; i++) {
689             if (!urls[i].endsWith("/"))
690                 urls[i] += "/";
691             urls[i] += "events/" + p.topic;
692         }
693
694         Client client = Client.create();
695         client.setConnectTimeout(5000);
696         WebResource webResource = client.resource(urls[0]);
697
698         log.info("UEB URL: " + urls[0]);
699         log.info("Sending request:");
700         log.info(request);
701         long t1 = System.currentTimeMillis();
702
703         HttpResponse r = new HttpResponse();
704         r.code = 200;
705
706         if (!p.skipSending) {
707             String tt = "application/json";
708             String tt1 = tt + ";charset=UTF-8";
709
710             ClientResponse response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
711
712             r.code = response.getStatus();
713             r.headers = response.getHeaders();
714             if (response.hasEntity())
715                 r.body = response.getEntity(String.class);
716         }
717
718         long t2 = System.currentTimeMillis();
719         log.info("Response received. Time: " + (t2 - t1));
720         log.info("HTTP response code: " + r.code);
721         logHeaders(r.headers);
722         log.info("HTTP response:\n" + r.body);
723
724         return r;
725     }
726
727     protected void logProperties(Map<String, Object> mm) {
728         List<String> ll = new ArrayList<>();
729         for (Object o : mm.keySet())
730             ll.add((String) o);
731         Collections.sort(ll);
732
733         log.info("Properties:");
734         for (String name : ll)
735             log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
736     }
737
738     protected void logHeaders(MultivaluedMap<String, String> mm) {
739         log.info("HTTP response headers:");
740
741         if (mm == null)
742             return;
743
744         List<String> ll = new ArrayList<>();
745         for (Object o : mm.keySet())
746             ll.add((String) o);
747         Collections.sort(ll);
748
749         for (String name : ll)
750             log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
751     }
752
753     public void setUebServers(String uebServers) {
754         this.uebServers = uebServers;
755     }
756
757     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
758         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
759     }
760 }