2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
 
   7  * ================================================================================
 
   8  * Licensed under the Apache License, Version 2.0 (the "License");
 
   9  * you may not use this file except in compliance with the License.
 
  10  * You may obtain a copy of the License at
 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
 
  14  * Unless required by applicable law or agreed to in writing, software
 
  15  * distributed under the License is distributed on an "AS IS" BASIS,
 
  16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  17  * See the License for the specific language governing permissions and
 
  18  * limitations under the License.
 
  19  * ============LICENSE_END=========================================================
 
  22 package org.onap.ccsdk.sli.plugins.restapicall;
 
  24 import com.sun.jersey.api.client.ClientHandlerException;
 
  25 import com.sun.jersey.api.client.UniformInterfaceException;
 
  26 import java.io.FileInputStream;
 
  27 import java.io.IOException;
 
  28 import java.net.SocketException;
 
  30 import java.nio.file.Files;
 
  31 import java.nio.file.Paths;
 
  32 import java.security.KeyStore;
 
  33 import java.util.ArrayList;
 
  34 import java.util.Collections;
 
  35 import java.util.HashMap;
 
  36 import java.util.HashSet;
 
  37 import java.util.List;
 
  39 import java.util.Map.Entry;
 
  42 import javax.net.ssl.HostnameVerifier;
 
  43 import javax.net.ssl.HttpsURLConnection;
 
  44 import javax.net.ssl.KeyManagerFactory;
 
  45 import javax.net.ssl.SSLContext;
 
  46 import javax.net.ssl.SSLSession;
 
  47 import javax.ws.rs.core.EntityTag;
 
  48 import javax.ws.rs.core.MultivaluedMap;
 
  49 import javax.ws.rs.core.UriBuilder;
 
  51 import org.apache.commons.lang3.StringUtils;
 
  52 import org.codehaus.jettison.json.JSONException;
 
  53 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
  54 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
 
  55 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
 
  56 import org.slf4j.Logger;
 
  57 import org.slf4j.LoggerFactory;
 
  59 import com.sun.jersey.api.client.Client;
 
  60 import com.sun.jersey.api.client.ClientResponse;
 
  61 import com.sun.jersey.api.client.WebResource;
 
  62 import com.sun.jersey.api.client.config.ClientConfig;
 
  63 import com.sun.jersey.api.client.config.DefaultClientConfig;
 
  64 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
 
  65 import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
 
  66 import com.sun.jersey.oauth.client.OAuthClientFilter;
 
  67 import com.sun.jersey.oauth.signature.OAuthParameters;
 
  68 import com.sun.jersey.oauth.signature.OAuthSecrets;
 
  69 import com.sun.jersey.client.urlconnection.HTTPSProperties;
 
  71 public class RestapiCallNode implements SvcLogicJavaPlugin {
 
  73     private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
 
  75     private String uebServers;
 
  76     private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
 
  77     protected RetryPolicyStore retryPolicyStore;
 
  79     protected RetryPolicyStore getRetryPolicyStore() {
 
  80         return retryPolicyStore;
 
  83     public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
 
  84         this.retryPolicyStore = retryPolicyStore;
 
  87     public RestapiCallNode() {
 
  92      * Allows Directed Graphs  the ability to interact with REST APIs.
 
  93      * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
 
  95      *  <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
 
  97      *      <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>
 
  98      *      <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>
 
  99      *      <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
 
 100      *      <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
 
 101      *      <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
 
 102      *      <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
 
 103      *      <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
 
 104      *      <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
 
 105      *      <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>
 
 106      *      <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
 
 107      *      <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>
 
 108      *      <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>
 
 109      *      <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>
 
 110      *      <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
 
 111      *      <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
 
 112      *      <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>
 
 113      *      <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
 
 114      *      <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
 
 115      *      <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
 
 118      * @param ctx Reference to context memory
 
 119      * @throws SvcLogicException
 
 121      * @see String#split(String, int)
 
 123     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 124         sendRequest(paramMap, ctx, null);
 
 127     public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
 
 128             throws SvcLogicException {
 
 130         RetryPolicy retryPolicy = null;
 
 131         HttpResponse r = new HttpResponse();
 
 133             Parameters p = getParameters(paramMap);
 
 134             if (p.partner != null) {
 
 135                 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
 
 137             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 140             if (p.templateFileName != null) {
 
 141                 String reqTemplate = readFile(p.templateFileName);
 
 142                 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
 
 143             } else if (p.requestBody != null) {
 
 146             r = sendHttpRequest(req, p);
 
 147             setResponseStatus(ctx, p.responsePrefix, r);
 
 149             if (p.dumpHeaders && r.headers != null) {
 
 150                 for (Entry<String, List<String>> a : r.headers.entrySet()) {
 
 151                     ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
 
 155             if (p.returnRequestPayload && req != null) {
 
 156                 ctx.setAttribute(pp + "httpRequest", req);
 
 159             if (r.body != null && r.body.trim().length() > 0) {
 
 160                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 162                 if (p.convertResponse) {
 
 163                     Map<String, String> mm = null;
 
 164                     if (p.format == Format.XML)
 
 165                         mm = XmlParser.convertToProperties(r.body, p.listNameList);
 
 166                     else if (p.format == Format.JSON)
 
 167                         mm = JsonParser.convertToProperties(r.body);
 
 170                         for (Map.Entry<String,String> entry : mm.entrySet())
 
 171                             ctx.setAttribute(pp + entry.getKey(), entry.getValue());
 
 174         } catch (SvcLogicException e) {
 
 175             boolean shouldRetry = false;
 
 176             if (e.getCause().getCause() instanceof SocketException) {
 
 180             log.error("Error sending the request: " + e.getMessage(), e);
 
 181             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 182             if (retryPolicy == null || shouldRetry == false) {
 
 183                 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 185                 if (retryCount == null) {
 
 188                 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
 
 190                 log.debug(retryMessage);
 
 192                     retryCount = retryCount + 1;
 
 193                     if (retryCount < retryPolicy.getMaximumRetries() + 1) {
 
 194                         URI uri = new URI(paramMap.get("restapiUrl"));
 
 195                         String hostname = uri.getHost();
 
 196                         String retryString = retryPolicy.getNextHostName(uri.toString());
 
 197                         URI uriTwo = new URI(retryString);
 
 198                         URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
 
 199                                 uriTwo.getScheme()).build();
 
 200                         paramMap.put("restapiUrl", retryUri.toString());
 
 201                         log.debug("URL was set to {}", retryUri.toString());
 
 202                         log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
 
 203                             hostname, retryString);
 
 204                         log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
 
 205                         sendRequest(paramMap, ctx, retryCount);
 
 207                         log.debug("Maximum retries reached, calling setFailureResponseStatus.");
 
 208                         setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
 
 210                 } catch (Exception ex) {
 
 211                     log.error("Could not attempt retry.", ex);
 
 212                     String retryErrorMessage =
 
 213                             "Retry attempt has failed. No further retry shall be attempted, calling " +
 
 214                                 "setFailureResponseStatus.";
 
 215                     setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
 
 220         if (r != null && r.code >= 300)
 
 221             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 224     protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 225         Parameters p = new Parameters();
 
 226         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 227         p.requestBody = parseParam(paramMap, "requestBody", false, null);
 
 228         p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
 
 229         validateUrl(p.restapiUrl);
 
 230         p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
 
 231         p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
 
 232         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 233         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 234         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 235         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 236         p.contentType = parseParam(paramMap, "contentType", false, null);
 
 237         p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
 
 238         p.authtype = AuthType.fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 239         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 240         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 241         p.listNameList = getListNameList(paramMap);
 
 242         String skipSendingStr = paramMap.get("skipSending");
 
 243         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 244         p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
 
 245         p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
 
 246         p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
 
 247         p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
 
 248         p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
 
 249         p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
 
 250                 p.keyStorePassword != null;
 
 251         p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
 
 252         p.partner = parseParam(paramMap, "partner", false, null);
 
 253         p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
 
 254         p.returnRequestPayload = Boolean.valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
 
 258     private void validateUrl(String restapiUrl) throws SvcLogicException {
 
 260             URI.create(restapiUrl);
 
 261         } catch (IllegalArgumentException e) {
 
 262             throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
 
 266     protected Set<String> getListNameList(Map<String, String> paramMap) {
 
 267         Set<String> ll = new HashSet<>();
 
 268         for (Map.Entry<String,String> entry : paramMap.entrySet())
 
 269             if (entry.getKey().startsWith("listName"))
 
 270                 ll.add(entry.getValue());
 
 274     protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
 
 275             throws SvcLogicException {
 
 276         String s = paramMap.get(name);
 
 278         if (s == null || s.trim().length() == 0) {
 
 281             throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
 
 285         StringBuilder value = new StringBuilder();
 
 287         int i1 = s.indexOf('%');
 
 289             int i2 = s.indexOf('%', i1 + 1);
 
 293             String varName = s.substring(i1 + 1, i2);
 
 294             String varValue = System.getenv(varName);
 
 295             if (varValue == null)
 
 296                 varValue = "%" + varName + "%";
 
 298             value.append(s.substring(i, i1));
 
 299             value.append(varValue);
 
 302             i1 = s.indexOf('%', i);
 
 304         value.append(s.substring(i));
 
 306         log.info("Parameter {}: [{}]", name, value);
 
 307         return value.toString();
 
 310     protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
 
 311         throws SvcLogicException {
 
 312         log.info("Building {} started", format);
 
 313         long t1 = System.currentTimeMillis();
 
 315         template = expandRepeats(ctx, template, 1);
 
 317         Map<String, String> mm = new HashMap<>();
 
 318         for (String s : ctx.getAttributeKeySet())
 
 319             mm.put(s, ctx.getAttribute(s));
 
 321         StringBuilder ss = new StringBuilder();
 
 323         while (i < template.length()) {
 
 324             int i1 = template.indexOf("${", i);
 
 326                 ss.append(template.substring(i));
 
 330             int i2 = template.indexOf('}', i1 + 2);
 
 332                 throw new SvcLogicException("Template error: Matching } not found");
 
 334             String var1 = template.substring(i1 + 2, i2);
 
 335             String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
 
 336             // log.info(" " + var1 + ": " + value1);
 
 337             if (value1 == null || value1.trim().length() == 0) {
 
 338                 // delete the whole element (line)
 
 339                 int i3 = template.lastIndexOf('\n', i1);
 
 342                 int i4 = template.indexOf('\n', i1);
 
 344                     i4 = template.length();
 
 347                     ss.append(template.substring(i, i3));
 
 350                 ss.append(template.substring(i, i1)).append(value1);
 
 355         String req = format == Format.XML
 
 356                 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
 
 358         if (format == Format.JSON)
 
 359             req = XmlJsonUtil.removeLastCommaJson(req);
 
 361         long t2 = System.currentTimeMillis();
 
 362         log.info("Building {} completed. Time: {}", format, (t2 - t1));
 
 367     protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
 
 368         StringBuilder newTemplate = new StringBuilder();
 
 370         while (k < template.length()) {
 
 371             int i1 = template.indexOf("${repeat:", k);
 
 373                 newTemplate.append(template.substring(k));
 
 377             int i2 = template.indexOf(':', i1 + 9);
 
 379                 throw new SvcLogicException(
 
 380                         "Template error: Context variable name followed by : is required after repeat");
 
 382             // Find the closing }, store in i3
 
 386             while (nn > 0 && i < template.length()) {
 
 387                 i3 = template.indexOf('}', i);
 
 389                     throw new SvcLogicException("Template error: Matching } not found");
 
 390                 int i32 = template.indexOf('{', i);
 
 391                 if (i32 >= 0 && i32 < i3) {
 
 400             String var1 = template.substring(i1 + 9, i2);
 
 401             String value1 = ctx.getAttribute(var1);
 
 402             log.info("     {}:{}", var1, value1);
 
 405                 n = Integer.parseInt(value1);
 
 406             } catch (NumberFormatException e) {
 
 407                 log.info("value1 not set or not a number, n will remain set at zero");
 
 410             newTemplate.append(template.substring(k, i1));
 
 412             String rpt = template.substring(i2 + 1, i3);
 
 414             for (int ii = 0; ii < n; ii++) {
 
 415                 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
 
 416                 if (ii == n - 1 && ss.trim().endsWith(",")) {
 
 417                     int i4 = ss.lastIndexOf(',');
 
 419                         ss = ss.substring(0, i4) + ss.substring(i4 + 1);
 
 421                 newTemplate.append(ss);
 
 428             return newTemplate.toString();
 
 430         return expandRepeats(ctx, newTemplate.toString(), level + 1);
 
 433     protected String readFile(String fileName) throws SvcLogicException {
 
 435             byte[] encoded = Files.readAllBytes(Paths.get(fileName));
 
 436             return new String(encoded, "UTF-8");
 
 437         } catch (IOException | SecurityException e) {
 
 438             throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
 
 442     protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
 
 443         Parameters p = new Parameters();
 
 444         p.restapiUser = fp.user;
 
 445         p.restapiPassword = fp.password;
 
 446         p.oAuthConsumerKey = fp.oAuthConsumerKey;
 
 447         p.oAuthVersion = fp.oAuthVersion;
 
 448         p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
 
 449         p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
 
 450         p.authtype = fp.authtype;
 
 451         return addAuthType(c,p);
 
 454     protected Client addAuthType(Client client, Parameters p) throws SvcLogicException {
 
 455         if (p.authtype == AuthType.Unspecified){
 
 456             if (p.restapiUser != null && p.restapiPassword != null)
 
 457                 client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
 
 458             else if(p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
 
 459                     && p.oAuthSignatureMethod != null) {
 
 460                 OAuthParameters params = new OAuthParameters()
 
 461                         .signatureMethod(p.oAuthSignatureMethod)
 
 462                         .consumerKey(p.oAuthConsumerKey)
 
 463                         .version(p.oAuthVersion);
 
 465                 OAuthSecrets secrets = new OAuthSecrets()
 
 466                         .consumerSecret(p.oAuthConsumerSecret);
 
 467                 client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets));
 
 470             if (p.authtype == AuthType.DIGEST) {
 
 471                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 472                     client.addFilter(new HTTPDigestAuthFilter(p.restapiUser, p.restapiPassword));
 
 474                     throw new SvcLogicException("oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 475                                                         "parameters doesn't exist", new Throwable());
 
 477             } else if (p.authtype == AuthType.BASIC){
 
 478                 if (p.restapiUser != null && p.restapiPassword != null) {
 
 479                     client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
 
 481                     throw new SvcLogicException("oAUTH authentication type selected but all restapiUser and restapiPassword " +
 
 482                                                         "parameters doesn't exist", new Throwable());
 
 484             } else if(p.authtype == AuthType.OAUTH ) {
 
 485                 if(p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
 
 486                     OAuthParameters params = new OAuthParameters()
 
 487                             .signatureMethod(p.oAuthSignatureMethod)
 
 488                             .consumerKey(p.oAuthConsumerKey)
 
 489                             .version(p.oAuthVersion);
 
 491                     OAuthSecrets secrets = new OAuthSecrets()
 
 492                             .consumerSecret(p.oAuthConsumerSecret);
 
 493                     client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets));
 
 495                     throw new SvcLogicException("oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
 
 496                                                         "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
 
 503     protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
 
 505         ClientConfig config = new DefaultClientConfig();
 
 506         SSLContext ssl = null;
 
 507         if (p.ssl && p.restapiUrl.startsWith("https"))
 
 508             ssl = createSSLContext(p);
 
 510             HostnameVerifier hostnameVerifier = (hostname, session) -> true;
 
 512             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
 
 513                     new HTTPSProperties(hostnameVerifier, ssl));
 
 516         logProperties(config.getProperties());
 
 518         Client client = Client.create(config);
 
 519         client.setConnectTimeout(5000);
 
 520         WebResource webResource = addAuthType(client,p).resource(p.restapiUrl);
 
 522         log.info("Sending request:");
 
 524         long t1 = System.currentTimeMillis();
 
 526         HttpResponse r = new HttpResponse();
 
 529         if (!p.skipSending) {
 
 530             String tt = p.format == Format.XML ? "application/xml" : "application/json";
 
 531             String tt1 = tt + ";charset=UTF-8";
 
 532             if (p.contentType != null) {
 
 537             WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
 
 538             if(p.format == Format.NONE){
 
 539                 webResourceBuilder = webResource.header("","");
 
 542             if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
 
 543                 String[] keyValuePairs = p.customHttpHeaders.split(",");
 
 544                 for (String singlePair : keyValuePairs) {
 
 545                     int equalPosition = singlePair.indexOf('=');
 
 546                     webResourceBuilder.header(singlePair.substring(0, equalPosition),
 
 547                             singlePair.substring(equalPosition + 1, singlePair.length()));
 
 551             webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
 
 553             ClientResponse response;
 
 556                 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
 
 557             } catch (UniformInterfaceException | ClientHandlerException e) {
 
 558                 throw new SvcLogicException("Exception while sending http request to client "
 
 559                     + e.getLocalizedMessage(), e);
 
 562             r.code = response.getStatus();
 
 563             r.headers = response.getHeaders();
 
 564             EntityTag etag = response.getEntityTag();
 
 566                 r.message = etag.getValue();
 
 567             if (response.hasEntity() && r.code != 204)
 
 568                 r.body = response.getEntity(String.class);
 
 571         long t2 = System.currentTimeMillis();
 
 572         log.info("Response received. Time: {}", (t2 - t1));
 
 573         log.info("HTTP response code: {}", r.code);
 
 574         log.info("HTTP response message: {}", r.message);
 
 575         logHeaders(r.headers);
 
 576         log.info("HTTP response: {}", r.body);
 
 581     protected SSLContext createSSLContext(Parameters p) {
 
 582         try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
 
 583             System.setProperty("jsse.enableSNIExtension", "false");
 
 584             System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
 
 585             System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
 
 587             HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
 
 589             KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
 
 590             KeyStore ks = KeyStore.getInstance("PKCS12");
 
 591             char[] pwd = p.keyStorePassword.toCharArray();
 
 595             SSLContext ctx = SSLContext.getInstance("TLS");
 
 596             ctx.init(kmf.getKeyManagers(), null, null);
 
 598         } catch (Exception e) {
 
 599             log.error("Error creating SSLContext: {}", e.getMessage(), e);
 
 604     protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
 
 607         resp.message = errorMessage;
 
 608         String pp = prefix != null ? prefix + '.' : "";
 
 609         ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
 
 610         ctx.setAttribute(pp + "response-message", resp.message);
 
 613     protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
 
 614         String pp = prefix != null ? prefix + '.' : "";
 
 615         ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
 
 616         ctx.setAttribute(pp + "response-message", r.message);
 
 619     public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 620         HttpResponse r = null;
 
 622             FileParam p = getFileParameters(paramMap);
 
 623             byte[] data = Files.readAllBytes(Paths.get(p.fileName));
 
 625             r = sendHttpData(data, p);
 
 626             setResponseStatus(ctx, p.responsePrefix, r);
 
 628         } catch (SvcLogicException | IOException e) {
 
 629             log.error("Error sending the request: {}", e.getMessage(), e);
 
 631             r = new HttpResponse();
 
 633             r.message = e.getMessage();
 
 634             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 635             setResponseStatus(ctx, prefix, r);
 
 638         if (r != null && r.code >= 300)
 
 639             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 642     private static class FileParam {
 
 644         public String fileName;
 
 647         public String password;
 
 648         public HttpMethod httpMethod;
 
 649         public String responsePrefix;
 
 650         public boolean skipSending;
 
 651         public String oAuthConsumerKey;
 
 652         public String oAuthConsumerSecret;
 
 653         public String oAuthSignatureMethod;
 
 654         public String oAuthVersion;
 
 655         public AuthType authtype;
 
 658     private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 659         FileParam p = new FileParam();
 
 660         p.fileName = parseParam(paramMap, "fileName", true, null);
 
 661         p.url = parseParam(paramMap, "url", true, null);
 
 662         p.user = parseParam(paramMap, "user", false, null);
 
 663         p.password = parseParam(paramMap, "password", false, null);
 
 664         p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
 
 665         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 666         String skipSendingStr = paramMap.get("skipSending");
 
 667         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 668         p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
 
 669         p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
 
 670         p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
 
 671         p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
 
 672         p.authtype = AuthType.fromString(parseParam(paramMap, "authType", false, "unspecified"));
 
 676     protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
 
 677         Client client = Client.create();
 
 678         client.setConnectTimeout(5000);
 
 679         client.setFollowRedirects(true);
 
 680         WebResource webResource = addAuthType(client,p).resource(p.url);
 
 682         log.info("Sending file");
 
 683         long t1 = System.currentTimeMillis();
 
 685         HttpResponse r = new HttpResponse();
 
 688         if (!p.skipSending) {
 
 689             String tt = "application/octet-stream";
 
 691             ClientResponse response;
 
 693                 if (p.httpMethod == HttpMethod.POST)
 
 694                     response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
 
 695                 else if (p.httpMethod == HttpMethod.PUT)
 
 696                     response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
 
 698                     throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 699             } catch (UniformInterfaceException | ClientHandlerException e) {
 
 700                 throw new SvcLogicException("Exception while sending http request to client " +
 
 701                     e.getLocalizedMessage(), e);
 
 704             r.code = response.getStatus();
 
 705             r.headers = response.getHeaders();
 
 706             EntityTag etag = response.getEntityTag();
 
 708                 r.message = etag.getValue();
 
 709             if (response.hasEntity() && r.code != 204)
 
 710                 r.body = response.getEntity(String.class);
 
 713                 String newUrl = response.getHeaders().getFirst("Location");
 
 715                 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
 
 717                 webResource = client.resource(newUrl);
 
 720                     if (p.httpMethod == HttpMethod.POST)
 
 721                         response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
 
 722                     else if (p.httpMethod == HttpMethod.PUT)
 
 723                         response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
 
 725                         throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
 
 726                 } catch (UniformInterfaceException | ClientHandlerException e) {
 
 727                     throw new SvcLogicException("Exception while sending http request to client " +
 
 728                         e.getLocalizedMessage(), e);
 
 731                 r.code = response.getStatus();
 
 732                 etag = response.getEntityTag();
 
 734                     r.message = etag.getValue();
 
 735                 if (response.hasEntity() && r.code != 204)
 
 736                     r.body = response.getEntity(String.class);
 
 740         long t2 = System.currentTimeMillis();
 
 741         log.info("Response received. Time: {}", (t2 - t1));
 
 742         log.info("HTTP response code: {}", r.code);
 
 743         log.info("HTTP response message: {}", r.message);
 
 744         logHeaders(r.headers);
 
 745         log.info("HTTP response: {}", r.body);
 
 750     public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
 
 753             UebParam p = getUebParameters(paramMap);
 
 755             String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
 
 759             if (p.templateFileName == null) {
 
 760                 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
 
 761                 p.templateFileName = defaultUebTemplateFileName;
 
 764             String reqTemplate = readFile(p.templateFileName);
 
 765             reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
 
 766             req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
 
 768             r = postOnUeb(req, p);
 
 769             setResponseStatus(ctx, p.responsePrefix, r);
 
 771                 ctx.setAttribute(pp + "httpResponse", r.body);
 
 773         } catch (SvcLogicException e) {
 
 774             log.error("Error sending the request: {}", e.getMessage(), e);
 
 776             r = new HttpResponse();
 
 778             r.message = e.getMessage();
 
 779             String prefix = parseParam(paramMap, "responsePrefix", false, null);
 
 780             setResponseStatus(ctx, prefix, r);
 
 784             throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
 
 787     private static class UebParam {
 
 790         public String templateFileName;
 
 791         public String rootVarName;
 
 792         public String responsePrefix;
 
 793         public boolean skipSending;
 
 796     private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
 
 797         UebParam p = new UebParam();
 
 798         p.topic = parseParam(paramMap, "topic", true, null);
 
 799         p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
 
 800         p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
 
 801         p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
 
 802         String skipSendingStr = paramMap.get("skipSending");
 
 803         p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
 
 807     protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
 
 808         String[] urls = uebServers.split(" ");
 
 809         for (int i = 0; i < urls.length; i++) {
 
 810             if (!urls[i].endsWith("/"))
 
 812             urls[i] += "events/" + p.topic;
 
 815         Client client = Client.create();
 
 816         client.setConnectTimeout(5000);
 
 817         WebResource webResource = client.resource(urls[0]);
 
 819         log.info("UEB URL: {}", urls[0]);
 
 820         log.info("Sending request:");
 
 822         long t1 = System.currentTimeMillis();
 
 824         HttpResponse r = new HttpResponse();
 
 827         if (!p.skipSending) {
 
 828             String tt = "application/json";
 
 829             String tt1 = tt + ";charset=UTF-8";
 
 831             ClientResponse response;
 
 834                 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
 
 835             } catch (UniformInterfaceException | ClientHandlerException e) {
 
 836                 throw new SvcLogicException("Exception while posting http request to client " +
 
 837                     e.getLocalizedMessage(), e);
 
 840             r.code = response.getStatus();
 
 841             r.headers = response.getHeaders();
 
 842             if (response.hasEntity())
 
 843                 r.body = response.getEntity(String.class);
 
 846         long t2 = System.currentTimeMillis();
 
 847         log.info("Response received. Time: {}", (t2 - t1));
 
 848         log.info("HTTP response code: {}", r.code);
 
 849         logHeaders(r.headers);
 
 850         log.info("HTTP response:\n {}", r.body);
 
 855     protected void logProperties(Map<String, Object> mm) {
 
 856         List<String> ll = new ArrayList<>();
 
 857         for (Object o : mm.keySet())
 
 859         Collections.sort(ll);
 
 861         log.info("Properties:");
 
 862         for (String name : ll)
 
 863             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 866     protected void logHeaders(MultivaluedMap<String, String> mm) {
 
 867         log.info("HTTP response headers:");
 
 872         List<String> ll = new ArrayList<>();
 
 873         for (Object o : mm.keySet())
 
 875         Collections.sort(ll);
 
 877         for (String name : ll)
 
 878             log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
 
 881     public void setUebServers(String uebServers) {
 
 882         this.uebServers = uebServers;
 
 885     public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
 
 886         this.defaultUebTemplateFileName = defaultUebTemplateFileName;