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