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 static java.lang.Boolean.valueOf;
 
  25 import static javax.ws.rs.client.Entity.entity;
 
  26 import static org.onap.ccsdk.sli.plugins.restapicall.AuthType.fromString;
 
  28 import java.io.FileInputStream;
 
  29 import java.io.IOException;
 
  30 import java.net.SocketException;
 
  32 import java.nio.file.Files;
 
  33 import java.nio.file.Paths;
 
  34 import java.security.KeyStore;
 
  35 import java.util.ArrayList;
 
  36 import java.util.Collections;
 
  37 import java.util.HashMap;
 
  38 import java.util.HashSet;
 
  39 import java.util.List;
 
  41 import java.util.Map.Entry;
 
  42 import java.util.Properties;
 
  44 import javax.net.ssl.HttpsURLConnection;
 
  45 import javax.net.ssl.KeyManagerFactory;
 
  46 import javax.net.ssl.SSLContext;
 
  47 import javax.ws.rs.ProcessingException;
 
  48 import javax.ws.rs.client.Client;
 
  49 import javax.ws.rs.client.ClientBuilder;
 
  50 import javax.ws.rs.client.Entity;
 
  51 import javax.ws.rs.client.Invocation;
 
  52 import javax.ws.rs.client.WebTarget;
 
  53 import javax.ws.rs.core.EntityTag;
 
  54 import javax.ws.rs.core.Feature;
 
  55 import javax.ws.rs.core.MultivaluedMap;
 
  56 import javax.ws.rs.core.Response;
 
  57 import javax.ws.rs.core.UriBuilder;
 
  58 import org.apache.commons.lang3.StringUtils;
 
  59 import org.glassfish.jersey.client.ClientProperties;
 
  60 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
 
  61 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
 
  62 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
 
  63 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  64 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  65 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
 
  66 import org.slf4j.Logger;
 
  67 import org.slf4j.LoggerFactory;
 
  69 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  71     protected static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties";
 
  72     protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
 
  73     protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
 
  74     protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
 
  76     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  77     protected RetryPolicyStore retryPolicyStore;
 
  78     private String uebServers;
 
  79     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  81     public RestapiCallNode() {
 
  82         String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
 
  84         try (FileInputStream in = new FileInputStream(configDir + "/" + DME2_PROPERTIES_FILE_NAME)) {
 
  85             Properties props = new Properties();
 
  87             this.retryPolicyStore = new RetryPolicyStore();
 
  88             this.retryPolicyStore.setProxyServers(props.getProperty("proxyUrl"));
 
  89             log.info("DME2 support enabled");
 
  90         } catch (Exception e) {
 
  91             log.warn("DME2 properties could not be read, DME2 support will not be enabled.", e);
 
  94         try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
 
  95             Properties props = new Properties();
 
  97             this.uebServers = props.getProperty("servers");
 
  98             log.info("UEB support enabled");
 
  99         } catch (Exception e) {
 
 100             log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
 
 105      * Returns parameters from the parameter map.
 
 107      * @param paramMap parameter map
 
 108      * @param p        parameters instance
 
 109      * @return parameters filed instance
 
 110      * @throws SvcLogicException when svc logic exception occurs
 
 112     public static Parameters getParameters(Map<String, String> paramMap,
 
 114         throws SvcLogicException {
 
 115         p.templateFileName = parseParam(paramMap, "templateFileName",
 
 117         p.requestBody = parseParam(paramMap, "requestBody", false, null);
 
 118         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
 
 119         validateUrl(p.restapiUrl);
 
 120         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
 
 121         p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
 
 123         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey",
 
 125         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret",
 
 127         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod",
 
 129         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 130         p.contentType = parseParam(paramMap, "contentType", false, null);
 
 131         p.format = Format.fromString(parseParam(paramMap, "format", false,
 
 133         p.authtype = fromString(parseParam(paramMap, "authType", false,
 
 135         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
 
 137         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 138         p.listNameList = getListNameList(paramMap);
 
 139         String skipSendingStr = paramMap.get("skipSending");
 
 140         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 141         p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
 
 143         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName",
 
 145         p.trustStorePassword = parseParam(paramMap, "trustStorePassword",
 
 147         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName",
 
 149         p.keyStorePassword = parseParam(paramMap, "keyStorePassword",
 
 151         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null
 
 152             && p.keyStoreFileName != null && p.keyStorePassword != null;
 
 153         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders",
 
 155         p.partner = parseParam(paramMap, "partner", false, null);
 
 156         p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders",
 
 158         p.returnRequestPayload = valueOf(parseParam(
 
 159             paramMap, "returnRequestPayload", false, null));
 
 164      * Validates the given URL in the parameters.
 
 166      * @param restapiUrl rest api URL
 
 167      * @throws SvcLogicException when URL validation fails
 
 169     private static void validateUrl(String restapiUrl)
 
 170         throws SvcLogicException {
 
 172             URI.create(restapiUrl);
 
 173         } catch (IllegalArgumentException e) {
 
 174             throw new SvcLogicException("Invalid input of url "
 
 175                 + e.getLocalizedMessage(), e);
 
 180      * Returns the list of list name.
 
 182      * @param paramMap parameters map
 
 183      * @return list of list name
 
 185     private static Set<String> getListNameList(Map<String, String> paramMap) {
 
 186         Set<String> ll = new HashSet<>();
 
 187         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
 
 188             if (entry.getKey().startsWith("listName")) {
 
 189                 ll.add(entry.getValue());
 
 196      * Parses the parameter string map of property, validates if required,
 
 197      * assigns default value if present and returns the value.
 
 199      * @param paramMap string param map
 
 200      * @param name     name of the property
 
 201      * @param required if value required
 
 202      * @param def      default value
 
 203      * @return value of the property
 
 204      * @throws SvcLogicException if required parameter value is empty
 
 206     public static String parseParam(Map<String, String> paramMap, String name,
 
 207         boolean required, String def)
 
 208         throws SvcLogicException {
 
 209         String s = paramMap.get(name);
 
 211         if (s == null || s.trim().length() == 0) {
 
 215             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 219         StringBuilder value = new StringBuilder();
 
 221         int i1 = s.indexOf('%');
 
 223             int i2 = s.indexOf('%', i1 + 1);
 
 228             String varName = s.substring(i1 + 1, i2);
 
 229             String varValue = System.getenv(varName);
 
 230             if (varValue == null) {
 
 231                 varValue = "%" + varName + "%";
 
 234             value.append(s.substring(i, i1));
 
 235             value.append(varValue);
 
 238             i1 = s.indexOf('%', i);
 
 240         value.append(s.substring(i));
 
 242         log.info("Parameter {}: [{}]", name, value);
 
 243         return value.toString();
 
 246     public RetryPolicyStore getRetryPolicyStore() {
 
 247         return retryPolicyStore;
 
 250     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
 251         this.retryPolicyStore = retryPolicyStore;
 
 255      * Allows Directed Graphs  the ability to interact with REST APIs.
 
 256      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
 
 258      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
 260      *      <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>
 
 261      *      <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>
 
 262      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
 
 263      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
 
 264      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
 
 265      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
 
 266      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
 
 267      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
 
 268      *      <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>
 
 269      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
 
 270      *      <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>
 
 271      *      <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>
 
 272      *      <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>
 
 273      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
 
 274      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
 
 275      *      <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>
 
 276      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
 
 277      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
 
 278      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
 
 281      * @param ctx Reference to context memory
 
 282      * @throws SvcLogicException
 
 284      * @see String#split(String, int)
 
 286     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 287         sendRequest(paramMap, ctx, null);
 
 290     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 291         throws SvcLogicException {
 
 293         RetryPolicy retryPolicy = null;
 
 294         HttpResponse r = new HttpResponse();
 
 296             Parameters p = getParameters(paramMap, new Parameters());
 
 297             if (p.partner != null) {
 
 298                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 300             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 303             if (p.templateFileName != null) {
 
 304                 String reqTemplate = readFile(p.templateFileName);
 
 305                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 306             } else if (p.requestBody != null) {
 
 309             r = sendHttpRequest(req, p);
 
 310             setResponseStatus(ctx, p.responsePrefix, r);
 
 312             if (p.dumpHeaders && r.headers != null) {
 
 313                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 314                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 318             if (p.returnRequestPayload && req != null) {
 
 319                 ctx.setAttribute(pp + "httpRequest", req);
 
 322             if (r.body != null && r.body.trim().length() > 0) {
 
 323                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 325                 if (p.convertResponse) {
 
 326                     Map<String, String> mm = null;
 
 327                     if (p.format == Format.XML) {
 
 328                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 329                     } else if (p.format == Format.JSON) {
 
 330                         mm = JsonParser.convertToProperties(r.body);
 
 334                         for (Map.Entry<String, String> entry : mm.entrySet()) {
 
 335                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 340         } catch (SvcLogicException e) {
 
 341             boolean shouldRetry = false;
 
 342             if (e.getCause().getCause() instanceof SocketException) {
 
 346             log.error("Error sending the request: " + e.getMessage(), e);
 
 347             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 348             if (retryPolicy == null || shouldRetry == false) {
 
 349                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 351                 if (retryCount == null) {
 
 354                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 356                 log.debug(retryMessage);
 
 358                     retryCount = retryCount + 1;
 
 359                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 360                         URI uri = new URI(paramMap.get("restapiUrl"));
 
 361                         String hostname = uri.getHost();
 
 362                         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 363                         URI uriTwo = new URI(retryString);
 
 364                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
 
 365                             uriTwo.getScheme()).build();
 
 366                         paramMap.put("restapiUrl", retryUri.toString());
 
 367                         log.debug("URL was set to {}", retryUri.toString());
 
 368                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
 
 369                             hostname, retryString);
 
 370                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
 
 371                         sendRequest(paramMap, ctx, retryCount);
 
 373                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 374                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 376                 } catch (Exception ex) {
 
 377                     log.error("Could not attempt retry.", ex);
 
 378                     String retryErrorMessage =
 
 379                         "Retry attempt has failed. No further retry shall be attempted, calling " +
 
 380                             "setFailureResponseStatus.";
 
 381                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 386         if (r != null && r.code >= 300) {
 
 387             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 391     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
 
 392         throws SvcLogicException {
 
 393         log.info("Building {} started", format);
 
 394         long t1 = System.currentTimeMillis();
 
 396         template = expandRepeats(ctx, template, 1);
 
 398         Map<String, String> mm = new HashMap<>();
 
 399         for (String s : ctx.getAttributeKeySet()) {
 
 400             mm.put(s, ctx.getAttribute(s));
 
 403         StringBuilder ss = new StringBuilder();
 
 405         while (i < template.length()) {
 
 406             int i1 = template.indexOf("${", i);
 
 408                 ss.append(template.substring(i));
 
 412             int i2 = template.indexOf('}', i1 + 2);
 
 414                 throw new SvcLogicException("Template error: Matching } not found");
 
 417             String var1 = template.substring(i1 + 2, i2);
 
 418             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 419             // log.info(" " + var1 + ": " + value1);
 
 420             if (value1 == null || value1.trim().length() == 0) {
 
 421                 // delete the whole element (line)
 
 422                 int i3 = template.lastIndexOf('\n', i1);
 
 426                 int i4 = template.indexOf('\n', i1);
 
 428                     i4 = template.length();
 
 432                     ss.append(template.substring(i, i3));
 
 436                 ss.append(template.substring(i, i1)).append(value1);
 
 441         String req = format == Format.XML
 
 442             ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
 
 444         if (format == Format.JSON) {
 
 445             req = XmlJsonUtil.removeLastCommaJson(req);
 
 448         long t2 = System.currentTimeMillis();
 
 449         log.info("Building {} completed. Time: {}", format, (t2 - t1));
 
 454     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 455         StringBuilder newTemplate = new StringBuilder();
 
 457         while (k < template.length()) {
 
 458             int i1 = template.indexOf("${repeat:", k);
 
 460                 newTemplate.append(template.substring(k));
 
 464             int i2 = template.indexOf(':', i1 + 9);
 
 466                 throw new SvcLogicException(
 
 467                     "Template error: Context variable name followed by : is required after repeat");
 
 470             // Find the closing }, store in i3
 
 474             while (nn > 0 && i < template.length()) {
 
 475                 i3 = template.indexOf('}', i);
 
 477                     throw new SvcLogicException("Template error: Matching } not found");
 
 479                 int i32 = template.indexOf('{', i);
 
 480                 if (i32 >= 0 && i32 < i3) {
 
 489             String var1 = template.substring(i1 + 9, i2);
 
 490             String value1 = ctx.getAttribute(var1);
 
 491             log.info("     {}:{}", var1, value1);
 
 494                 n = Integer.parseInt(value1);
 
 495             } catch (NumberFormatException e) {
 
 496                 log.info("value1 not set or not a number, n will remain set at zero");
 
 499             newTemplate.append(template.substring(k, i1));
 
 501             String rpt = template.substring(i2 + 1, i3);
 
 503             for (int ii = 0; ii < n; ii++) {
 
 504                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 505                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 506                     int i4 = ss.lastIndexOf(',');
 
 508                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 511                 newTemplate.append(ss);
 
 518             return newTemplate.toString();
 
 521         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 524     protected String readFile(String fileName) throws SvcLogicException {
 
 526             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 527             return new String(encoded, "UTF-8");
 
 528         } catch (IOException | SecurityException e) {
 
 529             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
 
 533     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
 
 534         Parameters p = new Parameters();
 
 535         p.restapiUser = fp.user;
 
 536         p.restapiPassword = fp.password;
 
 537         p.oAuthConsumerKey = fp.oAuthConsumerKey;
 
 538         p.oAuthVersion = fp.oAuthVersion;
 
 539         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
 
 540         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
 
 541         p.authtype = fp.authtype;
 
 542         return addAuthType(c, p);
 
 545     protected Client addAuthType(Client client, Parameters p) throws SvcLogicException {
 
 546         if (p.authtype == AuthType.Unspecified) {
 
 547             if (p.restapiUser != null && p.restapiPassword != null) {
 
 548                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 549             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
 
 550                 && p.oAuthSignatureMethod != null) {
 
 551                 Feature oAuth1Feature = OAuth1ClientSupport
 
 552                     .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 553                     .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 554                 client.register(oAuth1Feature);
 
 557             if (p.authtype == AuthType.DIGEST) {
 
 558                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 559                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
 
 561                     throw new SvcLogicException(
 
 562                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 563                             "parameters doesn't exist", new Throwable());
 
 565             } else if (p.authtype == AuthType.BASIC) {
 
 566                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 567                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 569                     throw new SvcLogicException(
 
 570                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 571                             "parameters doesn't exist", new Throwable());
 
 573             } else if (p.authtype == AuthType.OAUTH) {
 
 574                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 575                     Feature oAuth1Feature = OAuth1ClientSupport
 
 576                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 577                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 578                     client.register(oAuth1Feature);
 
 580                     throw new SvcLogicException(
 
 581                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
 
 582                             "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
 
 590      * Receives the http response for the http request sent.
 
 592      * @param request request msg
 
 593      * @param p       parameters
 
 594      * @return HTTP response
 
 595      * @throws SvcLogicException when sending http request fails
 
 597     public HttpResponse sendHttpRequest(String request, Parameters p)
 
 598         throws SvcLogicException {
 
 600         SSLContext ssl = null;
 
 601         if (p.ssl && p.restapiUrl.startsWith("https")) {
 
 602             ssl = createSSLContext(p);
 
 607             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
 
 608             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
 
 611             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
 
 614         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 616         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
 
 618         log.info("Sending request:");
 
 620         long t1 = System.currentTimeMillis();
 
 622         HttpResponse r = new HttpResponse();
 
 625         if (!p.skipSending) {
 
 626             String tt = p.format == Format.XML ? "application/xml" : "application/json";
 
 627             String tt1 = tt + ";charset=UTF-8";
 
 628             if (p.contentType != null) {
 
 633             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
 635             if (p.format == Format.NONE) {
 
 636                 invocationBuilder.header("", "");
 
 639             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 640                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 641                 for (String singlePair : keyValuePairs) {
 
 642                     int equalPosition = singlePair.indexOf('=');
 
 643                     invocationBuilder.header(singlePair.substring(0, equalPosition),
 
 644                         singlePair.substring(equalPosition + 1, singlePair.length()));
 
 648             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 653                 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
 
 654             } catch (ProcessingException | IllegalStateException e) {
 
 655                 throw new SvcLogicException("Exception while posting http request to client " +
 
 656                     e.getLocalizedMessage(), e);
 
 659             r.code = response.getStatus();
 
 660             r.headers = response.getStringHeaders();
 
 661             EntityTag etag = response.getEntityTag();
 
 663                 r.message = etag.getValue();
 
 665             if (response.hasEntity() && r.code != 204) {
 
 666                 r.body = response.readEntity(String.class);
 
 670         long t2 = System.currentTimeMillis();
 
 671         log.info("Response received. Time: {}", (t2 - t1));
 
 672         log.info("HTTP response code: {}", r.code);
 
 673         log.info("HTTP response message: {}", r.message);
 
 674         logHeaders(r.headers);
 
 675         log.info("HTTP response: {}", r.body);
 
 680     protected SSLContext createSSLContext(Parameters p) {
 
 681         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
 
 682             System.setProperty("jsse.enableSNIExtension", "false");
 
 683             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 684             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 686             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 688             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 689             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 690             char[] pwd = p.keyStorePassword.toCharArray();
 
 694             SSLContext ctx = SSLContext.getInstance("TLS");
 
 695             ctx.init(kmf.getKeyManagers(), null, null);
 
 697         } catch (Exception e) {
 
 698             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 703     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 706         resp.message = errorMessage;
 
 707         String pp = prefix != null ? prefix + '.' : "";
 
 708         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
 
 709         ctx.setAttribute(pp + "response-message", resp.message);
 
 712     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 713         String pp = prefix != null ? prefix + '.' : "";
 
 714         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 715         ctx.setAttribute(pp + "response-message", r.message);
 
 718     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 719         HttpResponse r = null;
 
 721             FileParam p = getFileParameters(paramMap);
 
 722             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 724             r = sendHttpData(data, p);
 
 725             setResponseStatus(ctx, p.responsePrefix, r);
 
 727         } catch (SvcLogicException | IOException e) {
 
 728             log.error("Error sending the request: {}", e.getMessage(), e);
 
 730             r = new HttpResponse();
 
 732             r.message = e.getMessage();
 
 733             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 734             setResponseStatus(ctx, prefix, r);
 
 737         if (r != null && r.code >= 300) {
 
 738             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 742     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 743         FileParam p = new FileParam();
 
 744         p.fileName = parseParam(paramMap, "fileName", true, null);
 
 745         p.url = parseParam(paramMap, "url", true, null);
 
 746         p.user = parseParam(paramMap, "user", false, null);
 
 747         p.password = parseParam(paramMap, "password", false, null);
 
 748         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 749         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 750         String skipSendingStr = paramMap.get("skipSending");
 
 751         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 752         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 753         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 754         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 755         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 756         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 760     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 763             UebParam p = getUebParameters(paramMap);
 
 765             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 769             if (p.templateFileName == null) {
 
 770                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
 771                 p.templateFileName = defaultUebTemplateFileName;
 
 774             String reqTemplate = readFile(p.templateFileName);
 
 775             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 776             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 778             r = postOnUeb(req, p);
 
 779             setResponseStatus(ctx, p.responsePrefix, r);
 
 780             if (r.body != null) {
 
 781                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 784         } catch (SvcLogicException e) {
 
 785             log.error("Error sending the request: {}", e.getMessage(), e);
 
 787             r = new HttpResponse();
 
 789             r.message = e.getMessage();
 
 790             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 791             setResponseStatus(ctx, prefix, r);
 
 795             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 799     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
 801         Client client = ClientBuilder.newBuilder().build();
 
 802         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 803         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
 
 804         WebTarget webTarget = addAuthType(client, p).target(p.url);
 
 806         log.info("Sending file");
 
 807         long t1 = System.currentTimeMillis();
 
 809         HttpResponse r = new HttpResponse();
 
 812         if (!p.skipSending) {
 
 813             String tt = "application/octet-stream";
 
 814             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
 
 819                 if (p.httpMethod == HttpMethod.POST) {
 
 820                     response = invocationBuilder.post(Entity.entity(data, tt));
 
 821                 } else if (p.httpMethod == HttpMethod.PUT) {
 
 822                     response = invocationBuilder.put(Entity.entity(data, tt));
 
 824                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 826             } catch (ProcessingException e) {
 
 827                 throw new SvcLogicException("Exception while posting http request to client " +
 
 828                     e.getLocalizedMessage(), e);
 
 831             r.code = response.getStatus();
 
 832             r.headers = response.getStringHeaders();
 
 833             EntityTag etag = response.getEntityTag();
 
 835                 r.message = etag.getValue();
 
 837             if (response.hasEntity() && r.code != 204) {
 
 838                 r.body = response.readEntity(String.class);
 
 842                 String newUrl = response.getStringHeaders().getFirst("Location");
 
 844                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
 846                 webTarget = client.target(newUrl);
 
 847                 invocationBuilder = webTarget.request(tt).accept(tt);
 
 850                     if (p.httpMethod == HttpMethod.POST) {
 
 851                         response = invocationBuilder.post(Entity.entity(data, tt));
 
 852                     } else if (p.httpMethod == HttpMethod.PUT) {
 
 853                         response = invocationBuilder.put(Entity.entity(data, tt));
 
 855                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 857                 } catch (ProcessingException e) {
 
 858                     throw new SvcLogicException("Exception while posting http request to client " +
 
 859                         e.getLocalizedMessage(), e);
 
 862                 r.code = response.getStatus();
 
 863                 etag = response.getEntityTag();
 
 865                     r.message = etag.getValue();
 
 867                 if (response.hasEntity() && r.code != 204) {
 
 868                     r.body = response.readEntity(String.class);
 
 873         long t2 = System.currentTimeMillis();
 
 874         log.info("Response received. Time: {}", (t2 - t1));
 
 875         log.info("HTTP response code: {}", r.code);
 
 876         log.info("HTTP response message: {}", r.message);
 
 877         logHeaders(r.headers);
 
 878         log.info("HTTP response: {}", r.body);
 
 883     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 884         UebParam p = new UebParam();
 
 885         p.topic = parseParam(paramMap, "topic", true, null);
 
 886         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 887         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
 888         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 889         String skipSendingStr = paramMap.get("skipSending");
 
 890         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 894     protected void logProperties(Map<String, Object> mm) {
 
 895         List<String> ll = new ArrayList<>();
 
 896         for (Object o : mm.keySet()) {
 
 899         Collections.sort(ll);
 
 901         log.info("Properties:");
 
 902         for (String name : ll) {
 
 903             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 907     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 908         log.info("HTTP response headers:");
 
 914         List<String> ll = new ArrayList<>();
 
 915         for (Object o : mm.keySet()) {
 
 918         Collections.sort(ll);
 
 920         for (String name : ll) {
 
 921             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 925     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
 
 926         String[] urls = uebServers.split(" ");
 
 927         for (int i = 0; i < urls.length; i++) {
 
 928             if (!urls[i].endsWith("/")) {
 
 931             urls[i] += "events/" + p.topic;
 
 934         Client client = ClientBuilder.newBuilder().build();
 
 935         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 936         WebTarget webTarget = client.target(urls[0]);
 
 938         log.info("UEB URL: {}", urls[0]);
 
 939         log.info("Sending request:");
 
 941         long t1 = System.currentTimeMillis();
 
 943         HttpResponse r = new HttpResponse();
 
 946         if (!p.skipSending) {
 
 947             String tt = "application/json";
 
 948             String tt1 = tt + ";charset=UTF-8";
 
 951             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
 954                 response = invocationBuilder.post(Entity.entity(request, tt1));
 
 955             } catch (ProcessingException e) {
 
 956                 throw new SvcLogicException("Exception while posting http request to client " +
 
 957                     e.getLocalizedMessage(), e);
 
 959             r.code = response.getStatus();
 
 960             r.headers = response.getStringHeaders();
 
 961             if (response.hasEntity()) {
 
 962                 r.body = response.readEntity(String.class);
 
 966         long t2 = System.currentTimeMillis();
 
 967         log.info("Response received. Time: {}", (t2 - t1));
 
 968         log.info("HTTP response code: {}", r.code);
 
 969         logHeaders(r.headers);
 
 970         log.info("HTTP response:\n {}", r.body);
 
 975     public void setUebServers(String uebServers) {
 
 976         this.uebServers = uebServers;
 
 979     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 980         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
 
 983     private static class FileParam {
 
 985         public String fileName;
 
 988         public String password;
 
 989         public HttpMethod httpMethod;
 
 990         public String responsePrefix;
 
 991         public boolean skipSending;
 
 992         public String oAuthConsumerKey;
 
 993         public String oAuthConsumerSecret;
 
 994         public String oAuthSignatureMethod;
 
 995         public String oAuthVersion;
 
 996         public AuthType authtype;
 
 999     private static class UebParam {
 
1001         public String topic;
 
1002         public String templateFileName;
 
1003         public String rootVarName;
 
1004         public String responsePrefix;
 
1005         public boolean skipSending;