2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
 
   7  * Modifications Copyright © 2018 IBM.
 
   8  * ================================================================================
 
   9  * Licensed under the Apache License, Version 2.0 (the "License");
 
  10  * you may not use this file except in compliance with the License.
 
  11  * You may obtain a copy of the License at
 
  13  *      http://www.apache.org/licenses/LICENSE-2.0
 
  15  * Unless required by applicable law or agreed to in writing, software
 
  16  * distributed under the License is distributed on an "AS IS" BASIS,
 
  17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  18  * See the License for the specific language governing permissions and
 
  19  * limitations under the License.
 
  20  * ============LICENSE_END=========================================================
 
  23 package org.onap.ccsdk.sli.plugins.restapicall;
 
  25 import static java.lang.Boolean.valueOf;
 
  26 import static javax.ws.rs.client.Entity.entity;
 
  27 import static org.onap.ccsdk.sli.plugins.restapicall.AuthType.fromString;
 
  29 import java.io.FileInputStream;
 
  30 import java.io.IOException;
 
  31 import java.net.SocketException;
 
  33 import java.nio.file.Files;
 
  34 import java.nio.file.Paths;
 
  35 import java.security.KeyStore;
 
  36 import java.util.ArrayList;
 
  37 import java.util.Collections;
 
  38 import java.util.HashMap;
 
  39 import java.util.HashSet;
 
  40 import java.util.List;
 
  42 import java.util.Map.Entry;
 
  43 import java.util.Properties;
 
  45 import javax.net.ssl.HttpsURLConnection;
 
  46 import javax.net.ssl.KeyManagerFactory;
 
  47 import javax.net.ssl.SSLContext;
 
  48 import javax.ws.rs.ProcessingException;
 
  49 import javax.ws.rs.client.Client;
 
  50 import javax.ws.rs.client.ClientBuilder;
 
  51 import javax.ws.rs.client.Entity;
 
  52 import javax.ws.rs.client.Invocation;
 
  53 import javax.ws.rs.client.WebTarget;
 
  54 import javax.ws.rs.core.EntityTag;
 
  55 import javax.ws.rs.core.Feature;
 
  56 import javax.ws.rs.core.MultivaluedMap;
 
  57 import javax.ws.rs.core.Response;
 
  58 import javax.ws.rs.core.UriBuilder;
 
  59 import org.apache.commons.lang3.StringUtils;
 
  60 import org.glassfish.jersey.client.ClientProperties;
 
  61 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
 
  62 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
 
  63 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
 
  64 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  65 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  66 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
 
  67 import org.slf4j.Logger;
 
  68 import org.slf4j.LoggerFactory;
 
  70 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  72     protected static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties";
 
  73     protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
 
  74     protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
 
  75     protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
 
  77     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  78     protected RetryPolicyStore retryPolicyStore;
 
  79     private String uebServers;
 
  80     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  82     private String responseReceivedMessage = "Response received. Time: {}";
 
  83     private String responseHttpCodeMessage = "HTTP response code: {}";
 
  84     private String requestPostingException = "Exception while posting http request to client ";
 
  85     private static String skipSendingMessage = "skipSending";
 
  86     private static String responsePrefix = "responsePrefix";
 
  87     private static String restapiUrlString = "restapiUrl";
 
  89     public RestapiCallNode() {
 
  90         String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
 
  92         try (FileInputStream in = new FileInputStream(configDir + "/" + DME2_PROPERTIES_FILE_NAME)) {
 
  93             Properties props = new Properties();
 
  95             this.retryPolicyStore = new RetryPolicyStore();
 
  96             this.retryPolicyStore.setProxyServers(props.getProperty("proxyUrl"));
 
  97             log.info("DME2 support enabled");
 
  98         } catch (Exception e) {
 
  99             log.warn("DME2 properties could not be read, DME2 support will not be enabled.", e);
 
 102         try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
 
 103             Properties props = new Properties();
 
 105             this.uebServers = props.getProperty("servers");
 
 106             log.info("UEB support enabled");
 
 107         } catch (Exception e) {
 
 108             log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
 
 113      * Returns parameters from the parameter map.
 
 115      * @param paramMap parameter map
 
 116      * @param p        parameters instance
 
 117      * @return parameters filed instance
 
 118      * @throws SvcLogicException when svc logic exception occurs
 
 120     public static Parameters getParameters(Map<String, String> paramMap,
 
 122         throws SvcLogicException {
 
 123         p.templateFileName = parseParam(paramMap, "templateFileName",
 
 125         p.requestBody = parseParam(paramMap, "requestBody", false, null);
 
 126         p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
 
 127         validateUrl(p.restapiUrl);
 
 128         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
 
 129         p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
 
 131         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey",
 
 133         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret",
 
 135         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod",
 
 137         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 138         p.contentType = parseParam(paramMap, "contentType", false, null);
 
 139         p.format = Format.fromString(parseParam(paramMap, "format", false,
 
 141         p.authtype = fromString(parseParam(paramMap, "authType", false,
 
 143         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
 
 145         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 146         p.listNameList = getListNameList(paramMap);
 
 147         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 148         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 149         p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
 
 151         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName",
 
 153         p.trustStorePassword = parseParam(paramMap, "trustStorePassword",
 
 155         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName",
 
 157         p.keyStorePassword = parseParam(paramMap, "keyStorePassword",
 
 159         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null
 
 160             && p.keyStoreFileName != null && p.keyStorePassword != null;
 
 161         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders",
 
 163         p.partner = parseParam(paramMap, "partner", false, null);
 
 164         p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders",
 
 166         p.returnRequestPayload = valueOf(parseParam(
 
 167             paramMap, "returnRequestPayload", false, null));
 
 168         p.accept = parseParam(paramMap, "accept",
 
 174      * Validates the given URL in the parameters.
 
 176      * @param restapiUrl rest api URL
 
 177      * @throws SvcLogicException when URL validation fails
 
 179     private static void validateUrl(String restapiUrl)
 
 180         throws SvcLogicException {
 
 182             URI.create(restapiUrl);
 
 183         } catch (IllegalArgumentException e) {
 
 184             throw new SvcLogicException("Invalid input of url "
 
 185                 + e.getLocalizedMessage(), e);
 
 190      * Returns the list of list name.
 
 192      * @param paramMap parameters map
 
 193      * @return list of list name
 
 195     private static Set<String> getListNameList(Map<String, String> paramMap) {
 
 196         Set<String> ll = new HashSet<>();
 
 197         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
 
 198             if (entry.getKey().startsWith("listName")) {
 
 199                 ll.add(entry.getValue());
 
 206      * Parses the parameter string map of property, validates if required,
 
 207      * assigns default value if present and returns the value.
 
 209      * @param paramMap string param map
 
 210      * @param name     name of the property
 
 211      * @param required if value required
 
 212      * @param def      default value
 
 213      * @return value of the property
 
 214      * @throws SvcLogicException if required parameter value is empty
 
 216     public static String parseParam(Map<String, String> paramMap, String name,
 
 217         boolean required, String def)
 
 218         throws SvcLogicException {
 
 219         String s = paramMap.get(name);
 
 221         if (s == null || s.trim().length() == 0) {
 
 225             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 229         StringBuilder value = new StringBuilder();
 
 231         int i1 = s.indexOf('%');
 
 233             int i2 = s.indexOf('%', i1 + 1);
 
 238             String varName = s.substring(i1 + 1, i2);
 
 239             String varValue = System.getenv(varName);
 
 240             if (varValue == null) {
 
 241                 varValue = "%" + varName + "%";
 
 244             value.append(s.substring(i, i1));
 
 245             value.append(varValue);
 
 248             i1 = s.indexOf('%', i);
 
 250         value.append(s.substring(i));
 
 252         log.info("Parameter {}: [{}]", name, value);
 
 253         return value.toString();
 
 256     public RetryPolicyStore getRetryPolicyStore() {
 
 257         return retryPolicyStore;
 
 260     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
 261         this.retryPolicyStore = retryPolicyStore;
 
 265      * Allows Directed Graphs  the ability to interact with REST APIs.
 
 266      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
 
 268      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
 270      *      <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>
 
 271      *      <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>
 
 272      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
 
 273      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
 
 274      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
 
 275      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
 
 276      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
 
 277      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
 
 278      *      <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>
 
 279      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
 
 280      *      <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>
 
 281      *      <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>
 
 282      *      <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>
 
 283      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
 
 284      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
 
 285      *      <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>
 
 286      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
 
 287      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
 
 288      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
 
 291      * @param ctx Reference to context memory
 
 292      * @throws SvcLogicException
 
 294      * @see String#split(String, int)
 
 296     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 297         sendRequest(paramMap, ctx, null);
 
 300     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 301         throws SvcLogicException {
 
 303         RetryPolicy retryPolicy = null;
 
 304         HttpResponse r = new HttpResponse();
 
 306             Parameters p = getParameters(paramMap, new Parameters());
 
 307             if (p.partner != null) {
 
 308                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 310             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 313             if (p.templateFileName != null) {
 
 314                 String reqTemplate = readFile(p.templateFileName);
 
 315                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 316             } else if (p.requestBody != null) {
 
 319             r = sendHttpRequest(req, p);
 
 320             setResponseStatus(ctx, p.responsePrefix, r);
 
 322             if (p.dumpHeaders && r.headers != null) {
 
 323                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 324                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 328             if (p.returnRequestPayload && req != null) {
 
 329                 ctx.setAttribute(pp + "httpRequest", req);
 
 332             if (r.body != null && r.body.trim().length() > 0) {
 
 333                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 335                 if (p.convertResponse) {
 
 336                     Map<String, String> mm = null;
 
 337                     if (p.format == Format.XML) {
 
 338                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 339                     } else if (p.format == Format.JSON) {
 
 340                         mm = JsonParser.convertToProperties(r.body);
 
 344                         for (Map.Entry<String, String> entry : mm.entrySet()) {
 
 345                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 350         } catch (SvcLogicException e) {
 
 351             boolean shouldRetry = false;
 
 352             if (e.getCause().getCause() instanceof SocketException) {
 
 356             log.error("Error sending the request: " + e.getMessage(), e);
 
 357             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 358             if (retryPolicy == null || !shouldRetry) {
 
 359                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 361                 if (retryCount == null) {
 
 364                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 366                 log.debug(retryMessage);
 
 368                     retryCount = retryCount + 1;
 
 369                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 370                         URI uri = new URI(paramMap.get(restapiUrlString));
 
 371                         String hostname = uri.getHost();
 
 372                         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 373                         URI uriTwo = new URI(retryString);
 
 374                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
 
 375                             uriTwo.getScheme()).build();
 
 376                         paramMap.put(restapiUrlString, retryUri.toString());
 
 377                         log.debug("URL was set to {}", retryUri.toString());
 
 378                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
 
 379                             hostname, retryString);
 
 380                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
 
 381                         sendRequest(paramMap, ctx, retryCount);
 
 383                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 384                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 386                 } catch (Exception ex) {
 
 387                     log.error("Could not attempt retry.", ex);
 
 388                     String retryErrorMessage =
 
 389                         "Retry attempt has failed. No further retry shall be attempted, calling " +
 
 390                             "setFailureResponseStatus.";
 
 391                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 396         if (r != null && r.code >= 300) {
 
 397             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 401     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
 
 402         throws SvcLogicException {
 
 403         log.info("Building {} started", format);
 
 404         long t1 = System.currentTimeMillis();
 
 405         String originalTemplate = template;
 
 407         template = expandRepeats(ctx, template, 1);
 
 409         Map<String, String> mm = new HashMap<>();
 
 410         for (String s : ctx.getAttributeKeySet()) {
 
 411             mm.put(s, ctx.getAttribute(s));
 
 414         StringBuilder ss = new StringBuilder();
 
 416         while (i < template.length()) {
 
 417             int i1 = template.indexOf("${", i);
 
 419                 ss.append(template.substring(i));
 
 423             int i2 = template.indexOf('}', i1 + 2);
 
 425                 throw new SvcLogicException("Template error: Matching } not found");
 
 428             String var1 = template.substring(i1 + 2, i2);
 
 429             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 430             if (value1 == null || value1.trim().length() == 0) {
 
 431                 // delete the whole element (line)
 
 432                 int i3 = template.lastIndexOf('\n', i1);
 
 436                 int i4 = template.indexOf('\n', i1);
 
 438                     i4 = template.length();
 
 442                     ss.append(template.substring(i, i3));
 
 446                 ss.append(template.substring(i, i1)).append(value1);
 
 451         String req = format == Format.XML
 
 452             ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
 
 454         if (format == Format.JSON) {
 
 455             req = XmlJsonUtil.removeLastCommaJson(req);
 
 458         long t2 = System.currentTimeMillis();
 
 459         log.info("Building {} completed. Time: {}", format, (t2 - t1));
 
 464     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 465         StringBuilder newTemplate = new StringBuilder();
 
 467         while (k < template.length()) {
 
 468             int i1 = template.indexOf("${repeat:", k);
 
 470                 newTemplate.append(template.substring(k));
 
 474             int i2 = template.indexOf(':', i1 + 9);
 
 476                 throw new SvcLogicException(
 
 477                     "Template error: Context variable name followed by : is required after repeat");
 
 480             // Find the closing }, store in i3
 
 484             while (nn > 0 && i < template.length()) {
 
 485                 i3 = template.indexOf('}', i);
 
 487                     throw new SvcLogicException("Template error: Matching } not found");
 
 489                 int i32 = template.indexOf('{', i);
 
 490                 if (i32 >= 0 && i32 < i3) {
 
 499             String var1 = template.substring(i1 + 9, i2);
 
 500             String value1 = ctx.getAttribute(var1);
 
 501             log.info("     {}:{}", var1, value1);
 
 504                 n = Integer.parseInt(value1);
 
 505             } catch (NumberFormatException e) {
 
 506                 log.info("value1 not set or not a number, n will remain set at zero");
 
 509             newTemplate.append(template.substring(k, i1));
 
 511             String rpt = template.substring(i2 + 1, i3);
 
 513             for (int ii = 0; ii < n; ii++) {
 
 514                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 515                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 516                     int i4 = ss.lastIndexOf(',');
 
 518                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 521                 newTemplate.append(ss);
 
 528             return newTemplate.toString();
 
 531         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 534     protected String readFile(String fileName) throws SvcLogicException {
 
 536             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 537             return new String(encoded, "UTF-8");
 
 538         } catch (IOException | SecurityException e) {
 
 539             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
 
 543     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
 
 544         Parameters p = new Parameters();
 
 545         p.restapiUser = fp.user;
 
 546         p.restapiPassword = fp.password;
 
 547         p.oAuthConsumerKey = fp.oAuthConsumerKey;
 
 548         p.oAuthVersion = fp.oAuthVersion;
 
 549         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
 
 550         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
 
 551         p.authtype = fp.authtype;
 
 552         return addAuthType(c, p);
 
 555     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
 
 556         if (p.authtype == AuthType.Unspecified) {
 
 557             if (p.restapiUser != null && p.restapiPassword != null) {
 
 558                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 559             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
 
 560                 && p.oAuthSignatureMethod != null) {
 
 561                 Feature oAuth1Feature = OAuth1ClientSupport
 
 562                     .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 563                     .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 564                 client.register(oAuth1Feature);
 
 567             if (p.authtype == AuthType.DIGEST) {
 
 568                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 569                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
 
 571                     throw new SvcLogicException(
 
 572                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 573                             "parameters doesn't exist", new Throwable());
 
 575             } else if (p.authtype == AuthType.BASIC) {
 
 576                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 577                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 579                     throw new SvcLogicException(
 
 580                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 581                             "parameters doesn't exist", new Throwable());
 
 583             } else if (p.authtype == AuthType.OAUTH) {
 
 584                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 585                     Feature oAuth1Feature = OAuth1ClientSupport
 
 586                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 587                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 588                     client.register(oAuth1Feature);
 
 590                     throw new SvcLogicException(
 
 591                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
 
 592                             "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
 
 600      * Receives the http response for the http request sent.
 
 602      * @param request request msg
 
 603      * @param p       parameters
 
 604      * @return HTTP response
 
 605      * @throws SvcLogicException when sending http request fails
 
 607     public HttpResponse sendHttpRequest(String request, Parameters p)
 
 608         throws SvcLogicException {
 
 610         SSLContext ssl = null;
 
 611         if (p.ssl && p.restapiUrl.startsWith("https")) {
 
 612             ssl = createSSLContext(p);
 
 617             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
 
 618             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
 
 621             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
 
 624         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 626         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
 
 628         log.info("Sending request:");
 
 630         long t1 = System.currentTimeMillis();
 
 632         HttpResponse r = new HttpResponse();
 
 635         if (!p.skipSending) {
 
 636             String accept = p.accept;
 
 638                 accept = p.format == Format.XML ? "application/xml" : "application/json";
 
 640             String contentType = p.contentType;
 
 641             if(contentType == null) {
 
 642                 contentType = accept + ";charset=UTF-8";
 
 645             Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
 
 647             if (p.format == Format.NONE) {
 
 648                 invocationBuilder.header("", "");
 
 651             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 652                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 653                 for (String singlePair : keyValuePairs) {
 
 654                     int equalPosition = singlePair.indexOf('=');
 
 655                     invocationBuilder.header(singlePair.substring(0, equalPosition),
 
 656                         singlePair.substring(equalPosition + 1, singlePair.length()));
 
 660             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 665                 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
 
 666             } catch (ProcessingException | IllegalStateException e) {
 
 667                 throw new SvcLogicException(requestPostingException +
 
 668                     e.getLocalizedMessage(), e);
 
 671             r.code = response.getStatus();
 
 672             r.headers = response.getStringHeaders();
 
 673             EntityTag etag = response.getEntityTag();
 
 675                 r.message = etag.getValue();
 
 677             if (response.hasEntity() && r.code != 204) {
 
 678                 r.body = response.readEntity(String.class);
 
 682         long t2 = System.currentTimeMillis();
 
 683         log.info(responseReceivedMessage, (t2 - t1));
 
 684         log.info(responseHttpCodeMessage, r.code);
 
 685         log.info("HTTP response message: {}", r.message);
 
 686         logHeaders(r.headers);
 
 687         log.info("HTTP response: {}", r.body);
 
 692     protected SSLContext createSSLContext(Parameters p) {
 
 693         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
 
 694             System.setProperty("jsse.enableSNIExtension", "false");
 
 695             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 696             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 698             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 700             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 701             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 702             char[] pwd = p.keyStorePassword.toCharArray();
 
 706             SSLContext ctx = SSLContext.getInstance("TLS");
 
 707             ctx.init(kmf.getKeyManagers(), null, null);
 
 709         } catch (Exception e) {
 
 710             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 715     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 718         resp.message = errorMessage;
 
 719         String pp = prefix != null ? prefix + '.' : "";
 
 720         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
 
 721         ctx.setAttribute(pp + "response-message", resp.message);
 
 724     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 725         String pp = prefix != null ? prefix + '.' : "";
 
 726         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 727         ctx.setAttribute(pp + "response-message", r.message);
 
 730     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 731         HttpResponse r = null;
 
 733             FileParam p = getFileParameters(paramMap);
 
 734             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 736             r = sendHttpData(data, p);
 
 737             setResponseStatus(ctx, p.responsePrefix, r);
 
 739         } catch (SvcLogicException | IOException e) {
 
 740             log.error("Error sending the request: {}", e.getMessage(), e);
 
 742             r = new HttpResponse();
 
 744             r.message = e.getMessage();
 
 745             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 746             setResponseStatus(ctx, prefix, r);
 
 749         if (r != null && r.code >= 300) {
 
 750             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 754     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 755         FileParam p = new FileParam();
 
 756         p.fileName = parseParam(paramMap, "fileName", true, null);
 
 757         p.url = parseParam(paramMap, "url", true, null);
 
 758         p.user = parseParam(paramMap, "user", false, null);
 
 759         p.password = parseParam(paramMap, "password", false, null);
 
 760         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 761         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 762         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 763         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 764         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 765         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 766         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 767         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 768         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 772     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 775             UebParam p = getUebParameters(paramMap);
 
 777             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 781             if (p.templateFileName == null) {
 
 782                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
 783                 p.templateFileName = defaultUebTemplateFileName;
 
 786             String reqTemplate = readFile(p.templateFileName);
 
 787             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 788             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 790             r = postOnUeb(req, p);
 
 791             setResponseStatus(ctx, p.responsePrefix, r);
 
 792             if (r.body != null) {
 
 793                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 796         } catch (SvcLogicException e) {
 
 797             log.error("Error sending the request: {}", e.getMessage(), e);
 
 799             r = new HttpResponse();
 
 801             r.message = e.getMessage();
 
 802             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 803             setResponseStatus(ctx, prefix, r);
 
 807             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 811     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
 813         Client client = ClientBuilder.newBuilder().build();
 
 814         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 815         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
 
 816         WebTarget webTarget = addAuthType(client, p).target(p.url);
 
 818         log.info("Sending file");
 
 819         long t1 = System.currentTimeMillis();
 
 821         HttpResponse r = new HttpResponse();
 
 824         if (!p.skipSending) {
 
 825             String tt = "application/octet-stream";
 
 826             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
 
 831                 if (p.httpMethod == HttpMethod.POST) {
 
 832                     response = invocationBuilder.post(Entity.entity(data, tt));
 
 833                 } else if (p.httpMethod == HttpMethod.PUT) {
 
 834                     response = invocationBuilder.put(Entity.entity(data, tt));
 
 836                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 838             } catch (ProcessingException e) {
 
 839                 throw new SvcLogicException(requestPostingException +
 
 840                     e.getLocalizedMessage(), e);
 
 843             r.code = response.getStatus();
 
 844             r.headers = response.getStringHeaders();
 
 845             EntityTag etag = response.getEntityTag();
 
 847                 r.message = etag.getValue();
 
 849             if (response.hasEntity() && r.code != 204) {
 
 850                 r.body = response.readEntity(String.class);
 
 854                 String newUrl = response.getStringHeaders().getFirst("Location");
 
 856                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
 858                 webTarget = client.target(newUrl);
 
 859                 invocationBuilder = webTarget.request(tt).accept(tt);
 
 862                     if (p.httpMethod == HttpMethod.POST) {
 
 863                         response = invocationBuilder.post(Entity.entity(data, tt));
 
 864                     } else if (p.httpMethod == HttpMethod.PUT) {
 
 865                         response = invocationBuilder.put(Entity.entity(data, tt));
 
 867                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 869                 } catch (ProcessingException e) {
 
 870                     throw new SvcLogicException(requestPostingException +
 
 871                         e.getLocalizedMessage(), e);
 
 874                 r.code = response.getStatus();
 
 875                 etag = response.getEntityTag();
 
 877                     r.message = etag.getValue();
 
 879                 if (response.hasEntity() && r.code != 204) {
 
 880                     r.body = response.readEntity(String.class);
 
 885         long t2 = System.currentTimeMillis();
 
 886         log.info(responseReceivedMessage, (t2 - t1));
 
 887         log.info(responseHttpCodeMessage, r.code);
 
 888         log.info("HTTP response message: {}", r.message);
 
 889         logHeaders(r.headers);
 
 890         log.info("HTTP response: {}", r.body);
 
 895     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 896         UebParam p = new UebParam();
 
 897         p.topic = parseParam(paramMap, "topic", true, null);
 
 898         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 899         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
 900         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 901         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 902         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 906     protected void logProperties(Map<String, Object> mm) {
 
 907         List<String> ll = new ArrayList<>();
 
 908         for (Object o : mm.keySet()) {
 
 911         Collections.sort(ll);
 
 913         log.info("Properties:");
 
 914         for (String name : ll) {
 
 915             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 919     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 920         log.info("HTTP response headers:");
 
 926         List<String> ll = new ArrayList<>();
 
 927         for (Object o : mm.keySet()) {
 
 930         Collections.sort(ll);
 
 932         for (String name : ll) {
 
 933             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 937     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
 
 938         String[] urls = uebServers.split(" ");
 
 939         for (int i = 0; i < urls.length; i++) {
 
 940             if (!urls[i].endsWith("/")) {
 
 943             urls[i] += "events/" + p.topic;
 
 946         Client client = ClientBuilder.newBuilder().build();
 
 947         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 948         WebTarget webTarget = client.target(urls[0]);
 
 950         log.info("UEB URL: {}", urls[0]);
 
 951         log.info("Sending request:");
 
 953         long t1 = System.currentTimeMillis();
 
 955         HttpResponse r = new HttpResponse();
 
 958         if (!p.skipSending) {
 
 959             String tt = "application/json";
 
 960             String tt1 = tt + ";charset=UTF-8";
 
 963             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
 966                 response = invocationBuilder.post(Entity.entity(request, tt1));
 
 967             } catch (ProcessingException e) {
 
 968                 throw new SvcLogicException(requestPostingException +
 
 969                     e.getLocalizedMessage(), e);
 
 971             r.code = response.getStatus();
 
 972             r.headers = response.getStringHeaders();
 
 973             if (response.hasEntity()) {
 
 974                 r.body = response.readEntity(String.class);
 
 978         long t2 = System.currentTimeMillis();
 
 979         log.info(responseReceivedMessage, (t2 - t1));
 
 980         log.info(responseHttpCodeMessage, r.code);
 
 981         logHeaders(r.headers);
 
 982         log.info("HTTP response:\n {}", r.body);
 
 987     public void setUebServers(String uebServers) {
 
 988         this.uebServers = uebServers;
 
 991     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 992         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
 
 995     private static class FileParam {
 
 997         public String fileName;
 
1000         public String password;
 
1001         public HttpMethod httpMethod;
 
1002         public String responsePrefix;
 
1003         public boolean skipSending;
 
1004         public String oAuthConsumerKey;
 
1005         public String oAuthConsumerSecret;
 
1006         public String oAuthSignatureMethod;
 
1007         public String oAuthVersion;
 
1008         public AuthType authtype;
 
1011     private static class UebParam {
 
1013         public String topic;
 
1014         public String templateFileName;
 
1015         public String rootVarName;
 
1016         public String responsePrefix;
 
1017         public boolean skipSending;