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