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));
 
 172      * Validates the given URL in the parameters.
 
 174      * @param restapiUrl rest api URL
 
 175      * @throws SvcLogicException when URL validation fails
 
 177     private static void validateUrl(String restapiUrl)
 
 178         throws SvcLogicException {
 
 180             URI.create(restapiUrl);
 
 181         } catch (IllegalArgumentException e) {
 
 182             throw new SvcLogicException("Invalid input of url "
 
 183                 + e.getLocalizedMessage(), e);
 
 188      * Returns the list of list name.
 
 190      * @param paramMap parameters map
 
 191      * @return list of list name
 
 193     private static Set<String> getListNameList(Map<String, String> paramMap) {
 
 194         Set<String> ll = new HashSet<>();
 
 195         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
 
 196             if (entry.getKey().startsWith("listName")) {
 
 197                 ll.add(entry.getValue());
 
 204      * Parses the parameter string map of property, validates if required,
 
 205      * assigns default value if present and returns the value.
 
 207      * @param paramMap string param map
 
 208      * @param name     name of the property
 
 209      * @param required if value required
 
 210      * @param def      default value
 
 211      * @return value of the property
 
 212      * @throws SvcLogicException if required parameter value is empty
 
 214     public static String parseParam(Map<String, String> paramMap, String name,
 
 215         boolean required, String def)
 
 216         throws SvcLogicException {
 
 217         String s = paramMap.get(name);
 
 219         if (s == null || s.trim().length() == 0) {
 
 223             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 227         StringBuilder value = new StringBuilder();
 
 229         int i1 = s.indexOf('%');
 
 231             int i2 = s.indexOf('%', i1 + 1);
 
 236             String varName = s.substring(i1 + 1, i2);
 
 237             String varValue = System.getenv(varName);
 
 238             if (varValue == null) {
 
 239                 varValue = "%" + varName + "%";
 
 242             value.append(s.substring(i, i1));
 
 243             value.append(varValue);
 
 246             i1 = s.indexOf('%', i);
 
 248         value.append(s.substring(i));
 
 250         log.info("Parameter {}: [{}]", name, value);
 
 251         return value.toString();
 
 254     public RetryPolicyStore getRetryPolicyStore() {
 
 255         return retryPolicyStore;
 
 258     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
 259         this.retryPolicyStore = retryPolicyStore;
 
 263      * Allows Directed Graphs  the ability to interact with REST APIs.
 
 264      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
 
 266      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
 268      *      <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>
 
 269      *      <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>
 
 270      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
 
 271      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
 
 272      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
 
 273      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
 
 274      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
 
 275      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
 
 276      *      <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>
 
 277      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
 
 278      *      <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>
 
 279      *      <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>
 
 280      *      <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>
 
 281      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
 
 282      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
 
 283      *      <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>
 
 284      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
 
 285      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
 
 286      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
 
 289      * @param ctx Reference to context memory
 
 290      * @throws SvcLogicException
 
 292      * @see String#split(String, int)
 
 294     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 295         sendRequest(paramMap, ctx, null);
 
 298     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 299         throws SvcLogicException {
 
 301         RetryPolicy retryPolicy = null;
 
 302         HttpResponse r = new HttpResponse();
 
 304             Parameters p = getParameters(paramMap, new Parameters());
 
 305             if (p.partner != null) {
 
 306                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 308             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 311             if (p.templateFileName != null) {
 
 312                 String reqTemplate = readFile(p.templateFileName);
 
 313                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 314             } else if (p.requestBody != null) {
 
 317             r = sendHttpRequest(req, p);
 
 318             setResponseStatus(ctx, p.responsePrefix, r);
 
 320             if (p.dumpHeaders && r.headers != null) {
 
 321                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 322                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 326             if (p.returnRequestPayload && req != null) {
 
 327                 ctx.setAttribute(pp + "httpRequest", req);
 
 330             if (r.body != null && r.body.trim().length() > 0) {
 
 331                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 333                 if (p.convertResponse) {
 
 334                     Map<String, String> mm = null;
 
 335                     if (p.format == Format.XML) {
 
 336                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 337                     } else if (p.format == Format.JSON) {
 
 338                         mm = JsonParser.convertToProperties(r.body);
 
 342                         for (Map.Entry<String, String> entry : mm.entrySet()) {
 
 343                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 348         } catch (SvcLogicException e) {
 
 349             boolean shouldRetry = false;
 
 350             if (e.getCause().getCause() instanceof SocketException) {
 
 354             log.error("Error sending the request: " + e.getMessage(), e);
 
 355             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 356             if (retryPolicy == null || !shouldRetry) {
 
 357                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 359                 if (retryCount == null) {
 
 362                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 364                 log.debug(retryMessage);
 
 366                     retryCount = retryCount + 1;
 
 367                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 368                         URI uri = new URI(paramMap.get(restapiUrlString));
 
 369                         String hostname = uri.getHost();
 
 370                         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 371                         URI uriTwo = new URI(retryString);
 
 372                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
 
 373                             uriTwo.getScheme()).build();
 
 374                         paramMap.put(restapiUrlString, retryUri.toString());
 
 375                         log.debug("URL was set to {}", retryUri.toString());
 
 376                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
 
 377                             hostname, retryString);
 
 378                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
 
 379                         sendRequest(paramMap, ctx, retryCount);
 
 381                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 382                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 384                 } catch (Exception ex) {
 
 385                     log.error("Could not attempt retry.", ex);
 
 386                     String retryErrorMessage =
 
 387                         "Retry attempt has failed. No further retry shall be attempted, calling " +
 
 388                             "setFailureResponseStatus.";
 
 389                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 394         if (r != null && r.code >= 300) {
 
 395             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 399     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
 
 400         throws SvcLogicException {
 
 401         log.info("Building {} started", format);
 
 402         long t1 = System.currentTimeMillis();
 
 403         String originalTemplate = template;
 
 405         template = expandRepeats(ctx, template, 1);
 
 407         Map<String, String> mm = new HashMap<>();
 
 408         for (String s : ctx.getAttributeKeySet()) {
 
 409             mm.put(s, ctx.getAttribute(s));
 
 412         StringBuilder ss = new StringBuilder();
 
 414         while (i < template.length()) {
 
 415             int i1 = template.indexOf("${", i);
 
 417                 ss.append(template.substring(i));
 
 421             int i2 = template.indexOf('}', i1 + 2);
 
 423                 throw new SvcLogicException("Template error: Matching } not found");
 
 426             String var1 = template.substring(i1 + 2, i2);
 
 427             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 428             if (value1 == null || value1.trim().length() == 0) {
 
 429                 // delete the whole element (line)
 
 430                 int i3 = template.lastIndexOf('\n', i1);
 
 434                 int i4 = template.indexOf('\n', i1);
 
 436                     i4 = template.length();
 
 440                     ss.append(template.substring(i, i3));
 
 444                 ss.append(template.substring(i, i1)).append(value1);
 
 449         String req = format == Format.XML
 
 450             ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
 
 452         if (format == Format.JSON) {
 
 453             req = XmlJsonUtil.removeLastCommaJson(req);
 
 456         long t2 = System.currentTimeMillis();
 
 457         log.info("Building {} completed. Time: {}", format, (t2 - t1));
 
 462     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 463         StringBuilder newTemplate = new StringBuilder();
 
 465         while (k < template.length()) {
 
 466             int i1 = template.indexOf("${repeat:", k);
 
 468                 newTemplate.append(template.substring(k));
 
 472             int i2 = template.indexOf(':', i1 + 9);
 
 474                 throw new SvcLogicException(
 
 475                     "Template error: Context variable name followed by : is required after repeat");
 
 478             // Find the closing }, store in i3
 
 482             while (nn > 0 && i < template.length()) {
 
 483                 i3 = template.indexOf('}', i);
 
 485                     throw new SvcLogicException("Template error: Matching } not found");
 
 487                 int i32 = template.indexOf('{', i);
 
 488                 if (i32 >= 0 && i32 < i3) {
 
 497             String var1 = template.substring(i1 + 9, i2);
 
 498             String value1 = ctx.getAttribute(var1);
 
 499             log.info("     {}:{}", var1, value1);
 
 502                 n = Integer.parseInt(value1);
 
 503             } catch (NumberFormatException e) {
 
 504                 log.info("value1 not set or not a number, n will remain set at zero");
 
 507             newTemplate.append(template.substring(k, i1));
 
 509             String rpt = template.substring(i2 + 1, i3);
 
 511             for (int ii = 0; ii < n; ii++) {
 
 512                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 513                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 514                     int i4 = ss.lastIndexOf(',');
 
 516                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 519                 newTemplate.append(ss);
 
 526             return newTemplate.toString();
 
 529         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 532     protected String readFile(String fileName) throws SvcLogicException {
 
 534             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 535             return new String(encoded, "UTF-8");
 
 536         } catch (IOException | SecurityException e) {
 
 537             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
 
 541     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
 
 542         Parameters p = new Parameters();
 
 543         p.restapiUser = fp.user;
 
 544         p.restapiPassword = fp.password;
 
 545         p.oAuthConsumerKey = fp.oAuthConsumerKey;
 
 546         p.oAuthVersion = fp.oAuthVersion;
 
 547         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
 
 548         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
 
 549         p.authtype = fp.authtype;
 
 550         return addAuthType(c, p);
 
 553     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
 
 554         if (p.authtype == AuthType.Unspecified) {
 
 555             if (p.restapiUser != null && p.restapiPassword != null) {
 
 556                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 557             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
 
 558                 && p.oAuthSignatureMethod != null) {
 
 559                 Feature oAuth1Feature = OAuth1ClientSupport
 
 560                     .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 561                     .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 562                 client.register(oAuth1Feature);
 
 565             if (p.authtype == AuthType.DIGEST) {
 
 566                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 567                     client.register(HttpAuthenticationFeature.digest(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.BASIC) {
 
 574                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 575                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 577                     throw new SvcLogicException(
 
 578                         "oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 579                             "parameters doesn't exist", new Throwable());
 
 581             } else if (p.authtype == AuthType.OAUTH) {
 
 582                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 583                     Feature oAuth1Feature = OAuth1ClientSupport
 
 584                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 585                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 586                     client.register(oAuth1Feature);
 
 588                     throw new SvcLogicException(
 
 589                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
 
 590                             "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
 
 598      * Receives the http response for the http request sent.
 
 600      * @param request request msg
 
 601      * @param p       parameters
 
 602      * @return HTTP response
 
 603      * @throws SvcLogicException when sending http request fails
 
 605     public HttpResponse sendHttpRequest(String request, Parameters p)
 
 606         throws SvcLogicException {
 
 608         SSLContext ssl = null;
 
 609         if (p.ssl && p.restapiUrl.startsWith("https")) {
 
 610             ssl = createSSLContext(p);
 
 615             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
 
 616             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
 
 619             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
 
 622         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 624         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
 
 626         log.info("Sending request:");
 
 628         long t1 = System.currentTimeMillis();
 
 630         HttpResponse r = new HttpResponse();
 
 633         if (!p.skipSending) {
 
 634             String tt = p.format == Format.XML ? "application/xml" : "application/json";
 
 635             String tt1 = tt + ";charset=UTF-8";
 
 636             if (p.contentType != null) {
 
 641             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
 643             if (p.format == Format.NONE) {
 
 644                 invocationBuilder.header("", "");
 
 647             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 648                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 649                 for (String singlePair : keyValuePairs) {
 
 650                     int equalPosition = singlePair.indexOf('=');
 
 651                     invocationBuilder.header(singlePair.substring(0, equalPosition),
 
 652                         singlePair.substring(equalPosition + 1, singlePair.length()));
 
 656             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 661                 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
 
 662             } catch (ProcessingException | IllegalStateException e) {
 
 663                 throw new SvcLogicException(requestPostingException +
 
 664                     e.getLocalizedMessage(), e);
 
 667             r.code = response.getStatus();
 
 668             r.headers = response.getStringHeaders();
 
 669             EntityTag etag = response.getEntityTag();
 
 671                 r.message = etag.getValue();
 
 673             if (response.hasEntity() && r.code != 204) {
 
 674                 r.body = response.readEntity(String.class);
 
 678         long t2 = System.currentTimeMillis();
 
 679         log.info(responseReceivedMessage, (t2 - t1));
 
 680         log.info(responseHttpCodeMessage, r.code);
 
 681         log.info("HTTP response message: {}", r.message);
 
 682         logHeaders(r.headers);
 
 683         log.info("HTTP response: {}", r.body);
 
 688     protected SSLContext createSSLContext(Parameters p) {
 
 689         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
 
 690             System.setProperty("jsse.enableSNIExtension", "false");
 
 691             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 692             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 694             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 696             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 697             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 698             char[] pwd = p.keyStorePassword.toCharArray();
 
 702             SSLContext ctx = SSLContext.getInstance("TLS");
 
 703             ctx.init(kmf.getKeyManagers(), null, null);
 
 705         } catch (Exception e) {
 
 706             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 711     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 714         resp.message = errorMessage;
 
 715         String pp = prefix != null ? prefix + '.' : "";
 
 716         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
 
 717         ctx.setAttribute(pp + "response-message", resp.message);
 
 720     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 721         String pp = prefix != null ? prefix + '.' : "";
 
 722         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 723         ctx.setAttribute(pp + "response-message", r.message);
 
 726     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 727         HttpResponse r = null;
 
 729             FileParam p = getFileParameters(paramMap);
 
 730             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 732             r = sendHttpData(data, p);
 
 733             setResponseStatus(ctx, p.responsePrefix, r);
 
 735         } catch (SvcLogicException | IOException e) {
 
 736             log.error("Error sending the request: {}", e.getMessage(), e);
 
 738             r = new HttpResponse();
 
 740             r.message = e.getMessage();
 
 741             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 742             setResponseStatus(ctx, prefix, r);
 
 745         if (r != null && r.code >= 300) {
 
 746             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 750     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 751         FileParam p = new FileParam();
 
 752         p.fileName = parseParam(paramMap, "fileName", true, null);
 
 753         p.url = parseParam(paramMap, "url", true, null);
 
 754         p.user = parseParam(paramMap, "user", false, null);
 
 755         p.password = parseParam(paramMap, "password", false, null);
 
 756         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 757         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 758         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 759         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 760         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 761         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 762         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 763         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 764         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 768     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 771             UebParam p = getUebParameters(paramMap);
 
 773             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 777             if (p.templateFileName == null) {
 
 778                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
 779                 p.templateFileName = defaultUebTemplateFileName;
 
 782             String reqTemplate = readFile(p.templateFileName);
 
 783             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 784             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 786             r = postOnUeb(req, p);
 
 787             setResponseStatus(ctx, p.responsePrefix, r);
 
 788             if (r.body != null) {
 
 789                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 792         } catch (SvcLogicException e) {
 
 793             log.error("Error sending the request: {}", e.getMessage(), e);
 
 795             r = new HttpResponse();
 
 797             r.message = e.getMessage();
 
 798             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 799             setResponseStatus(ctx, prefix, r);
 
 803             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 807     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
 809         Client client = ClientBuilder.newBuilder().build();
 
 810         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 811         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
 
 812         WebTarget webTarget = addAuthType(client, p).target(p.url);
 
 814         log.info("Sending file");
 
 815         long t1 = System.currentTimeMillis();
 
 817         HttpResponse r = new HttpResponse();
 
 820         if (!p.skipSending) {
 
 821             String tt = "application/octet-stream";
 
 822             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
 
 827                 if (p.httpMethod == HttpMethod.POST) {
 
 828                     response = invocationBuilder.post(Entity.entity(data, tt));
 
 829                 } else if (p.httpMethod == HttpMethod.PUT) {
 
 830                     response = invocationBuilder.put(Entity.entity(data, tt));
 
 832                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 834             } catch (ProcessingException e) {
 
 835                 throw new SvcLogicException(requestPostingException +
 
 836                     e.getLocalizedMessage(), e);
 
 839             r.code = response.getStatus();
 
 840             r.headers = response.getStringHeaders();
 
 841             EntityTag etag = response.getEntityTag();
 
 843                 r.message = etag.getValue();
 
 845             if (response.hasEntity() && r.code != 204) {
 
 846                 r.body = response.readEntity(String.class);
 
 850                 String newUrl = response.getStringHeaders().getFirst("Location");
 
 852                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
 854                 webTarget = client.target(newUrl);
 
 855                 invocationBuilder = webTarget.request(tt).accept(tt);
 
 858                     if (p.httpMethod == HttpMethod.POST) {
 
 859                         response = invocationBuilder.post(Entity.entity(data, tt));
 
 860                     } else if (p.httpMethod == HttpMethod.PUT) {
 
 861                         response = invocationBuilder.put(Entity.entity(data, tt));
 
 863                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 865                 } catch (ProcessingException e) {
 
 866                     throw new SvcLogicException(requestPostingException +
 
 867                         e.getLocalizedMessage(), e);
 
 870                 r.code = response.getStatus();
 
 871                 etag = response.getEntityTag();
 
 873                     r.message = etag.getValue();
 
 875                 if (response.hasEntity() && r.code != 204) {
 
 876                     r.body = response.readEntity(String.class);
 
 881         long t2 = System.currentTimeMillis();
 
 882         log.info(responseReceivedMessage, (t2 - t1));
 
 883         log.info(responseHttpCodeMessage, r.code);
 
 884         log.info("HTTP response message: {}", r.message);
 
 885         logHeaders(r.headers);
 
 886         log.info("HTTP response: {}", r.body);
 
 891     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 892         UebParam p = new UebParam();
 
 893         p.topic = parseParam(paramMap, "topic", true, null);
 
 894         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 895         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
 896         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 897         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 898         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 902     protected void logProperties(Map<String, Object> mm) {
 
 903         List<String> ll = new ArrayList<>();
 
 904         for (Object o : mm.keySet()) {
 
 907         Collections.sort(ll);
 
 909         log.info("Properties:");
 
 910         for (String name : ll) {
 
 911             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 915     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 916         log.info("HTTP response headers:");
 
 922         List<String> ll = new ArrayList<>();
 
 923         for (Object o : mm.keySet()) {
 
 926         Collections.sort(ll);
 
 928         for (String name : ll) {
 
 929             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 933     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
 
 934         String[] urls = uebServers.split(" ");
 
 935         for (int i = 0; i < urls.length; i++) {
 
 936             if (!urls[i].endsWith("/")) {
 
 939             urls[i] += "events/" + p.topic;
 
 942         Client client = ClientBuilder.newBuilder().build();
 
 943         client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
 
 944         WebTarget webTarget = client.target(urls[0]);
 
 946         log.info("UEB URL: {}", urls[0]);
 
 947         log.info("Sending request:");
 
 949         long t1 = System.currentTimeMillis();
 
 951         HttpResponse r = new HttpResponse();
 
 954         if (!p.skipSending) {
 
 955             String tt = "application/json";
 
 956             String tt1 = tt + ";charset=UTF-8";
 
 959             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
 962                 response = invocationBuilder.post(Entity.entity(request, tt1));
 
 963             } catch (ProcessingException e) {
 
 964                 throw new SvcLogicException(requestPostingException +
 
 965                     e.getLocalizedMessage(), e);
 
 967             r.code = response.getStatus();
 
 968             r.headers = response.getStringHeaders();
 
 969             if (response.hasEntity()) {
 
 970                 r.body = response.readEntity(String.class);
 
 974         long t2 = System.currentTimeMillis();
 
 975         log.info(responseReceivedMessage, (t2 - t1));
 
 976         log.info(responseHttpCodeMessage, r.code);
 
 977         logHeaders(r.headers);
 
 978         log.info("HTTP response:\n {}", r.body);
 
 983     public void setUebServers(String uebServers) {
 
 984         this.uebServers = uebServers;
 
 987     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 988         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
 
 991     private static class FileParam {
 
 993         public String fileName;
 
 996         public String password;
 
 997         public HttpMethod httpMethod;
 
 998         public String responsePrefix;
 
 999         public boolean skipSending;
 
1000         public String oAuthConsumerKey;
 
1001         public String oAuthConsumerSecret;
 
1002         public String oAuthSignatureMethod;
 
1003         public String oAuthVersion;
 
1004         public AuthType authtype;
 
1007     private static class UebParam {
 
1009         public String topic;
 
1010         public String templateFileName;
 
1011         public String rootVarName;
 
1012         public String responsePrefix;
 
1013         public boolean skipSending;