2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
 
   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
 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  22 package org.onap.ccsdk.sli.plugins.restapicall;
 
  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;
 
  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;
 
  39 import java.util.Map.Entry;
 
  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;
 
  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;
 
  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;
 
  67 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  69     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  71     private String uebServers;
 
  72     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  73     protected RetryPolicyStore retryPolicyStore;
 
  75     protected RetryPolicyStore getRetryPolicyStore() {
 
  76         return retryPolicyStore;
 
  79     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
  80         this.retryPolicyStore = retryPolicyStore;
 
  83     public RestapiCallNode() {
 
  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
 
  91      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
  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>
 
 109      * @param ctx Reference to context memory
 
 110      * @throws SvcLogicException
 
 112      * @see String#split(String, int)
 
 114     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 115         sendRequest(paramMap, ctx, null);
 
 118     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 119             throws SvcLogicException {
 
 121         RetryPolicy retryPolicy = null;
 
 122         HttpResponse r = new HttpResponse();
 
 124             Parameters p = getParameters(paramMap);
 
 125             if (p.partner != null) {
 
 126                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 128             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 131             if (p.templateFileName != null) {
 
 132                 String reqTemplate = readFile(p.templateFileName);
 
 133                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 134             } else if (p.requestBody != null) {
 
 137             r = sendHttpRequest(req, p);
 
 138             setResponseStatus(ctx, p.responsePrefix, r);
 
 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(), ","));
 
 146             if (r.body != null && r.body.trim().length() > 0) {
 
 147                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 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);
 
 157                         for (Map.Entry<String,String> entry : mm.entrySet())
 
 158                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 161         } catch (SvcLogicException e) {
 
 162             boolean shouldRetry = false;
 
 163             if (e.getCause().getCause() instanceof SocketException) {
 
 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);
 
 172                 if (retryCount == null) {
 
 175                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 177                 log.debug(retryMessage);
 
 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);
 
 194                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 195                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 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);
 
 207         if (r != null && r.code >= 300)
 
 208             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 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));
 
 239     private void validateUrl(String restapiUrl) throws SvcLogicException {
 
 241             URI.create(restapiUrl);
 
 242         } catch (IllegalArgumentException e) {
 
 243             throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
 
 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());
 
 255     protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
 
 256             throws SvcLogicException {
 
 257         String s = paramMap.get(name);
 
 259         if (s == null || s.trim().length() == 0) {
 
 262             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 266         StringBuilder value = new StringBuilder();
 
 268         int i1 = s.indexOf('%');
 
 270             int i2 = s.indexOf('%', i1 + 1);
 
 274             String varName = s.substring(i1 + 1, i2);
 
 275             String varValue = System.getenv(varName);
 
 276             if (varValue == null)
 
 277                 varValue = "%" + varName + "%";
 
 279             value.append(s.substring(i, i1));
 
 280             value.append(varValue);
 
 283             i1 = s.indexOf('%', i);
 
 285         value.append(s.substring(i));
 
 287         log.info("Parameter {}: [{}]", name, value);
 
 288         return value.toString();
 
 291     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
 
 292         throws SvcLogicException {
 
 293         log.info("Building {} started", format);
 
 294         long t1 = System.currentTimeMillis();
 
 296         template = expandRepeats(ctx, template, 1);
 
 298         Map<String, String> mm = new HashMap<>();
 
 299         for (String s : ctx.getAttributeKeySet())
 
 300             mm.put(s, ctx.getAttribute(s));
 
 302         StringBuilder ss = new StringBuilder();
 
 304         while (i < template.length()) {
 
 305             int i1 = template.indexOf("${", i);
 
 307                 ss.append(template.substring(i));
 
 311             int i2 = template.indexOf('}', i1 + 2);
 
 313                 throw new SvcLogicException("Template error: Matching } not found");
 
 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);
 
 323                 int i4 = template.indexOf('\n', i1);
 
 325                     i4 = template.length();
 
 328                     ss.append(template.substring(i, i3));
 
 331                 ss.append(template.substring(i, i1)).append(value1);
 
 336         String req = format == Format.XML
 
 337                 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
 
 339         if (format == Format.JSON)
 
 340             req = XmlJsonUtil.removeLastCommaJson(req);
 
 342         long t2 = System.currentTimeMillis();
 
 343         log.info("Building {} completed. Time: {}", format, (t2 - t1));
 
 348     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 349         StringBuilder newTemplate = new StringBuilder();
 
 351         while (k < template.length()) {
 
 352             int i1 = template.indexOf("${repeat:", k);
 
 354                 newTemplate.append(template.substring(k));
 
 358             int i2 = template.indexOf(':', i1 + 9);
 
 360                 throw new SvcLogicException(
 
 361                         "Template error: Context variable name followed by : is required after repeat");
 
 363             // Find the closing }, store in i3
 
 367             while (nn > 0 && i < template.length()) {
 
 368                 i3 = template.indexOf('}', i);
 
 370                     throw new SvcLogicException("Template error: Matching } not found");
 
 371                 int i32 = template.indexOf('{', i);
 
 372                 if (i32 >= 0 && i32 < i3) {
 
 381             String var1 = template.substring(i1 + 9, i2);
 
 382             String value1 = ctx.getAttribute(var1);
 
 383             log.info("     {}:{}", var1, value1);
 
 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");
 
 391             newTemplate.append(template.substring(k, i1));
 
 393             String rpt = template.substring(i2 + 1, i3);
 
 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(',');
 
 400                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 402                 newTemplate.append(ss);
 
 409             return newTemplate.toString();
 
 411         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 414     protected String readFile(String fileName) throws SvcLogicException {
 
 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);
 
 423     protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
 
 425         ClientConfig config = new DefaultClientConfig();
 
 426         SSLContext ssl = null;
 
 427         if (p.ssl && p.restapiUrl.startsWith("https"))
 
 428             ssl = createSSLContext(p);
 
 430             HostnameVerifier hostnameVerifier = (hostname, session) -> true;
 
 432             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
 
 433                     new HTTPSProperties(hostnameVerifier, ssl));
 
 436         logProperties(config.getProperties());
 
 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);
 
 444         log.info("Sending request:");
 
 446         long t1 = System.currentTimeMillis();
 
 448         HttpResponse r = new HttpResponse();
 
 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) {
 
 459             WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
 
 460             if(p.format == Format.NONE){
 
 461                 webResourceBuilder = webResource.header("","");
 
 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()));
 
 473             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 475             ClientResponse response;
 
 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);
 
 484             r.code = response.getStatus();
 
 485             r.headers = response.getHeaders();
 
 486             EntityTag etag = response.getEntityTag();
 
 488                 r.message = etag.getValue();
 
 489             if (response.hasEntity() && r.code != 204)
 
 490                 r.body = response.getEntity(String.class);
 
 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);
 
 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);
 
 509             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 511             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 512             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 513             char[] pwd = p.keyStorePassword.toCharArray();
 
 517             SSLContext ctx = SSLContext.getInstance("TLS");
 
 518             ctx.init(kmf.getKeyManagers(), null, null);
 
 520         } catch (Exception e) {
 
 521             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 526     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 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);
 
 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);
 
 541     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 542         HttpResponse r = null;
 
 544             FileParam p = getFileParameters(paramMap);
 
 545             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 547             r = sendHttpData(data, p);
 
 548             setResponseStatus(ctx, p.responsePrefix, r);
 
 550         } catch (SvcLogicException | IOException e) {
 
 551             log.error("Error sending the request: {}", e.getMessage(), e);
 
 553             r = new HttpResponse();
 
 555             r.message = e.getMessage();
 
 556             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 557             setResponseStatus(ctx, prefix, r);
 
 560         if (r != null && r.code >= 300)
 
 561             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 564     private static class FileParam {
 
 566         public String fileName;
 
 569         public String password;
 
 570         public HttpMethod httpMethod;
 
 571         public String responsePrefix;
 
 572         public boolean skipSending;
 
 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);
 
 588     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
 589         Client client = Client.create();
 
 590         client.setConnectTimeout(5000);
 
 591         client.setFollowRedirects(true);
 
 593             client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
 
 594         WebResource webResource = client.resource(p.url);
 
 596         log.info("Sending file");
 
 597         long t1 = System.currentTimeMillis();
 
 599         HttpResponse r = new HttpResponse();
 
 602         if (!p.skipSending) {
 
 603             String tt = "application/octet-stream";
 
 605             ClientResponse response;
 
 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);
 
 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);
 
 618             r.code = response.getStatus();
 
 619             r.headers = response.getHeaders();
 
 620             EntityTag etag = response.getEntityTag();
 
 622                 r.message = etag.getValue();
 
 623             if (response.hasEntity() && r.code != 204)
 
 624                 r.body = response.getEntity(String.class);
 
 627                 String newUrl = response.getHeaders().getFirst("Location");
 
 629                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
 631                 webResource = client.resource(newUrl);
 
 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);
 
 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);
 
 645                 r.code = response.getStatus();
 
 646                 etag = response.getEntityTag();
 
 648                     r.message = etag.getValue();
 
 649                 if (response.hasEntity() && r.code != 204)
 
 650                     r.body = response.getEntity(String.class);
 
 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);
 
 664     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 667             UebParam p = getUebParameters(paramMap);
 
 669             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 673             if (p.templateFileName == null) {
 
 674                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
 675                 p.templateFileName = defaultUebTemplateFileName;
 
 678             String reqTemplate = readFile(p.templateFileName);
 
 679             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 680             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 682             r = postOnUeb(req, p);
 
 683             setResponseStatus(ctx, p.responsePrefix, r);
 
 685                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 687         } catch (SvcLogicException e) {
 
 688             log.error("Error sending the request: {}", e.getMessage(), e);
 
 690             r = new HttpResponse();
 
 692             r.message = e.getMessage();
 
 693             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 694             setResponseStatus(ctx, prefix, r);
 
 698             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 701     private static class UebParam {
 
 704         public String templateFileName;
 
 705         public String rootVarName;
 
 706         public String responsePrefix;
 
 707         public boolean skipSending;
 
 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);
 
 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("/"))
 
 726             urls[i] += "events/" + p.topic;
 
 729         Client client = Client.create();
 
 730         client.setConnectTimeout(5000);
 
 731         WebResource webResource = client.resource(urls[0]);
 
 733         log.info("UEB URL: {}", urls[0]);
 
 734         log.info("Sending request:");
 
 736         long t1 = System.currentTimeMillis();
 
 738         HttpResponse r = new HttpResponse();
 
 741         if (!p.skipSending) {
 
 742             String tt = "application/json";
 
 743             String tt1 = tt + ";charset=UTF-8";
 
 745             ClientResponse response;
 
 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);
 
 754             r.code = response.getStatus();
 
 755             r.headers = response.getHeaders();
 
 756             if (response.hasEntity())
 
 757                 r.body = response.getEntity(String.class);
 
 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);
 
 769     protected void logProperties(Map<String, Object> mm) {
 
 770         List<String> ll = new ArrayList<>();
 
 771         for (Object o : mm.keySet())
 
 773         Collections.sort(ll);
 
 775         log.info("Properties:");
 
 776         for (String name : ll)
 
 777             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 780     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 781         log.info("HTTP response headers:");
 
 786         List<String> ll = new ArrayList<>();
 
 787         for (Object o : mm.keySet())
 
 789         Collections.sort(ll);
 
 791         for (String name : ll)
 
 792             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 795     public void setUebServers(String uebServers) {
 
 796         this.uebServers = uebServers;
 
 799     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 800         this.defaultUebTemplateFileName = defaultUebTemplateFileName;