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 java.io.FileInputStream;
 
  26 import java.nio.file.Files;
 
  27 import java.nio.file.Paths;
 
  28 import java.security.KeyStore;
 
  29 import java.util.ArrayList;
 
  30 import java.util.Collections;
 
  31 import java.util.HashMap;
 
  32 import java.util.HashSet;
 
  33 import java.util.List;
 
  35 import java.util.Map.Entry;
 
  38 import javax.net.ssl.HostnameVerifier;
 
  39 import javax.net.ssl.HttpsURLConnection;
 
  40 import javax.net.ssl.KeyManagerFactory;
 
  41 import javax.net.ssl.SSLContext;
 
  42 import javax.net.ssl.SSLSession;
 
  43 import javax.ws.rs.core.EntityTag;
 
  44 import javax.ws.rs.core.MultivaluedMap;
 
  45 import javax.ws.rs.core.UriBuilder;
 
  47 import org.apache.commons.lang3.StringUtils;
 
  48 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  49 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  50 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
 
  51 import org.slf4j.Logger;
 
  52 import org.slf4j.LoggerFactory;
 
  54 import com.sun.jersey.api.client.Client;
 
  55 import com.sun.jersey.api.client.ClientResponse;
 
  56 import com.sun.jersey.api.client.WebResource;
 
  57 import com.sun.jersey.api.client.config.ClientConfig;
 
  58 import com.sun.jersey.api.client.config.DefaultClientConfig;
 
  59 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
 
  60 import com.sun.jersey.client.urlconnection.HTTPSProperties;
 
  62 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  64         private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  66         private String uebServers;
 
  67         private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  68         protected RetryPolicyStore retryPolicyStore;
 
  70         protected RetryPolicyStore getRetryPolicyStore() {
 
  71                 return retryPolicyStore;
 
  74         public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
  75                 this.retryPolicyStore = retryPolicyStore;
 
  78         public RestapiCallNode() {
 
  83      * Allows Directed Graphs  the ability to interact with REST APIs.
 
  84      * @param parameters HashMap<String,String> of parameters passed by the DG to this function
 
  86      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
  88      *      <tr><td>templateFileName</td><td>Optional</td><td>full path to template file that can be used to build a request</td><td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td></tr>
 
  89      *      <tr><td>restapiUrl</td><td>Mandatory</td><td>url to send the request to</td><td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td></tr>
 
  90      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
 
  91      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
 
  92      *      <tr><td>contentType</td><td>Optional</td><td>http content type to set in the http header</td><td>usually application/json or application/xml</td></tr>
 
  93      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
 
  94      *      <tr><td>httpMethod</td><td>Optional</td><td>http method to use when sending the request</td><td>get post put delete patch</td></tr>
 
  95      *      <tr><td>responsePrefix</td><td>Optional</td><td>location the response will be written to in context memory</td><td>tmp.restapi.result</td></tr>
 
  96      *      <tr><td>listName[i]</td><td>Optional</td><td>Used for processing XML responses with repeating elements.</td>vpn-information.vrf-details<td></td></tr>
 
  97      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
 
  98      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
 
  99      *      <tr><td>customHttpHeaders</td><td>Optional</td><td>a list additional http headers to be passed in, follow the format in the example</td><td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td></tr>
 
 100      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
 
 101      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
 
 104      * @param ctx Reference to context memory
 
 105      * @throws SvcLogicException
 
 107      * @see String#split(String, int)
 
 109         public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 110                 sendRequest(paramMap, ctx, null);
 
 113         public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 114                 throws SvcLogicException {
 
 116                 RetryPolicy retryPolicy = null;
 
 117                 HttpResponse r = null;
 
 119                         Parameters p = getParameters(paramMap);
 
 120                         if (p.partner != null) {
 
 121                                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 123                         String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 126                         if (p.templateFileName != null) {
 
 127                                 String reqTemplate = readFile(p.templateFileName);
 
 128                                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 130                         r = sendHttpRequest(req, p);
 
 131                         setResponseStatus(ctx, p.responsePrefix, r);
 
 133                         if (p.dumpHeaders && r.headers != null) {
 
 134                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 135                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 139                         if (r.body != null && r.body.trim().length() > 0) {
 
 140                                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 142                                 if (p.convertResponse) {
 
 143                                         Map<String, String> mm = null;
 
 144                                         if (p.format == Format.XML)
 
 145                                                 mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 146                                         else if (p.format == Format.JSON)
 
 147                                                 mm = JsonParser.convertToProperties(r.body);
 
 150                                                 for (String key : mm.keySet())
 
 151                                                         ctx.setAttribute(pp + key, mm.get(key));
 
 154                 } catch (Exception e) {
 
 155                         boolean shouldRetry = false;
 
 156                         if (e.getCause() instanceof java.net.SocketException) {
 
 160                         log.error("Error sending the request: " + e.getMessage(), e);
 
 161                         String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 162                         if (retryPolicy == null || shouldRetry == false) {
 
 163                                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 165                                 if (retryCount == null) {
 
 168                                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 170                                 log.debug(retryMessage);
 
 172                                         retryCount = retryCount + 1;
 
 173                                         if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 174                                                 URI uri = new URI(paramMap.get("restapiUrl"));
 
 175                                                 String hostname = uri.getHost();
 
 176                                                 String retryString = retryPolicy.getNextHostName((uri.toString()));
 
 177                                                 URI uriTwo = new URI(retryString);
 
 178                                                 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
 
 179                                                         uriTwo.getScheme()).build();
 
 180                                                 paramMap.put("restapiUrl", retryUri.toString());
 
 181                                                 log.debug("URL was set to " + retryUri.toString());
 
 182                                                 log.debug("Failed to communicate with host " + hostname +
 
 183                                                         ". Request will be re-attempted using the host " + retryString + ".");
 
 184                                                 log.debug("This is retry attempt " + retryCount + " out of " + retryPolicy.getMaximumRetries());
 
 185                                                 sendRequest(paramMap, ctx, retryCount);
 
 187                                                 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 188                                                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 190                                 } catch (Exception ex) {
 
 191                                         log.error("Could not attempt retry.", ex);
 
 192                                         String retryErrorMessage =
 
 193                                                 "Retry attempt has failed. No further retry shall be attempted, calling setFailureResponseStatus.";
 
 194                                         setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 199                 if (r != null && r.code >= 300)
 
 200                         throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 203         protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 204                 Parameters p = new Parameters();
 
 205                 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 206                 p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
 
 207                 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
 
 208                 p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
 
 209                 p.contentType = parseParam(paramMap, "contentType", false, null);
 
 210                 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
 
 211                 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 212                 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 213                 p.listNameList = getListNameList(paramMap);
 
 214                 String skipSendingStr = paramMap.get("skipSending");
 
 215                 p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
 
 216                 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
 
 217                 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
 
 218                 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
 
 219                 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
 
 220                 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
 
 221                 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
 
 222                         p.keyStorePassword != null;
 
 223                 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
 
 224                 p.partner = parseParam(paramMap, "partner", false, null);
 
 225             p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
 
 229         protected Set<String> getListNameList(Map<String, String> paramMap) {
 
 230                 Set<String> ll = new HashSet<String>();
 
 231                 for (String key : paramMap.keySet())
 
 232                         if (key.startsWith("listName"))
 
 233                                 ll.add(paramMap.get(key));
 
 237         protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
 
 238                 throws SvcLogicException {
 
 239                 String s = paramMap.get(name);
 
 241                 if (s == null || s.trim().length() == 0) {
 
 244                         throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 250                 int i1 = s.indexOf('%');
 
 252                         int i2 = s.indexOf('%', i1 + 1);
 
 256                         String varName = s.substring(i1 + 1, i2);
 
 257                         String varValue = System.getenv(varName);
 
 258                         if (varValue == null)
 
 259                                 varValue = "%" + varName + "%";
 
 261                         value += s.substring(i, i1);
 
 265                         i1 = s.indexOf('%', i);
 
 267                 value += s.substring(i);
 
 269                 log.info("Parameter " + name + ": [" + value + "]");
 
 273         protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) {
 
 274                 log.info("Building " + format + " started");
 
 275                 long t1 = System.currentTimeMillis();
 
 277                 template = expandRepeats(ctx, template, 1);
 
 279                 Map<String, String> mm = new HashMap<>();
 
 280                 for (String s : ctx.getAttributeKeySet())
 
 281                         mm.put(s, ctx.getAttribute(s));
 
 283                 StringBuilder ss = new StringBuilder();
 
 285                 while (i < template.length()) {
 
 286                         int i1 = template.indexOf("${", i);
 
 288                                 ss.append(template.substring(i));
 
 292                         int i2 = template.indexOf('}', i1 + 2);
 
 294                                 throw new RuntimeException("Template error: Matching } not found");
 
 296                         String var1 = template.substring(i1 + 2, i2);
 
 297                         String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 298                         // log.info(" " + var1 + ": " + value1);
 
 299                         if (value1 == null || value1.trim().length() == 0) {
 
 300                                 // delete the whole element (line)
 
 301                                 int i3 = template.lastIndexOf('\n', i1);
 
 304                                 int i4 = template.indexOf('\n', i1);
 
 306                                         i4 = template.length();
 
 309                                         ss.append(template.substring(i, i3));
 
 312                                 ss.append(template.substring(i, i1)).append(value1);
 
 317                 String req = format == Format.XML
 
 318                         ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
 
 320                 if (format == Format.JSON)
 
 321                         req = XmlJsonUtil.removeLastCommaJson(req);
 
 323                 long t2 = System.currentTimeMillis();
 
 324                 log.info("Building " + format + " completed. Time: " + (t2 - t1));
 
 329         protected String expandRepeats(SvcLogicContext ctx, String template, int level) {
 
 330                 StringBuilder newTemplate = new StringBuilder();
 
 332                 while (k < template.length()) {
 
 333                         int i1 = template.indexOf("${repeat:", k);
 
 335                                 newTemplate.append(template.substring(k));
 
 339                         int i2 = template.indexOf(':', i1 + 9);
 
 341                                 throw new RuntimeException(
 
 342                                         "Template error: Context variable name followed by : is required after repeat");
 
 344                         // Find the closing }, store in i3
 
 348                         while (nn > 0 && i < template.length()) {
 
 349                                 i3 = template.indexOf('}', i);
 
 351                                         throw new RuntimeException("Template error: Matching } not found");
 
 352                                 int i32 = template.indexOf('{', i);
 
 353                                 if (i32 >= 0 && i32 < i3) {
 
 362                         String var1 = template.substring(i1 + 9, i2);
 
 363                         String value1 = ctx.getAttribute(var1);
 
 364                         log.info("     " + var1 + ": " + value1);
 
 367                                 n = Integer.parseInt(value1);
 
 368                         } catch (Exception e) {
 
 372                         newTemplate.append(template.substring(k, i1));
 
 374                         String rpt = template.substring(i2 + 1, i3);
 
 376                         for (int ii = 0; ii < n; ii++) {
 
 377                                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 378                                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 379                                         int i4 = ss.lastIndexOf(',');
 
 381                                                 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 383                                 newTemplate.append(ss);
 
 390                         return newTemplate.toString();
 
 392                 return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 395         protected String readFile(String fileName) throws Exception {
 
 396                 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 397                 return new String(encoded, "UTF-8");
 
 400         protected HttpResponse sendHttpRequest(String request, Parameters p) throws Exception {
 
 401                 ClientConfig config = new DefaultClientConfig();
 
 402                 SSLContext ssl = null;
 
 403                 if (p.ssl && p.restapiUrl.startsWith("https"))
 
 404                         ssl = createSSLContext(p);
 
 406                         HostnameVerifier hostnameVerifier = new HostnameVerifier() {
 
 409                                 public boolean verify(String hostname, SSLSession session) {
 
 414                         config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
 
 415                                 new HTTPSProperties(hostnameVerifier, ssl));
 
 418                 logProperties(config.getProperties());
 
 420                 Client client = Client.create(config);
 
 421                 client.setConnectTimeout(5000);
 
 422                 if (p.restapiUser != null)
 
 423                         client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
 
 424                 WebResource webResource = client.resource(p.restapiUrl);
 
 426                 log.info("Sending request:");
 
 428                 long t1 = System.currentTimeMillis();
 
 430                 HttpResponse r = new HttpResponse();
 
 433                 if (!p.skipSending) {
 
 434                         String tt = p.format == Format.XML ? "application/xml" : "application/json";
 
 435                         String tt1 = tt + ";charset=UTF-8";
 
 436                         if (p.contentType != null) {
 
 441                         WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
 
 443             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 444                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 445                 for (String singlePair : keyValuePairs) {
 
 446                     int equalPosition = singlePair.indexOf('=');
 
 447                     webResourceBuilder.header(singlePair.substring(0, equalPosition), singlePair.substring(equalPosition + 1, singlePair.length()));
 
 451             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 453                         ClientResponse response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
 
 455                         r.code = response.getStatus();
 
 456                         r.headers = response.getHeaders();
 
 457                         EntityTag etag = response.getEntityTag();
 
 459                                 r.message = etag.getValue();
 
 460                         if (response.hasEntity() && r.code != 204)
 
 461                                 r.body = response.getEntity(String.class);
 
 464                 long t2 = System.currentTimeMillis();
 
 465                 log.info("Response received. Time: " + (t2 - t1));
 
 466                 log.info("HTTP response code: " + r.code);
 
 467                 log.info("HTTP response message: " + r.message);
 
 468                 logHeaders(r.headers);
 
 469                 log.info("HTTP response: " + r.body);
 
 474         protected SSLContext createSSLContext(Parameters p) {
 
 476                         System.setProperty("jsse.enableSNIExtension", "false");
 
 477                         System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 478                         System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 480                         HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
 
 483                                 public boolean verify(String string, SSLSession ssls) {
 
 488                         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 489                         FileInputStream in = new FileInputStream(p.keyStoreFileName);
 
 490                         KeyStore ks = KeyStore.getInstance("PKCS12");
 
 491                         char[] pwd = p.keyStorePassword.toCharArray();
 
 495                         SSLContext ctx = SSLContext.getInstance("TLS");
 
 496                         ctx.init(kmf.getKeyManagers(), null, null);
 
 498                 } catch (Exception e) {
 
 499                         log.error("Error creating SSLContext: " + e.getMessage(), e);
 
 504         protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage, HttpResponse r) {
 
 505                 r = new HttpResponse();
 
 507                 r.message = errorMessage;
 
 508                 String pp = prefix != null ? prefix + '.' : "";
 
 509                 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 510                 ctx.setAttribute(pp + "response-message", r.message);
 
 513         protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 514                 String pp = prefix != null ? prefix + '.' : "";
 
 515                 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 516                 ctx.setAttribute(pp + "response-message", r.message);
 
 519         public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 520                 HttpResponse r = null;
 
 522                         FileParam p = getFileParameters(paramMap);
 
 523                         byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 525                         r = sendHttpData(data, p);
 
 526                         setResponseStatus(ctx, p.responsePrefix, r);
 
 528                 } catch (Exception e) {
 
 529                         log.error("Error sending the request: " + e.getMessage(), e);
 
 531                         r = new HttpResponse();
 
 533                         r.message = e.getMessage();
 
 534                         String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 535                         setResponseStatus(ctx, prefix, r);
 
 538                 if (r != null && r.code >= 300)
 
 539                         throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 542         private static class FileParam {
 
 544                 public String fileName;
 
 547                 public String password;
 
 548                 public HttpMethod httpMethod;
 
 549                 public String responsePrefix;
 
 550                 public boolean skipSending;
 
 553         private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 554                 FileParam p = new FileParam();
 
 555                 p.fileName = parseParam(paramMap, "fileName", true, null);
 
 556                 p.url = parseParam(paramMap, "url", true, null);
 
 557                 p.user = parseParam(paramMap, "user", false, null);
 
 558                 p.password = parseParam(paramMap, "password", false, null);
 
 559                 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 560                 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 561                 String skipSendingStr = paramMap.get("skipSending");
 
 562                 p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
 
 566         protected HttpResponse sendHttpData(byte[] data, FileParam p) {
 
 567                 Client client = Client.create();
 
 568                 client.setConnectTimeout(5000);
 
 569                 client.setFollowRedirects(true);
 
 571                         client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
 
 572                 WebResource webResource = client.resource(p.url);
 
 574                 log.info("Sending file");
 
 575                 long t1 = System.currentTimeMillis();
 
 577                 HttpResponse r = new HttpResponse();
 
 580                 if (!p.skipSending) {
 
 581                         String tt = "application/octet-stream";
 
 583                         ClientResponse response = null;
 
 584                         if (p.httpMethod == HttpMethod.POST)
 
 585                                 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
 
 586                         else if (p.httpMethod == HttpMethod.PUT)
 
 587                                 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
 
 589                         r.code = response.getStatus();
 
 590                         r.headers = response.getHeaders();
 
 591                         EntityTag etag = response.getEntityTag();
 
 593                                 r.message = etag.getValue();
 
 594                         if (response.hasEntity() && r.code != 204)
 
 595                                 r.body = response.getEntity(String.class);
 
 598                                 String newUrl = response.getHeaders().getFirst("Location");
 
 600                                 log.info("Got response code 301. Sending same request to URL: " + newUrl);
 
 602                                 webResource = client.resource(newUrl);
 
 604                                 if (p.httpMethod == HttpMethod.POST)
 
 605                                         response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
 
 606                                 else if (p.httpMethod == HttpMethod.PUT)
 
 607                                         response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
 
 609                                 r.code = response.getStatus();
 
 610                                 etag = response.getEntityTag();
 
 612                                         r.message = etag.getValue();
 
 613                                 if (response.hasEntity() && r.code != 204)
 
 614                                         r.body = response.getEntity(String.class);
 
 618                 long t2 = System.currentTimeMillis();
 
 619                 log.info("Response received. Time: " + (t2 - t1));
 
 620                 log.info("HTTP response code: " + r.code);
 
 621                 log.info("HTTP response message: " + r.message);
 
 622                 logHeaders(r.headers);
 
 623                 log.info("HTTP response: " + r.body);
 
 628         public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 629                 HttpResponse r = null;
 
 631                         UebParam p = getUebParameters(paramMap);
 
 633                         String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 637                         if (p.templateFileName == null) {
 
 638                                 log.info("No template file name specified. Using default UEB template: " + defaultUebTemplateFileName);
 
 639                                 p.templateFileName = defaultUebTemplateFileName;
 
 642                         String reqTemplate = readFile(p.templateFileName);
 
 643                         reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 644                         req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 646                         r = postOnUeb(req, p);
 
 647                         setResponseStatus(ctx, p.responsePrefix, r);
 
 649                                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 651                 } catch (Exception e) {
 
 652                         log.error("Error sending the request: " + e.getMessage(), e);
 
 654                         r = new HttpResponse();
 
 656                         r.message = e.getMessage();
 
 657                         String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 658                         setResponseStatus(ctx, prefix, r);
 
 661                 if (r != null && r.code >= 300)
 
 662                         throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 665         private static class UebParam {
 
 668                 public String templateFileName;
 
 669                 public String rootVarName;
 
 670                 public String responsePrefix;
 
 671                 public boolean skipSending;
 
 674         private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 675                 UebParam p = new UebParam();
 
 676                 p.topic = parseParam(paramMap, "topic", true, null);
 
 677                 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 678                 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
 679                 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 680                 String skipSendingStr = paramMap.get("skipSending");
 
 681                 p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
 
 685         protected HttpResponse postOnUeb(String request, UebParam p) throws Exception {
 
 686                 String[] urls = uebServers.split(" ");
 
 687                 for (int i = 0; i < urls.length; i++) {
 
 688                         if (!urls[i].endsWith("/"))
 
 690                         urls[i] += "events/" + p.topic;
 
 693                 Client client = Client.create();
 
 694                 client.setConnectTimeout(5000);
 
 695                 WebResource webResource = client.resource(urls[0]);
 
 697                 log.info("UEB URL: " + urls[0]);
 
 698                 log.info("Sending request:");
 
 700                 long t1 = System.currentTimeMillis();
 
 702                 HttpResponse r = new HttpResponse();
 
 705                 if (!p.skipSending) {
 
 706                         String tt = "application/json";
 
 707                         String tt1 = tt + ";charset=UTF-8";
 
 709                         ClientResponse response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
 
 711                         r.code = response.getStatus();
 
 712                         r.headers = response.getHeaders();
 
 713                         if (response.hasEntity())
 
 714                                 r.body = response.getEntity(String.class);
 
 717                 long t2 = System.currentTimeMillis();
 
 718                 log.info("Response received. Time: " + (t2 - t1));
 
 719                 log.info("HTTP response code: " + r.code);
 
 720                 logHeaders(r.headers);
 
 721                 log.info("HTTP response:\n" + r.body);
 
 726         protected void logProperties(Map<String, Object> mm) {
 
 727                 List<String> ll = new ArrayList<>();
 
 728                 for (Object o : mm.keySet())
 
 730                 Collections.sort(ll);
 
 732                 log.info("Properties:");
 
 733                 for (String name : ll)
 
 734                         log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
 
 737         protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 738                 log.info("HTTP response headers:");
 
 743                 List<String> ll = new ArrayList<>();
 
 744                 for (Object o : mm.keySet())
 
 746                 Collections.sort(ll);
 
 748                 for (String name : ll)
 
 749                         log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
 
 752         public void setUebServers(String uebServers) {
 
 753                 this.uebServers = uebServers;
 
 756         public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 757                 this.defaultUebTemplateFileName = defaultUebTemplateFileName;