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