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.onap.logging.filter.base.MetricLogClientFilter;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
79 public class RestapiCallNode implements SvcLogicJavaPlugin {
81 protected static final String PARTNERS_FILE_NAME = "partners.json";
82 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
83 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
84 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
85 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
86 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
88 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
89 private String uebServers;
90 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
92 private String responseReceivedMessage = "Response received. Time: {}";
93 private String responseHttpCodeMessage = "HTTP response code: {}";
94 private String requestPostingException = "Exception while posting http request to client ";
95 protected static final String skipSendingMessage = "skipSending";
96 protected static final String responsePrefix = "responsePrefix";
97 protected static final String restapiUrlString = "restapiUrl";
98 protected static final String restapiUserKey = "restapiUser";
99 protected static final String restapiPasswordKey = "restapiPassword";
100 protected Integer httpConnectTimeout;
101 protected Integer httpReadTimeout;
103 protected HashMap<String, PartnerDetails> partnerStore;
105 public RestapiCallNode() {
106 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
108 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
109 JSONObject partners = new JSONObject(jsonString);
110 partnerStore = new HashMap<>();
111 loadPartners(partners);
112 log.info("Partners support enabled");
113 } catch (Exception e) {
114 log.warn("Partners file could not be read, Partner support will not be enabled.", e);
117 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
118 Properties props = new Properties();
120 uebServers = props.getProperty("servers");
121 log.info("UEB support enabled");
122 } catch (Exception e) {
123 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
125 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
126 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
129 protected void loadPartners(JSONObject partners) {
130 Iterator<String> keys = partners.keys();
131 String partnerUserKey = "user";
132 String partnerPasswordKey = "password";
133 String partnerUrlKey = "url";
135 while (keys.hasNext()) {
136 String partnerKey = keys.next();
138 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
139 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
141 if (partnerObject.has(partnerUrlKey)) {
142 url = partnerObject.getString(partnerUrlKey);
144 String userName = partnerObject.getString(partnerUserKey);
145 String password = partnerObject.getString(partnerPasswordKey);
146 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
147 partnerStore.put(partnerKey, details);
148 log.info("mapped partner using partner key " + partnerKey);
150 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
152 } catch (JSONException e) {
153 log.info("Couldn't map the partner using partner key " + partnerKey, e);
158 /* Unobfuscate param value */
159 private static String getObfuscatedVal(String paramValue) {
160 String resValue = paramValue;
161 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
163 String paramStr = paramValue.substring(2, paramValue.length()-1);
164 if (paramStr != null && paramStr.length() > 0)
166 String val = System.getenv(paramStr);
167 if (val != null && val.length() > 0)
170 log.info("Obfuscated value RESET for param value:" + paramValue);
178 * Returns parameters from the parameter map.
180 * @param paramMap parameter map
181 * @param p parameters instance
182 * @return parameters filed instance
183 * @throws SvcLogicException when svc logic exception occurs
185 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
187 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
188 p.requestBody = parseParam(paramMap, "requestBody", false, null);
189 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
190 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
191 if (p.restapiUrlSuffix != null) {
192 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
195 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
196 validateUrl(p.restapiUrl);
198 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
199 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
200 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
201 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
202 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
203 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
204 p.contentType = parseParam(paramMap, "contentType", false, null);
205 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
206 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
207 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
208 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
209 p.listNameList = getListNameList(paramMap);
210 String skipSendingStr = paramMap.get(skipSendingMessage);
211 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
212 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
213 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
214 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
215 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
216 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
217 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
218 && p.keyStorePassword != null;
219 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
220 p.partner = parseParam(paramMap, "partner", false, null);
221 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
222 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
223 p.accept = parseParam(paramMap, "accept", false, null);
224 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
225 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
230 * Validates the given URL in the parameters.
232 * @param restapiUrl rest api URL
233 * @throws SvcLogicException when URL validation fails
235 private static void validateUrl(String restapiUrl) throws SvcLogicException {
236 if (restapiUrl.contains(",")) {
237 String[] urls = restapiUrl.split(",");
238 for (String url : urls) {
243 URI.create(restapiUrl);
244 } catch (IllegalArgumentException e) {
245 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
251 * Returns the list of list name.
253 * @param paramMap parameters map
254 * @return list of list name
256 private static Set<String> getListNameList(Map<String, String> paramMap) {
257 Set<String> ll = new HashSet<>();
258 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
259 if (entry.getKey().startsWith("listName")) {
260 ll.add(entry.getValue());
267 * Parses the parameter string map of property, validates if required, assigns default value if
268 * present and returns the value.
270 * @param paramMap string param map
271 * @param name name of the property
272 * @param required if value required
273 * @param def default value
274 * @return value of the property
275 * @throws SvcLogicException if required parameter value is empty
277 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
278 throws SvcLogicException {
279 String s = paramMap.get(name);
281 if (s == null || s.trim().length() == 0) {
285 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
289 StringBuilder value = new StringBuilder();
291 int i1 = s.indexOf('%');
293 int i2 = s.indexOf('%', i1 + 1);
298 String varName = s.substring(i1 + 1, i2);
299 String varValue = System.getenv(varName);
300 if (varValue == null) {
301 varValue = "%" + varName + "%";
304 value.append(s.substring(i, i1));
305 value.append(varValue);
308 i1 = s.indexOf('%', i);
310 value.append(s.substring(i));
312 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
314 return value.toString();
317 private static Object maskPassword(String name, Object value) {
318 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
319 for (String pwdName : pwdNames) {
320 if (name.contains(pwdName)) {
328 * Allows Directed Graphs the ability to interact with REST APIs.
330 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
334 * <th>Mandatory/Optional</th>
335 * <th>description</th>
336 * <th>example values</th></thead> <tbody>
338 * <td>templateFileName</td>
340 * <td>full path to template file that can be used to build a request</td>
341 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
344 * <td>restapiUrl</td>
346 * <td>url to send the request to</td>
347 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
350 * <td>restapiUser</td>
352 * <td>user name to use for http basic authentication</td>
356 * <td>restapiPassword</td>
358 * <td>unencrypted password to use for http basic authentication</td>
359 * <td>plain_password</td>
362 * <td>oAuthConsumerKey</td>
364 * <td>Consumer key to use for http oAuth authentication</td>
368 * <td>oAuthConsumerSecret</td>
370 * <td>Consumer secret to use for http oAuth authentication</td>
371 * <td>plain_secret</td>
374 * <td>oAuthSignatureMethod</td>
376 * <td>Consumer method to use for http oAuth authentication</td>
380 * <td>oAuthVersion</td>
382 * <td>Version http oAuth authentication</td>
386 * <td>contentType</td>
388 * <td>http content type to set in the http header</td>
389 * <td>usually application/json or application/xml</td>
394 * <td>should match request body format</td>
395 * <td>json or xml</td>
398 * <td>httpMethod</td>
400 * <td>http method to use when sending the request</td>
401 * <td>get post put delete patch</td>
404 * <td>responsePrefix</td>
406 * <td>location the response will be written to in context memory</td>
407 * <td>tmp.restapi.result</td>
410 * <td>listName[i]</td>
412 * <td>Used for processing XML responses with repeating
413 * elements.</td>vpn-information.vrf-details
417 * <td>skipSending</td>
420 * <td>true or false</td>
423 * <td>convertResponse</td>
425 * <td>whether the response should be converted</td>
426 * <td>true or false</td>
429 * <td>customHttpHeaders</td>
431 * <td>a list additional http headers to be passed in, follow the format in the example</td>
432 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
435 * <td>dumpHeaders</td>
437 * <td>when true writes http header content to context memory</td>
438 * <td>true or false</td>
443 * <td>used to retrieve username, password and url if partner store exists</td>
447 * <td>returnRequestPayload</td>
449 * <td>used to return payload built in the request</td>
450 * <td>true or false</td>
454 * @param ctx Reference to context memory
455 * @throws SvcLogicException
457 * @see String#split(String, int)
459 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
460 sendRequest(paramMap, ctx, null);
463 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
464 throws SvcLogicException {
466 HttpResponse r = new HttpResponse();
468 handlePartner(paramMap);
469 Parameters p = getParameters(paramMap, new Parameters());
470 if (p.restapiUrl.contains(",") && retryPolicy == null) {
471 String[] urls = p.restapiUrl.split(",");
472 retryPolicy = new RetryPolicy(urls, urls.length * 2);
473 p.restapiUrl = urls[0];
475 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
478 if (p.templateFileName != null) {
479 String reqTemplate = readFile(p.templateFileName);
480 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
481 } else if (p.requestBody != null) {
484 r = sendHttpRequest(req, p);
485 setResponseStatus(ctx, p.responsePrefix, r);
487 if (p.dumpHeaders && r.headers != null) {
488 for (Entry<String, List<String>> a : r.headers.entrySet()) {
489 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
493 if (p.returnRequestPayload && req != null) {
494 ctx.setAttribute(pp + "httpRequest", req);
497 if (r.body != null && r.body.trim().length() > 0) {
498 ctx.setAttribute(pp + "httpResponse", r.body);
500 if (p.convertResponse) {
501 Map<String, String> mm = null;
502 if (p.format == Format.XML) {
503 mm = XmlParser.convertToProperties(r.body, p.listNameList);
504 } else if (p.format == Format.JSON) {
505 mm = JsonParser.convertToProperties(r.body);
509 for (Map.Entry<String, String> entry : mm.entrySet()) {
510 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
515 } catch (SvcLogicException e) {
516 boolean shouldRetry = false;
517 if (e.getCause().getCause() instanceof SocketException) {
521 log.error("Error sending the request: " + e.getMessage(), e);
522 String prefix = parseParam(paramMap, responsePrefix, false, null);
523 if (retryPolicy == null || !shouldRetry) {
524 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
526 log.debug(retryPolicy.getRetryMessage());
528 // calling getNextHostName increments the retry count so it should be called before shouldRetry
529 String retryString = retryPolicy.getNextHostName();
530 if (retryPolicy.shouldRetry()) {
531 paramMap.put(restapiUrlString, retryString);
532 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
534 sendRequest(paramMap, ctx, retryPolicy);
536 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
537 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
539 } catch (Exception ex) {
540 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
541 + "has failed with error message " + ex.getMessage();
542 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
547 if (r != null && r.code >= 300) {
548 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
552 protected void handlePartner(Map<String, String> paramMap) {
553 String partner = paramMap.get("partner");
554 if (partner != null && partner.length() > 0) {
555 PartnerDetails details = partnerStore.get(partner);
556 paramMap.put(restapiUserKey, details.username);
557 paramMap.put(restapiPasswordKey, details.password);
558 if (paramMap.get(restapiUrlString) == null) {
559 paramMap.put(restapiUrlString, details.url);
564 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
565 log.info("Building {} started", format);
566 long t1 = System.currentTimeMillis();
567 String originalTemplate = template;
569 template = expandRepeats(ctx, template, 1);
571 Map<String, String> mm = new HashMap<>();
572 for (String s : ctx.getAttributeKeySet()) {
573 mm.put(s, ctx.getAttribute(s));
576 StringBuilder ss = new StringBuilder();
578 while (i < template.length()) {
579 int i1 = template.indexOf("${", i);
581 ss.append(template.substring(i));
585 int i2 = template.indexOf('}', i1 + 2);
587 throw new SvcLogicException("Template error: Matching } not found");
590 String var1 = template.substring(i1 + 2, i2);
591 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
592 if (value1 == null || value1.trim().length() == 0) {
593 // delete the whole element (line)
594 int i3 = template.lastIndexOf('\n', i1);
598 int i4 = template.indexOf('\n', i1);
600 i4 = template.length();
604 ss.append(template.substring(i, i3));
608 ss.append(template.substring(i, i1)).append(value1);
613 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
614 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
616 if (format == Format.JSON) {
617 req = XmlJsonUtil.removeLastCommaJson(req);
620 long t2 = System.currentTimeMillis();
621 log.info("Building {} completed. Time: {}", format, t2 - t1);
626 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
627 StringBuilder newTemplate = new StringBuilder();
629 while (k < template.length()) {
630 int i1 = template.indexOf("${repeat:", k);
632 newTemplate.append(template.substring(k));
636 int i2 = template.indexOf(':', i1 + 9);
638 throw new SvcLogicException(
639 "Template error: Context variable name followed by : is required after repeat");
642 // Find the closing }, store in i3
646 while (nn > 0 && i < template.length()) {
647 i3 = template.indexOf('}', i);
649 throw new SvcLogicException("Template error: Matching } not found");
651 int i32 = template.indexOf('{', i);
652 if (i32 >= 0 && i32 < i3) {
661 String var1 = template.substring(i1 + 9, i2);
662 String value1 = ctx.getAttribute(var1);
663 log.info(" {}:{}", var1, value1);
666 n = Integer.parseInt(value1);
667 } catch (NumberFormatException e) {
668 log.info("value1 not set or not a number, n will remain set at zero");
671 newTemplate.append(template.substring(k, i1));
673 String rpt = template.substring(i2 + 1, i3);
675 for (int ii = 0; ii < n; ii++) {
676 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
677 if (ii == n - 1 && ss.trim().endsWith(",")) {
678 int i4 = ss.lastIndexOf(',');
680 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
683 newTemplate.append(ss);
690 return newTemplate.toString();
693 return expandRepeats(ctx, newTemplate.toString(), level + 1);
696 protected String readFile(String fileName) throws SvcLogicException {
698 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
699 return new String(encoded, "UTF-8");
700 } catch (IOException | SecurityException e) {
701 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
705 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
706 Parameters p = new Parameters();
707 p.restapiUser = fp.user;
708 p.restapiPassword = fp.password;
709 p.oAuthConsumerKey = fp.oAuthConsumerKey;
710 p.oAuthVersion = fp.oAuthVersion;
711 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
712 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
713 p.authtype = fp.authtype;
714 return addAuthType(c, p);
717 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
718 if (p.authtype == AuthType.Unspecified) {
719 if (p.restapiUser != null && p.restapiPassword != null) {
720 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
721 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
722 Feature oAuth1Feature =
723 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
724 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
725 client.register(oAuth1Feature);
729 if (p.authtype == AuthType.DIGEST) {
730 if (p.restapiUser != null && p.restapiPassword != null) {
731 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
733 throw new SvcLogicException(
734 "oAUTH authentication type selected but all restapiUser and restapiPassword "
735 + "parameters doesn't exist",
738 } else if (p.authtype == AuthType.BASIC) {
739 if (p.restapiUser != null && p.restapiPassword != null) {
740 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
742 throw new SvcLogicException(
743 "oAUTH authentication type selected but all restapiUser and restapiPassword "
744 + "parameters doesn't exist",
747 } else if (p.authtype == AuthType.OAUTH) {
748 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
749 Feature oAuth1Feature = OAuth1ClientSupport
750 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
751 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
752 client.register(oAuth1Feature);
754 throw new SvcLogicException(
755 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
756 + "and oAuthSignatureMethod parameters doesn't exist",
765 * Receives the http response for the http request sent.
767 * @param request request msg
768 * @param p parameters
769 * @return HTTP response
770 * @throws SvcLogicException when sending http request fails
772 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
774 SSLContext ssl = null;
775 if (p.ssl && p.restapiUrl.startsWith("https")) {
776 ssl = createSSLContext(p);
781 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
782 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
784 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
786 setClientTimeouts(client);
787 // Needed to support additional HTTP methods such as PATCH
788 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
789 client.register(new MetricLogClientFilter());
790 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
792 long t1 = System.currentTimeMillis();
794 HttpResponse r = new HttpResponse();
796 String accept = p.accept;
797 if (accept == null) {
798 accept = p.format == Format.XML ? "application/xml" : "application/json";
801 String contentType = p.contentType;
802 if (contentType == null) {
803 contentType = accept + ";charset=UTF-8";
806 if (!p.skipSending && !p.multipartFormData) {
808 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
810 if (p.format == Format.NONE) {
811 invocationBuilder.header("", "");
814 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
815 String[] keyValuePairs = p.customHttpHeaders.split(",");
816 for (String singlePair : keyValuePairs) {
817 int equalPosition = singlePair.indexOf('=');
818 invocationBuilder.header(singlePair.substring(0, equalPosition),
819 singlePair.substring(equalPosition + 1, singlePair.length()));
823 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
828 // When the HTTP operation has no body do not set the content-type
829 //setting content-type has caused errors with some servers when no body is present
830 if (request == null) {
831 response = invocationBuilder.method(p.httpMethod.toString());
833 log.info("Sending request below to url " + p.restapiUrl);
835 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
837 } catch (ProcessingException | IllegalStateException e) {
838 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
841 r.code = response.getStatus();
842 r.headers = response.getStringHeaders();
843 EntityTag etag = response.getEntityTag();
845 r.message = etag.getValue();
847 if (response.hasEntity() && r.code != 204) {
848 r.body = response.readEntity(String.class);
850 } else if (!p.skipSending && p.multipartFormData) {
852 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
854 MultiPart multiPart = new MultiPart();
855 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
857 FileDataBodyPart fileDataBodyPart =
858 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
859 multiPart.bodyPart(fileDataBodyPart);
862 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
864 if (p.format == Format.NONE) {
865 invocationBuilder.header("", "");
868 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
869 String[] keyValuePairs = p.customHttpHeaders.split(",");
870 for (String singlePair : keyValuePairs) {
871 int equalPosition = singlePair.indexOf('=');
872 invocationBuilder.header(singlePair.substring(0, equalPosition),
873 singlePair.substring(equalPosition + 1, singlePair.length()));
877 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
883 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
884 } catch (ProcessingException | IllegalStateException e) {
885 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
888 r.code = response.getStatus();
889 r.headers = response.getStringHeaders();
890 EntityTag etag = response.getEntityTag();
892 r.message = etag.getValue();
894 if (response.hasEntity() && r.code != 204) {
895 r.body = response.readEntity(String.class);
900 long t2 = System.currentTimeMillis();
901 log.info(responseReceivedMessage, t2 - t1);
902 log.info(responseHttpCodeMessage, r.code);
903 log.info("HTTP response message: {}", r.message);
904 logHeaders(r.headers);
905 log.info("HTTP response: {}", r.body);
910 protected SSLContext createSSLContext(Parameters p) {
911 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
912 System.setProperty("jsse.enableSNIExtension", "false");
913 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
914 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
916 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
918 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
919 KeyStore ks = KeyStore.getInstance("PKCS12");
920 char[] pwd = p.keyStorePassword.toCharArray();
924 SSLContext ctx = SSLContext.getInstance("TLS");
925 ctx.init(kmf.getKeyManagers(), null, null);
927 } catch (Exception e) {
928 log.error("Error creating SSLContext: {}", e.getMessage(), e);
933 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
936 resp.message = errorMessage;
937 String pp = prefix != null ? prefix + '.' : "";
938 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
939 ctx.setAttribute(pp + "response-message", resp.message);
942 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
943 String pp = prefix != null ? prefix + '.' : "";
944 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
945 ctx.setAttribute(pp + "response-message", r.message);
948 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
949 HttpResponse r = null;
951 FileParam p = getFileParameters(paramMap);
952 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
954 r = sendHttpData(data, p);
955 setResponseStatus(ctx, p.responsePrefix, r);
957 } catch (SvcLogicException | IOException e) {
958 log.error("Error sending the request: {}", e.getMessage(), e);
960 r = new HttpResponse();
962 r.message = e.getMessage();
963 String prefix = parseParam(paramMap, responsePrefix, false, null);
964 setResponseStatus(ctx, prefix, r);
967 if (r != null && r.code >= 300) {
968 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
972 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
973 FileParam p = new FileParam();
974 p.fileName = parseParam(paramMap, "fileName", true, null);
975 p.url = parseParam(paramMap, "url", true, null);
976 p.user = parseParam(paramMap, "user", false, null);
977 p.password = parseParam(paramMap, "password", false, null);
978 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
979 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
980 String skipSendingStr = paramMap.get(skipSendingMessage);
981 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
982 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
983 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
984 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
985 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
986 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
990 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
993 UebParam p = getUebParameters(paramMap);
995 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
999 if (p.templateFileName == null) {
1000 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1001 p.templateFileName = defaultUebTemplateFileName;
1004 String reqTemplate = readFile(p.templateFileName);
1005 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1006 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1008 r = postOnUeb(req, p);
1009 setResponseStatus(ctx, p.responsePrefix, r);
1010 if (r.body != null) {
1011 ctx.setAttribute(pp + "httpResponse", r.body);
1014 } catch (SvcLogicException e) {
1015 log.error("Error sending the request: {}", e.getMessage(), e);
1017 r = new HttpResponse();
1019 r.message = e.getMessage();
1020 String prefix = parseParam(paramMap, responsePrefix, false, null);
1021 setResponseStatus(ctx, prefix, r);
1024 if (r.code >= 300) {
1025 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1029 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
1031 Client client = ClientBuilder.newBuilder().build();
1032 setClientTimeouts(client);
1033 client.property(ClientProperties.FOLLOW_REDIRECTS, true);
1034 WebTarget webTarget = addAuthType(client, p).target(p.url);
1036 log.info("Sending file");
1037 long t1 = System.currentTimeMillis();
1039 HttpResponse r = new HttpResponse();
1042 if (!p.skipSending) {
1043 String tt = "application/octet-stream";
1044 Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
1049 if (p.httpMethod == HttpMethod.POST) {
1050 response = invocationBuilder.post(Entity.entity(data, tt));
1051 } else if (p.httpMethod == HttpMethod.PUT) {
1052 response = invocationBuilder.put(Entity.entity(data, tt));
1054 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1056 } catch (ProcessingException e) {
1057 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1060 r.code = response.getStatus();
1061 r.headers = response.getStringHeaders();
1062 EntityTag etag = response.getEntityTag();
1064 r.message = etag.getValue();
1066 if (response.hasEntity() && r.code != 204) {
1067 r.body = response.readEntity(String.class);
1070 if (r.code == 301) {
1071 String newUrl = response.getStringHeaders().getFirst("Location");
1073 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
1075 webTarget = client.target(newUrl);
1076 invocationBuilder = webTarget.request(tt).accept(tt);
1079 if (p.httpMethod == HttpMethod.POST) {
1080 response = invocationBuilder.post(Entity.entity(data, tt));
1081 } else if (p.httpMethod == HttpMethod.PUT) {
1082 response = invocationBuilder.put(Entity.entity(data, tt));
1084 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1086 } catch (ProcessingException e) {
1087 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1090 r.code = response.getStatus();
1091 etag = response.getEntityTag();
1093 r.message = etag.getValue();
1095 if (response.hasEntity() && r.code != 204) {
1096 r.body = response.readEntity(String.class);
1101 long t2 = System.currentTimeMillis();
1102 log.info(responseReceivedMessage, t2 - t1);
1103 log.info(responseHttpCodeMessage, r.code);
1104 log.info("HTTP response message: {}", r.message);
1105 logHeaders(r.headers);
1106 log.info("HTTP response: {}", r.body);
1111 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1112 UebParam p = new UebParam();
1113 p.topic = parseParam(paramMap, "topic", true, null);
1114 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1115 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1116 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1117 String skipSendingStr = paramMap.get(skipSendingMessage);
1118 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1122 protected void logProperties(Map<String, Object> mm) {
1123 List<String> ll = new ArrayList<>();
1124 for (Object o : mm.keySet()) {
1127 Collections.sort(ll);
1129 log.info("Properties:");
1130 for (String name : ll) {
1131 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1135 protected void logHeaders(MultivaluedMap<String, String> mm) {
1136 log.info("HTTP response headers:");
1142 List<String> ll = new ArrayList<>();
1143 for (Object o : mm.keySet()) {
1146 Collections.sort(ll);
1148 for (String name : ll) {
1149 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1153 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1154 String[] urls = uebServers.split(" ");
1155 for (int i = 0; i < urls.length; i++) {
1156 if (!urls[i].endsWith("/")) {
1159 urls[i] += "events/" + p.topic;
1162 Client client = ClientBuilder.newBuilder().build();
1163 setClientTimeouts(client);
1164 WebTarget webTarget = client.target(urls[0]);
1166 log.info("UEB URL: {}", urls[0]);
1167 log.info("Sending request:");
1169 long t1 = System.currentTimeMillis();
1171 HttpResponse r = new HttpResponse();
1174 if (!p.skipSending) {
1175 String tt = "application/json";
1176 String tt1 = tt + ";charset=UTF-8";
1179 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1182 response = invocationBuilder.post(Entity.entity(request, tt1));
1183 } catch (ProcessingException e) {
1184 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1186 r.code = response.getStatus();
1187 r.headers = response.getStringHeaders();
1188 if (response.hasEntity()) {
1189 r.body = response.readEntity(String.class);
1193 long t2 = System.currentTimeMillis();
1194 log.info(responseReceivedMessage, t2 - t1);
1195 log.info(responseHttpCodeMessage, r.code);
1196 logHeaders(r.headers);
1197 log.info("HTTP response:\n {}", r.body);
1202 public void setUebServers(String uebServers) {
1203 this.uebServers = uebServers;
1206 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1207 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1210 protected void setClientTimeouts(Client client) {
1211 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1212 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1215 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1216 String stringValue = System.getProperty(propertyName);
1217 if (stringValue != null && stringValue.length() > 0) {
1219 return Integer.valueOf(stringValue);
1220 } catch (NumberFormatException e) {
1221 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1224 return defaultValue;
1228 private static class FileParam {
1230 public String fileName;
1233 public String password;
1234 public HttpMethod httpMethod;
1235 public String responsePrefix;
1236 public boolean skipSending;
1237 public String oAuthConsumerKey;
1238 public String oAuthConsumerSecret;
1239 public String oAuthSignatureMethod;
1240 public String oAuthVersion;
1241 public AuthType authtype;
1244 private static class UebParam {
1246 public String topic;
1247 public String templateFileName;
1248 public String rootVarName;
1249 public String responsePrefix;
1250 public boolean skipSending;