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.Iterator;
 
  41 import java.util.List;
 
  43 import java.util.Map.Entry;
 
  44 import java.util.Properties;
 
  46 import javax.net.ssl.HttpsURLConnection;
 
  47 import javax.net.ssl.KeyManagerFactory;
 
  48 import javax.net.ssl.SSLContext;
 
  49 import javax.ws.rs.ProcessingException;
 
  50 import javax.ws.rs.client.Client;
 
  51 import javax.ws.rs.client.ClientBuilder;
 
  52 import javax.ws.rs.client.Entity;
 
  53 import javax.ws.rs.client.Invocation;
 
  54 import javax.ws.rs.client.WebTarget;
 
  55 import javax.ws.rs.core.EntityTag;
 
  56 import javax.ws.rs.core.Feature;
 
  57 import javax.ws.rs.core.MediaType;
 
  58 import javax.ws.rs.core.MultivaluedMap;
 
  59 import javax.ws.rs.core.Response;
 
  60 import javax.ws.rs.core.UriBuilder;
 
  61 import org.apache.commons.lang3.StringUtils;
 
  62 import org.codehaus.jettison.json.JSONException;
 
  63 import org.codehaus.jettison.json.JSONObject;
 
  64 import org.glassfish.jersey.client.ClientProperties;
 
  65 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
 
  66 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
 
  67 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
 
  68 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
 
  69 import org.glassfish.jersey.media.multipart.MultiPart;
 
  70 import org.glassfish.jersey.media.multipart.MultiPartFeature;
 
  71 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
 
  72 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  73 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  74 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
 
  75 import org.slf4j.Logger;
 
  76 import org.slf4j.LoggerFactory;
 
  78 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  80     protected static final String PARTNERS_FILE_NAME = "partners.json";
 
  81     protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
 
  82     protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
 
  83     protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
 
  84     protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
 
  85     protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
 
  87     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  88     private String uebServers;
 
  89     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  91     private String responseReceivedMessage = "Response received. Time: {}";
 
  92     private String responseHttpCodeMessage = "HTTP response code: {}";
 
  93     private String requestPostingException = "Exception while posting http request to client ";
 
  94     protected static final String skipSendingMessage = "skipSending";
 
  95     protected static final String responsePrefix = "responsePrefix";
 
  96     protected static final String restapiUrlString = "restapiUrl";
 
  97     protected static final String restapiUserKey = "restapiUser";
 
  98     protected static final String restapiPasswordKey = "restapiPassword";
 
  99     protected Integer httpConnectTimeout;
 
 100     protected Integer httpReadTimeout;
 
 102     protected HashMap<String, PartnerDetails> partnerStore;
 
 104     public RestapiCallNode() {
 
 105         String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
 
 107             String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
 
 108             JSONObject partners = new JSONObject(jsonString);
 
 109             partnerStore = new HashMap<>();
 
 110             loadPartners(partners);
 
 111             log.info("Partners support enabled");
 
 112         } catch (Exception e) {
 
 113             log.warn("Partners file could not be read, Partner support will not be enabled.", e);
 
 116         try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
 
 117             Properties props = new Properties();
 
 119             uebServers = props.getProperty("servers");
 
 120             log.info("UEB support enabled");
 
 121         } catch (Exception e) {
 
 122             log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
 
 124         httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
 
 125         httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
 
 128     protected void loadPartners(JSONObject partners) {
 
 129         Iterator<String> keys = partners.keys();
 
 130         String partnerUserKey = "user";
 
 131         String partnerPasswordKey = "password";
 
 132         String partnerUrlKey = "url";
 
 134         while (keys.hasNext()) {
 
 135             String partnerKey = keys.next();
 
 137                 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
 
 138                 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
 
 140                     if (partnerObject.has(partnerUrlKey)) {
 
 141                         url = partnerObject.getString(partnerUrlKey);
 
 143                     String userName = partnerObject.getString(partnerUserKey);
 
 144                     String password = partnerObject.getString(partnerPasswordKey);
 
 145                     PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
 
 146                     partnerStore.put(partnerKey, details);
 
 147                     log.info("mapped partner using partner key " + partnerKey);
 
 149                     log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
 
 151             } catch (JSONException e) {
 
 152                 log.info("Couldn't map the partner using partner key " + partnerKey, e);
 
 157     /* Unobfuscate param value */
 
 158     private static String getObfuscatedVal(String paramValue) {
 
 159         String resValue = paramValue;
 
 160         if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
 
 162             String paramStr = paramValue.substring(2, paramValue.length()-1);
 
 163             if (paramStr  != null && paramStr.length() > 0)
 
 165                 String val = System.getenv(paramStr);
 
 166                 if (val != null && val.length() > 0)
 
 169                     log.info("Obfuscated value RESET for param value:" + paramValue);
 
 177      * Returns parameters from the parameter map.
 
 179      * @param paramMap parameter map
 
 180      * @param p parameters instance
 
 181      * @return parameters filed instance
 
 182      * @throws SvcLogicException when svc logic exception occurs
 
 184     public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
 
 186         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 187         p.requestBody = parseParam(paramMap, "requestBody", false, null);
 
 188         p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
 
 189         p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
 
 190         if (p.restapiUrlSuffix != null) {
 
 191             p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
 
 194         p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
 
 195         validateUrl(p.restapiUrl);
 
 197         p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
 
 198         p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
 
 199         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 200         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 201         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 202         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 203         p.contentType = parseParam(paramMap, "contentType", false, null);
 
 204         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
 
 205         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 206         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 207         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 208         p.listNameList = getListNameList(paramMap);
 
 209         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 210         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 211         p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
 
 212         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
 
 213         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
 
 214         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
 
 215         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
 
 216         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
 
 217             && p.keyStorePassword != null;
 
 218         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
 
 219         p.partner = parseParam(paramMap, "partner", false, null);
 
 220         p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
 
 221         p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
 
 222         p.accept = parseParam(paramMap, "accept", false, null);
 
 223         p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
 
 224         p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
 
 229      * Validates the given URL in the parameters.
 
 231      * @param restapiUrl rest api URL
 
 232      * @throws SvcLogicException when URL validation fails
 
 234     private static void validateUrl(String restapiUrl) throws SvcLogicException {
 
 235         if (restapiUrl.contains(",")) {
 
 236             String[] urls = restapiUrl.split(",");
 
 237             for (String url : urls) {
 
 242                 URI.create(restapiUrl);
 
 243             } catch (IllegalArgumentException e) {
 
 244                 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
 
 250      * Returns the list of list name.
 
 252      * @param paramMap parameters map
 
 253      * @return list of list name
 
 255     private static Set<String> getListNameList(Map<String, String> paramMap) {
 
 256         Set<String> ll = new HashSet<>();
 
 257         for (Map.Entry<String, String> entry : paramMap.entrySet()) {
 
 258             if (entry.getKey().startsWith("listName")) {
 
 259                 ll.add(entry.getValue());
 
 266      * Parses the parameter string map of property, validates if required, assigns default value if
 
 267      * present and returns the value.
 
 269      * @param paramMap string param map
 
 270      * @param name name of the property
 
 271      * @param required if value required
 
 272      * @param def default value
 
 273      * @return value of the property
 
 274      * @throws SvcLogicException if required parameter value is empty
 
 276     public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
 
 277         throws SvcLogicException {
 
 278         String s = paramMap.get(name);
 
 280         if (s == null || s.trim().length() == 0) {
 
 284             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 288         StringBuilder value = new StringBuilder();
 
 290         int i1 = s.indexOf('%');
 
 292             int i2 = s.indexOf('%', i1 + 1);
 
 297             String varName = s.substring(i1 + 1, i2);
 
 298             String varValue = System.getenv(varName);
 
 299             if (varValue == null) {
 
 300                 varValue = "%" + varName + "%";
 
 303             value.append(s.substring(i, i1));
 
 304             value.append(varValue);
 
 307             i1 = s.indexOf('%', i);
 
 309         value.append(s.substring(i));
 
 311         log.info("Parameter {}: [{}]", name, maskPassword(name, value));
 
 313         return value.toString();
 
 316     private static Object maskPassword(String name, Object value) {
 
 317         String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
 
 318         for (String pwdName : pwdNames) {
 
 319             if (name.contains(pwdName)) {
 
 327      * Allows Directed Graphs the ability to interact with REST APIs.
 
 329      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
 
 333      *        <th>Mandatory/Optional</th>
 
 334      *        <th>description</th>
 
 335      *        <th>example values</th></thead> <tbody>
 
 337      *        <td>templateFileName</td>
 
 339      *        <td>full path to template file that can be used to build a request</td>
 
 340      *        <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
 
 343      *        <td>restapiUrl</td>
 
 345      *        <td>url to send the request to</td>
 
 346      *        <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
 
 349      *        <td>restapiUser</td>
 
 351      *        <td>user name to use for http basic authentication</td>
 
 355      *        <td>restapiPassword</td>
 
 357      *        <td>unencrypted password to use for http basic authentication</td>
 
 358      *        <td>plain_password</td>
 
 361      *        <td>oAuthConsumerKey</td>
 
 363      *        <td>Consumer key to use for http oAuth authentication</td>
 
 367      *        <td>oAuthConsumerSecret</td>
 
 369      *        <td>Consumer secret to use for http oAuth authentication</td>
 
 370      *        <td>plain_secret</td>
 
 373      *        <td>oAuthSignatureMethod</td>
 
 375      *        <td>Consumer method to use for http oAuth authentication</td>
 
 379      *        <td>oAuthVersion</td>
 
 381      *        <td>Version http oAuth authentication</td>
 
 385      *        <td>contentType</td>
 
 387      *        <td>http content type to set in the http header</td>
 
 388      *        <td>usually application/json or application/xml</td>
 
 393      *        <td>should match request body format</td>
 
 394      *        <td>json or xml</td>
 
 397      *        <td>httpMethod</td>
 
 399      *        <td>http method to use when sending the request</td>
 
 400      *        <td>get post put delete patch</td>
 
 403      *        <td>responsePrefix</td>
 
 405      *        <td>location the response will be written to in context memory</td>
 
 406      *        <td>tmp.restapi.result</td>
 
 409      *        <td>listName[i]</td>
 
 411      *        <td>Used for processing XML responses with repeating
 
 412      *        elements.</td>vpn-information.vrf-details
 
 416      *        <td>skipSending</td>
 
 419      *        <td>true or false</td>
 
 422      *        <td>convertResponse</td>
 
 424      *        <td>whether the response should be converted</td>
 
 425      *        <td>true or false</td>
 
 428      *        <td>customHttpHeaders</td>
 
 430      *        <td>a list additional http headers to be passed in, follow the format in the example</td>
 
 431      *        <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
 
 434      *        <td>dumpHeaders</td>
 
 436      *        <td>when true writes http header content to context memory</td>
 
 437      *        <td>true or false</td>
 
 442      *        <td>used to retrieve username, password and url if partner store exists</td>
 
 446      *        <td>returnRequestPayload</td>
 
 448      *        <td>used to return payload built in the request</td>
 
 449      *        <td>true or false</td>
 
 453      * @param ctx Reference to context memory
 
 454      * @throws SvcLogicException
 
 456      * @see String#split(String, int)
 
 458     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 459         sendRequest(paramMap, ctx, null);
 
 462     protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
 
 463         throws SvcLogicException {
 
 465         HttpResponse r = new HttpResponse();
 
 467             handlePartner(paramMap);
 
 468             Parameters p = getParameters(paramMap, new Parameters());
 
 469             if (p.restapiUrl.contains(",") && retryPolicy == null) {
 
 470                 String[] urls = p.restapiUrl.split(",");
 
 471                 retryPolicy = new RetryPolicy(urls, urls.length * 2);
 
 472                 p.restapiUrl = urls[0];
 
 474             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 477             if (p.templateFileName != null) {
 
 478                 String reqTemplate = readFile(p.templateFileName);
 
 479                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 480             } else if (p.requestBody != null) {
 
 483             r = sendHttpRequest(req, p);
 
 484             setResponseStatus(ctx, p.responsePrefix, r);
 
 486             if (p.dumpHeaders && r.headers != null) {
 
 487                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 488                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 492             if (p.returnRequestPayload && req != null) {
 
 493                 ctx.setAttribute(pp + "httpRequest", req);
 
 496             if (r.body != null && r.body.trim().length() > 0) {
 
 497                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 499                 if (p.convertResponse) {
 
 500                     Map<String, String> mm = null;
 
 501                     if (p.format == Format.XML) {
 
 502                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 503                     } else if (p.format == Format.JSON) {
 
 504                         mm = JsonParser.convertToProperties(r.body);
 
 508                         for (Map.Entry<String, String> entry : mm.entrySet()) {
 
 509                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 514         } catch (SvcLogicException e) {
 
 515             boolean shouldRetry = false;
 
 516             if (e.getCause().getCause() instanceof SocketException) {
 
 520             log.error("Error sending the request: " + e.getMessage(), e);
 
 521             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 522             if (retryPolicy == null || !shouldRetry) {
 
 523                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 525                 log.debug(retryPolicy.getRetryMessage());
 
 527                     // calling getNextHostName increments the retry count so it should be called before shouldRetry
 
 528                     String retryString = retryPolicy.getNextHostName();
 
 529                     if (retryPolicy.shouldRetry()) {
 
 530                         paramMap.put(restapiUrlString, retryString);
 
 531                         log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
 
 533                         sendRequest(paramMap, ctx, retryPolicy);
 
 535                         log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
 
 536                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 538                 } catch (Exception ex) {
 
 539                     String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
 
 540                         + "has failed with error message " + ex.getMessage();
 
 541                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 546         if (r != null && r.code >= 300) {
 
 547             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 551     protected void handlePartner(Map<String, String> paramMap) {
 
 552         String partner = paramMap.get("partner");
 
 553         if (partner != null && partner.length() > 0) {
 
 554             PartnerDetails details = partnerStore.get(partner);
 
 555             paramMap.put(restapiUserKey, details.username);
 
 556             paramMap.put(restapiPasswordKey, details.password);
 
 557             if (paramMap.get(restapiUrlString) == null) {
 
 558                 paramMap.put(restapiUrlString, details.url);
 
 563     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
 
 564         log.info("Building {} started", format);
 
 565         long t1 = System.currentTimeMillis();
 
 566         String originalTemplate = template;
 
 568         template = expandRepeats(ctx, template, 1);
 
 570         Map<String, String> mm = new HashMap<>();
 
 571         for (String s : ctx.getAttributeKeySet()) {
 
 572             mm.put(s, ctx.getAttribute(s));
 
 575         StringBuilder ss = new StringBuilder();
 
 577         while (i < template.length()) {
 
 578             int i1 = template.indexOf("${", i);
 
 580                 ss.append(template.substring(i));
 
 584             int i2 = template.indexOf('}', i1 + 2);
 
 586                 throw new SvcLogicException("Template error: Matching } not found");
 
 589             String var1 = template.substring(i1 + 2, i2);
 
 590             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 591             if (value1 == null || value1.trim().length() == 0) {
 
 592                 // delete the whole element (line)
 
 593                 int i3 = template.lastIndexOf('\n', i1);
 
 597                 int i4 = template.indexOf('\n', i1);
 
 599                     i4 = template.length();
 
 603                     ss.append(template.substring(i, i3));
 
 607                 ss.append(template.substring(i, i1)).append(value1);
 
 612         String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
 
 613             : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
 
 615         if (format == Format.JSON) {
 
 616             req = XmlJsonUtil.removeLastCommaJson(req);
 
 619         long t2 = System.currentTimeMillis();
 
 620         log.info("Building {} completed. Time: {}", format, t2 - t1);
 
 625     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 626         StringBuilder newTemplate = new StringBuilder();
 
 628         while (k < template.length()) {
 
 629             int i1 = template.indexOf("${repeat:", k);
 
 631                 newTemplate.append(template.substring(k));
 
 635             int i2 = template.indexOf(':', i1 + 9);
 
 637                 throw new SvcLogicException(
 
 638                     "Template error: Context variable name followed by : is required after repeat");
 
 641             // Find the closing }, store in i3
 
 645             while (nn > 0 && i < template.length()) {
 
 646                 i3 = template.indexOf('}', i);
 
 648                     throw new SvcLogicException("Template error: Matching } not found");
 
 650                 int i32 = template.indexOf('{', i);
 
 651                 if (i32 >= 0 && i32 < i3) {
 
 660             String var1 = template.substring(i1 + 9, i2);
 
 661             String value1 = ctx.getAttribute(var1);
 
 662             log.info("     {}:{}", var1, value1);
 
 665                 n = Integer.parseInt(value1);
 
 666             } catch (NumberFormatException e) {
 
 667                 log.info("value1 not set or not a number, n will remain set at zero");
 
 670             newTemplate.append(template.substring(k, i1));
 
 672             String rpt = template.substring(i2 + 1, i3);
 
 674             for (int ii = 0; ii < n; ii++) {
 
 675                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 676                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 677                     int i4 = ss.lastIndexOf(',');
 
 679                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 682                 newTemplate.append(ss);
 
 689             return newTemplate.toString();
 
 692         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 695     protected String readFile(String fileName) throws SvcLogicException {
 
 697             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 698             return new String(encoded, "UTF-8");
 
 699         } catch (IOException | SecurityException e) {
 
 700             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
 
 704     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
 
 705         Parameters p = new Parameters();
 
 706         p.restapiUser = fp.user;
 
 707         p.restapiPassword = fp.password;
 
 708         p.oAuthConsumerKey = fp.oAuthConsumerKey;
 
 709         p.oAuthVersion = fp.oAuthVersion;
 
 710         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
 
 711         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
 
 712         p.authtype = fp.authtype;
 
 713         return addAuthType(c, p);
 
 716     public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
 
 717         if (p.authtype == AuthType.Unspecified) {
 
 718             if (p.restapiUser != null && p.restapiPassword != null) {
 
 719                 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 720             } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 721                 Feature oAuth1Feature =
 
 722                     OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 723                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 724                 client.register(oAuth1Feature);
 
 728             if (p.authtype == AuthType.DIGEST) {
 
 729                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 730                     client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
 
 732                     throw new SvcLogicException(
 
 733                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
 
 734                             + "parameters doesn't exist",
 
 737             } else if (p.authtype == AuthType.BASIC) {
 
 738                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 739                     client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
 
 741                     throw new SvcLogicException(
 
 742                         "oAUTH authentication type selected but all restapiUser and restapiPassword "
 
 743                             + "parameters doesn't exist",
 
 746             } else if (p.authtype == AuthType.OAUTH) {
 
 747                 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 748                     Feature oAuth1Feature = OAuth1ClientSupport
 
 749                         .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
 
 750                         .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
 
 751                     client.register(oAuth1Feature);
 
 753                     throw new SvcLogicException(
 
 754                         "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
 
 755                             + "and oAuthSignatureMethod parameters doesn't exist",
 
 764      * Receives the http response for the http request sent.
 
 766      * @param request request msg
 
 767      * @param p parameters
 
 768      * @return HTTP response
 
 769      * @throws SvcLogicException when sending http request fails
 
 771     public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
 
 773         SSLContext ssl = null;
 
 774         if (p.ssl && p.restapiUrl.startsWith("https")) {
 
 775             ssl = createSSLContext(p);
 
 780             HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
 
 781             client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
 
 783             client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
 
 785         setClientTimeouts(client);
 
 786         // Needed to support additional HTTP methods such as PATCH
 
 787         client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
 
 789         WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
 
 791         long t1 = System.currentTimeMillis();
 
 793         HttpResponse r = new HttpResponse();
 
 795         String accept = p.accept;
 
 796         if (accept == null) {
 
 797             accept = p.format == Format.XML ? "application/xml" : "application/json";
 
 800         String contentType = p.contentType;
 
 801         if (contentType == null) {
 
 802             contentType = accept + ";charset=UTF-8";
 
 805         if (!p.skipSending && !p.multipartFormData) {
 
 807             Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
 
 809             if (p.format == Format.NONE) {
 
 810                 invocationBuilder.header("", "");
 
 813             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 814                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 815                 for (String singlePair : keyValuePairs) {
 
 816                     int equalPosition = singlePair.indexOf('=');
 
 817                     invocationBuilder.header(singlePair.substring(0, equalPosition),
 
 818                         singlePair.substring(equalPosition + 1, singlePair.length()));
 
 822             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 824             invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
 
 829                 // When the HTTP operation has no body do not set the content-type
 
 830                 //setting content-type has caused errors with some servers when no body is present
 
 831                 if (request == null) {
 
 832                     response = invocationBuilder.method(p.httpMethod.toString());
 
 834                     log.info("Sending request below to url " + p.restapiUrl);
 
 836                     response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
 
 838             } catch (ProcessingException | IllegalStateException e) {
 
 839                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
 
 842             r.code = response.getStatus();
 
 843             r.headers = response.getStringHeaders();
 
 844             EntityTag etag = response.getEntityTag();
 
 846                 r.message = etag.getValue();
 
 848             if (response.hasEntity() && r.code != 204) {
 
 849                 r.body = response.readEntity(String.class);
 
 851         } else if (!p.skipSending && p.multipartFormData) {
 
 853             WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
 
 855             MultiPart multiPart = new MultiPart();
 
 856             multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
 
 858             FileDataBodyPart fileDataBodyPart =
 
 859                 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
 
 860             multiPart.bodyPart(fileDataBodyPart);
 
 863             Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
 
 865             if (p.format == Format.NONE) {
 
 866                 invocationBuilder.header("", "");
 
 869             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 870                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 871                 for (String singlePair : keyValuePairs) {
 
 872                     int equalPosition = singlePair.indexOf('=');
 
 873                     invocationBuilder.header(singlePair.substring(0, equalPosition),
 
 874                         singlePair.substring(equalPosition + 1, singlePair.length()));
 
 878             invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 884                     invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
 
 885             } catch (ProcessingException | IllegalStateException e) {
 
 886                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
 
 889             r.code = response.getStatus();
 
 890             r.headers = response.getStringHeaders();
 
 891             EntityTag etag = response.getEntityTag();
 
 893                 r.message = etag.getValue();
 
 895             if (response.hasEntity() && r.code != 204) {
 
 896                 r.body = response.readEntity(String.class);
 
 901         long t2 = System.currentTimeMillis();
 
 902         log.info(responseReceivedMessage, t2 - t1);
 
 903         log.info(responseHttpCodeMessage, r.code);
 
 904         log.info("HTTP response message: {}", r.message);
 
 905         logHeaders(r.headers);
 
 906         log.info("HTTP response: {}", r.body);
 
 911     protected SSLContext createSSLContext(Parameters p) {
 
 912         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
 
 913             System.setProperty("jsse.enableSNIExtension", "false");
 
 914             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 915             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 917             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 919             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 920             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 921             char[] pwd = p.keyStorePassword.toCharArray();
 
 925             SSLContext ctx = SSLContext.getInstance("TLS");
 
 926             ctx.init(kmf.getKeyManagers(), null, null);
 
 928         } catch (Exception e) {
 
 929             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 934     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 937         resp.message = errorMessage;
 
 938         String pp = prefix != null ? prefix + '.' : "";
 
 939         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
 
 940         ctx.setAttribute(pp + "response-message", resp.message);
 
 943     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 944         String pp = prefix != null ? prefix + '.' : "";
 
 945         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 946         ctx.setAttribute(pp + "response-message", r.message);
 
 949     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 950         HttpResponse r = null;
 
 952             FileParam p = getFileParameters(paramMap);
 
 953             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 955             r = sendHttpData(data, p);
 
 956             setResponseStatus(ctx, p.responsePrefix, r);
 
 958         } catch (SvcLogicException | IOException e) {
 
 959             log.error("Error sending the request: {}", e.getMessage(), e);
 
 961             r = new HttpResponse();
 
 963             r.message = e.getMessage();
 
 964             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
 965             setResponseStatus(ctx, prefix, r);
 
 968         if (r != null && r.code >= 300) {
 
 969             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 973     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 974         FileParam p = new FileParam();
 
 975         p.fileName = parseParam(paramMap, "fileName", true, null);
 
 976         p.url = parseParam(paramMap, "url", true, null);
 
 977         p.user = parseParam(paramMap, "user", false, null);
 
 978         p.password = parseParam(paramMap, "password", false, null);
 
 979         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 980         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
 981         String skipSendingStr = paramMap.get(skipSendingMessage);
 
 982         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 983         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 984         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 985         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 986         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 987         p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 991     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 994             UebParam p = getUebParameters(paramMap);
 
 996             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
1000             if (p.templateFileName == null) {
 
1001                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
1002                 p.templateFileName = defaultUebTemplateFileName;
 
1005             String reqTemplate = readFile(p.templateFileName);
 
1006             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
1007             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
1009             r = postOnUeb(req, p);
 
1010             setResponseStatus(ctx, p.responsePrefix, r);
 
1011             if (r.body != null) {
 
1012                 ctx.setAttribute(pp + "httpResponse", r.body);
 
1015         } catch (SvcLogicException e) {
 
1016             log.error("Error sending the request: {}", e.getMessage(), e);
 
1018             r = new HttpResponse();
 
1020             r.message = e.getMessage();
 
1021             String prefix = parseParam(paramMap, responsePrefix, false, null);
 
1022             setResponseStatus(ctx, prefix, r);
 
1025         if (r.code >= 300) {
 
1026             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
1030     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
1032         Client client = ClientBuilder.newBuilder().build();
 
1033         setClientTimeouts(client);
 
1034         client.property(ClientProperties.FOLLOW_REDIRECTS, true);
 
1035         WebTarget webTarget = addAuthType(client, p).target(p.url);
 
1037         log.info("Sending file");
 
1038         long t1 = System.currentTimeMillis();
 
1040         HttpResponse r = new HttpResponse();
 
1043         if (!p.skipSending) {
 
1044             String tt = "application/octet-stream";
 
1045             Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
 
1050                 if (p.httpMethod == HttpMethod.POST) {
 
1051                     response = invocationBuilder.post(Entity.entity(data, tt));
 
1052                 } else if (p.httpMethod == HttpMethod.PUT) {
 
1053                     response = invocationBuilder.put(Entity.entity(data, tt));
 
1055                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
1057             } catch (ProcessingException e) {
 
1058                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
 
1061             r.code = response.getStatus();
 
1062             r.headers = response.getStringHeaders();
 
1063             EntityTag etag = response.getEntityTag();
 
1065                 r.message = etag.getValue();
 
1067             if (response.hasEntity() && r.code != 204) {
 
1068                 r.body = response.readEntity(String.class);
 
1071             if (r.code == 301) {
 
1072                 String newUrl = response.getStringHeaders().getFirst("Location");
 
1074                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
1076                 webTarget = client.target(newUrl);
 
1077                 invocationBuilder = webTarget.request(tt).accept(tt);
 
1080                     if (p.httpMethod == HttpMethod.POST) {
 
1081                         response = invocationBuilder.post(Entity.entity(data, tt));
 
1082                     } else if (p.httpMethod == HttpMethod.PUT) {
 
1083                         response = invocationBuilder.put(Entity.entity(data, tt));
 
1085                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
1087                 } catch (ProcessingException e) {
 
1088                     throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
 
1091                 r.code = response.getStatus();
 
1092                 etag = response.getEntityTag();
 
1094                     r.message = etag.getValue();
 
1096                 if (response.hasEntity() && r.code != 204) {
 
1097                     r.body = response.readEntity(String.class);
 
1102         long t2 = System.currentTimeMillis();
 
1103         log.info(responseReceivedMessage, t2 - t1);
 
1104         log.info(responseHttpCodeMessage, r.code);
 
1105         log.info("HTTP response message: {}", r.message);
 
1106         logHeaders(r.headers);
 
1107         log.info("HTTP response: {}", r.body);
 
1112     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
1113         UebParam p = new UebParam();
 
1114         p.topic = parseParam(paramMap, "topic", true, null);
 
1115         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
1116         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
1117         p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
 
1118         String skipSendingStr = paramMap.get(skipSendingMessage);
 
1119         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
1123     protected void logProperties(Map<String, Object> mm) {
 
1124         List<String> ll = new ArrayList<>();
 
1125         for (Object o : mm.keySet()) {
 
1128         Collections.sort(ll);
 
1130         log.info("Properties:");
 
1131         for (String name : ll) {
 
1132             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
1136     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
1137         log.info("HTTP response headers:");
 
1143         List<String> ll = new ArrayList<>();
 
1144         for (Object o : mm.keySet()) {
 
1147         Collections.sort(ll);
 
1149         for (String name : ll) {
 
1150             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
1154     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
 
1155         String[] urls = uebServers.split(" ");
 
1156         for (int i = 0; i < urls.length; i++) {
 
1157             if (!urls[i].endsWith("/")) {
 
1160             urls[i] += "events/" + p.topic;
 
1163         Client client = ClientBuilder.newBuilder().build();
 
1164         setClientTimeouts(client);
 
1165         WebTarget webTarget = client.target(urls[0]);
 
1167         log.info("UEB URL: {}", urls[0]);
 
1168         log.info("Sending request:");
 
1170         long t1 = System.currentTimeMillis();
 
1172         HttpResponse r = new HttpResponse();
 
1175         if (!p.skipSending) {
 
1176             String tt = "application/json";
 
1177             String tt1 = tt + ";charset=UTF-8";
 
1180             Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
 
1183                 response = invocationBuilder.post(Entity.entity(request, tt1));
 
1184             } catch (ProcessingException e) {
 
1185                 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
 
1187             r.code = response.getStatus();
 
1188             r.headers = response.getStringHeaders();
 
1189             if (response.hasEntity()) {
 
1190                 r.body = response.readEntity(String.class);
 
1194         long t2 = System.currentTimeMillis();
 
1195         log.info(responseReceivedMessage, t2 - t1);
 
1196         log.info(responseHttpCodeMessage, r.code);
 
1197         logHeaders(r.headers);
 
1198         log.info("HTTP response:\n {}", r.body);
 
1203     public void setUebServers(String uebServers) {
 
1204         this.uebServers = uebServers;
 
1207     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
1208         this.defaultUebTemplateFileName = defaultUebTemplateFileName;
 
1211     protected void setClientTimeouts(Client client) {
 
1212         client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
 
1213         client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
 
1216     protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
 
1217         String stringValue = System.getProperty(propertyName);
 
1218         if (stringValue != null && stringValue.length() > 0) {
 
1220                 return Integer.valueOf(stringValue);
 
1221             } catch (NumberFormatException e) {
 
1222                 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
 
1225         return defaultValue;
 
1229     private static class FileParam {
 
1231         public String fileName;
 
1234         public String password;
 
1235         public HttpMethod httpMethod;
 
1236         public String responsePrefix;
 
1237         public boolean skipSending;
 
1238         public String oAuthConsumerKey;
 
1239         public String oAuthConsumerSecret;
 
1240         public String oAuthSignatureMethod;
 
1241         public String oAuthVersion;
 
1242         public AuthType authtype;
 
1245     private static class UebParam {
 
1247         public String topic;
 
1248         public String templateFileName;
 
1249         public String rootVarName;
 
1250         public String responsePrefix;
 
1251         public boolean skipSending;