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;
28 import java.io.BufferedReader;
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.io.InputStreamReader;
33 import java.io.OutputStream;
34 import java.net.HttpURLConnection;
35 import java.net.ProtocolException;
36 import java.net.SocketException;
39 import java.nio.file.Files;
40 import java.nio.file.Paths;
41 import java.security.KeyStore;
42 import java.util.ArrayList;
43 import java.util.Base64;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.Iterator;
48 import java.util.List;
50 import java.util.Map.Entry;
51 import java.util.Properties;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55 import javax.net.ssl.HttpsURLConnection;
56 import javax.net.ssl.KeyManagerFactory;
57 import javax.net.ssl.SSLContext;
58 import javax.ws.rs.ProcessingException;
59 import javax.ws.rs.client.Client;
60 import javax.ws.rs.client.ClientBuilder;
61 import javax.ws.rs.client.Entity;
62 import javax.ws.rs.client.Invocation;
63 import javax.ws.rs.client.WebTarget;
64 import javax.ws.rs.core.EntityTag;
65 import javax.ws.rs.core.Feature;
66 import javax.ws.rs.core.MediaType;
67 import javax.ws.rs.core.MultivaluedMap;
68 import javax.ws.rs.core.Response;
69 import javax.ws.rs.core.UriBuilder;
70 import org.apache.commons.lang3.StringUtils;
71 import org.codehaus.jettison.json.JSONException;
72 import org.codehaus.jettison.json.JSONObject;
73 import org.glassfish.jersey.client.ClientProperties;
74 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
75 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
76 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
77 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
78 import org.glassfish.jersey.media.multipart.MultiPart;
79 import org.glassfish.jersey.media.multipart.MultiPartFeature;
80 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
81 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
82 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
83 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
84 import org.onap.logging.filter.base.HttpURLConnectionMetricUtil;
85 import org.onap.logging.filter.base.MetricLogClientFilter;
86 import org.onap.logging.filter.base.ONAPComponents;
87 import org.onap.logging.ref.slf4j.ONAPLogConstants;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 public class RestapiCallNode implements SvcLogicJavaPlugin {
94 protected static final String PARTNERS_FILE_NAME = "partners.json";
95 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
96 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
97 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
98 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
99 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
101 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
102 private String uebServers;
103 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
105 private String responseReceivedMessage = "Response received. Time: {}";
106 private String responseHttpCodeMessage = "HTTP response code: {}";
107 private String requestPostingException = "Exception while posting http request to client ";
108 protected static final String skipSendingMessage = "skipSending";
109 protected static final String responsePrefix = "responsePrefix";
110 protected static final String restapiUrlString = "restapiUrl";
111 protected static final String restapiUserKey = "restapiUser";
112 protected static final String restapiPasswordKey = "restapiPassword";
113 protected Integer httpConnectTimeout;
114 protected Integer httpReadTimeout;
116 protected HashMap<String, PartnerDetails> partnerStore;
117 private static final Pattern retryPattern = Pattern.compile(".*,(http|https):.*");
119 public RestapiCallNode() {
120 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
122 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
123 JSONObject partners = new JSONObject(jsonString);
124 partnerStore = new HashMap<>();
125 loadPartners(partners);
126 log.info("Partners support enabled");
127 } catch (Exception e) {
128 log.warn("Partners file could not be read, Partner support will not be enabled. " + e.getMessage());
131 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
132 Properties props = new Properties();
134 uebServers = props.getProperty("servers");
135 log.info("UEB support enabled");
136 } catch (Exception e) {
137 log.warn("UEB properties could not be read, UEB support will not be enabled. " + e.getMessage());
139 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
140 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
143 @SuppressWarnings("unchecked")
144 protected void loadPartners(JSONObject partners) {
145 Iterator<String> keys = partners.keys();
146 String partnerUserKey = "user";
147 String partnerPasswordKey = "password";
148 String partnerUrlKey = "url";
150 while (keys.hasNext()) {
151 String partnerKey = keys.next();
153 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
154 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
156 if (partnerObject.has(partnerUrlKey)) {
157 url = partnerObject.getString(partnerUrlKey);
159 String userName = partnerObject.getString(partnerUserKey);
160 String password = partnerObject.getString(partnerPasswordKey);
161 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
162 partnerStore.put(partnerKey, details);
163 log.info("mapped partner using partner key " + partnerKey);
165 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
167 } catch (JSONException e) {
168 log.info("Couldn't map the partner using partner key " + partnerKey, e);
173 /* Unobfuscate param value */
174 private static String getObfuscatedVal(String paramValue) {
175 String resValue = paramValue;
176 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
178 String paramStr = paramValue.substring(2, paramValue.length()-1);
179 if (paramStr != null && paramStr.length() > 0)
181 String val = System.getenv(paramStr);
182 if (val != null && val.length() > 0)
185 log.info("Obfuscated value RESET for param value:" + paramValue);
193 * Returns parameters from the parameter map.
195 * @param paramMap parameter map
196 * @param p parameters instance
197 * @return parameters filed instance
198 * @throws SvcLogicException when svc logic exception occurs
200 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
202 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
203 p.requestBody = parseParam(paramMap, "requestBody", false, null);
204 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
205 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
206 if (p.restapiUrlSuffix != null) {
207 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
210 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
211 validateUrl(p.restapiUrl);
213 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
214 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
215 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
216 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
217 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
218 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
219 p.contentType = parseParam(paramMap, "contentType", false, null);
220 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
221 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
222 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
223 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
224 p.listNameList = getListNameList(paramMap);
225 String skipSendingStr = paramMap.get(skipSendingMessage);
226 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
227 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
228 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
229 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
230 p.ssl = p.keyStoreFileName != null && p.keyStorePassword != null;
231 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
232 p.partner = parseParam(paramMap, "partner", false, null);
233 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
234 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
235 p.accept = parseParam(paramMap, "accept", false, null);
236 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
237 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
238 p.targetEntity = parseParam(paramMap, "targetEntity", false, null);
243 * Validates the given URL in the parameters.
245 * @param restapiUrl rest api URL
246 * @throws SvcLogicException when URL validation fails
248 private static void validateUrl(String restapiUrl) throws SvcLogicException {
249 if (containsMultipleUrls(restapiUrl)) {
250 String[] urls = getMultipleUrls(restapiUrl);
251 for (String url : urls) {
256 URI.create(restapiUrl);
257 } catch (IllegalArgumentException e) {
258 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
264 * Returns the list of list name.
266 * @param paramMap parameters map
267 * @return list of list name
269 private static Set<String> getListNameList(Map<String, String> paramMap) {
270 Set<String> ll = new HashSet<>();
271 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
272 if (entry.getKey().startsWith("listName")) {
273 ll.add(entry.getValue());
280 * Parses the parameter string map of property, validates if required, assigns default value if
281 * present and returns the value.
283 * @param paramMap string param map
284 * @param name name of the property
285 * @param required if value required
286 * @param def default value
287 * @return value of the property
288 * @throws SvcLogicException if required parameter value is empty
290 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
291 throws SvcLogicException {
292 String s = paramMap.get(name);
294 if (s == null || s.trim().length() == 0) {
298 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
302 StringBuilder value = new StringBuilder();
304 int i1 = s.indexOf('%');
306 int i2 = s.indexOf('%', i1 + 1);
311 String varName = s.substring(i1 + 1, i2);
312 String varValue = System.getenv(varName);
313 if (varValue == null) {
314 varValue = "%" + varName + "%";
317 value.append(s.substring(i, i1));
318 value.append(varValue);
321 i1 = s.indexOf('%', i);
323 value.append(s.substring(i));
325 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
327 return value.toString();
330 private static Object maskPassword(String name, Object value) {
331 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
332 for (String pwdName : pwdNames) {
333 if (name.contains(pwdName)) {
341 * Allows Directed Graphs the ability to interact with REST APIs.
343 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
347 * <th>Mandatory/Optional</th>
348 * <th>description</th>
349 * <th>example values</th></thead> <tbody>
351 * <td>templateFileName</td>
353 * <td>full path to template file that can be used to build a request</td>
354 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
357 * <td>restapiUrl</td>
359 * <td>url to send the request to</td>
360 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
363 * <td>restapiUser</td>
365 * <td>user name to use for http basic authentication</td>
369 * <td>restapiPassword</td>
371 * <td>unencrypted password to use for http basic authentication</td>
372 * <td>plain_password</td>
375 * <td>oAuthConsumerKey</td>
377 * <td>Consumer key to use for http oAuth authentication</td>
381 * <td>oAuthConsumerSecret</td>
383 * <td>Consumer secret to use for http oAuth authentication</td>
384 * <td>plain_secret</td>
387 * <td>oAuthSignatureMethod</td>
389 * <td>Consumer method to use for http oAuth authentication</td>
393 * <td>oAuthVersion</td>
395 * <td>Version http oAuth authentication</td>
399 * <td>contentType</td>
401 * <td>http content type to set in the http header</td>
402 * <td>usually application/json or application/xml</td>
407 * <td>should match request body format</td>
408 * <td>json or xml</td>
411 * <td>httpMethod</td>
413 * <td>http method to use when sending the request</td>
414 * <td>get post put delete patch</td>
417 * <td>responsePrefix</td>
419 * <td>location the response will be written to in context memory</td>
420 * <td>tmp.restapi.result</td>
423 * <td>listName[i]</td>
425 * <td>Used for processing XML responses with repeating
426 * elements.</td>vpn-information.vrf-details
430 * <td>skipSending</td>
433 * <td>true or false</td>
436 * <td>convertResponse</td>
438 * <td>whether the response should be converted</td>
439 * <td>true or false</td>
442 * <td>customHttpHeaders</td>
444 * <td>a list additional http headers to be passed in, follow the format in the example</td>
445 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
448 * <td>dumpHeaders</td>
450 * <td>when true writes http header content to context memory</td>
451 * <td>true or false</td>
456 * <td>used to retrieve username, password and url if partner store exists</td>
460 * <td>returnRequestPayload</td>
462 * <td>used to return payload built in the request</td>
463 * <td>true or false</td>
467 * @param ctx Reference to context memory
468 * @throws SvcLogicException
470 * @see String#split(String, int)
472 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
473 sendRequest(paramMap, ctx, null);
476 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
477 throws SvcLogicException {
479 HttpResponse r = new HttpResponse();
481 handlePartner(paramMap);
482 Parameters p = getParameters(paramMap, new Parameters());
483 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
484 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
486 if (containsMultipleUrls(p.restapiUrl) && retryPolicy == null) {
487 String[] urls = getMultipleUrls(p.restapiUrl);
488 retryPolicy = new RetryPolicy(urls, urls.length * 2);
489 p.restapiUrl = urls[0];
491 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
494 if (p.templateFileName != null) {
495 String reqTemplate = readFile(p.templateFileName);
496 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
497 } else if (p.requestBody != null) {
500 r = sendHttpRequest(req, p);
501 setResponseStatus(ctx, p.responsePrefix, r);
503 if (p.dumpHeaders && r.headers != null) {
504 for (Entry<String, List<String>> a : r.headers.entrySet()) {
505 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
509 if (p.returnRequestPayload && req != null) {
510 ctx.setAttribute(pp + "httpRequest", req);
513 if (r.body != null && r.body.trim().length() > 0) {
514 ctx.setAttribute(pp + "httpResponse", r.body);
516 if (p.convertResponse) {
517 Map<String, String> mm = null;
518 if (p.format == Format.XML) {
519 mm = XmlParser.convertToProperties(r.body, p.listNameList);
520 } else if (p.format == Format.JSON) {
521 mm = JsonParser.convertToProperties(r.body);
525 for (Map.Entry<String, String> entry : mm.entrySet()) {
526 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
531 } catch (SvcLogicException e) {
532 boolean shouldRetry = false;
533 if (e.getCause().getCause() instanceof SocketException) {
537 log.error("Error sending the request: " + e.getMessage(), e);
538 String prefix = parseParam(paramMap, responsePrefix, false, null);
539 if (retryPolicy == null || !shouldRetry) {
540 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
542 log.debug(retryPolicy.getRetryMessage());
544 // calling getNextHostName increments the retry count so it should be called before shouldRetry
545 String retryString = retryPolicy.getNextHostName();
546 if (retryPolicy.shouldRetry()) {
547 paramMap.put(restapiUrlString, retryString);
548 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
550 sendRequest(paramMap, ctx, retryPolicy);
552 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
553 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
555 } catch (Exception ex) {
556 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
557 + "has failed with error message " + ex.getMessage();
558 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
563 if (r != null && r.code >= 300) {
564 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
568 protected void handlePartner(Map<String, String> paramMap) {
569 String partner = paramMap.get("partner");
570 if (partner != null && partner.length() > 0) {
571 PartnerDetails details = partnerStore.get(partner);
572 paramMap.put(restapiUserKey, details.username);
573 paramMap.put(restapiPasswordKey, details.password);
574 if (paramMap.get(restapiUrlString) == null) {
575 paramMap.put(restapiUrlString, details.url);
580 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
581 log.info("Building {} started", format);
582 long t1 = System.currentTimeMillis();
583 String originalTemplate = template;
585 template = expandRepeats(ctx, template, 1);
587 Map<String, String> mm = new HashMap<>();
588 for (String s : ctx.getAttributeKeySet()) {
589 mm.put(s, ctx.getAttribute(s));
592 StringBuilder ss = new StringBuilder();
594 while (i < template.length()) {
595 int i1 = template.indexOf("${", i);
597 ss.append(template.substring(i));
601 int i2 = template.indexOf('}', i1 + 2);
603 throw new SvcLogicException("Template error: Matching } not found");
606 String var1 = template.substring(i1 + 2, i2);
607 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
608 if (value1 == null || value1.trim().length() == 0) {
609 // delete the whole element (line)
610 int i3 = template.lastIndexOf('\n', i1);
614 int i4 = template.indexOf('\n', i1);
616 i4 = template.length();
620 ss.append(template.substring(i, i3));
624 ss.append(template.substring(i, i1)).append(value1);
629 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
630 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
632 if (format == Format.JSON) {
633 req = XmlJsonUtil.removeLastCommaJson(req);
636 long t2 = System.currentTimeMillis();
637 log.info("Building {} completed. Time: {}", format, t2 - t1);
642 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
643 StringBuilder newTemplate = new StringBuilder();
645 while (k < template.length()) {
646 int i1 = template.indexOf("${repeat:", k);
648 newTemplate.append(template.substring(k));
652 int i2 = template.indexOf(':', i1 + 9);
654 throw new SvcLogicException(
655 "Template error: Context variable name followed by : is required after repeat");
658 // Find the closing }, store in i3
662 while (nn > 0 && i < template.length()) {
663 i3 = template.indexOf('}', i);
665 throw new SvcLogicException("Template error: Matching } not found");
667 int i32 = template.indexOf('{', i);
668 if (i32 >= 0 && i32 < i3) {
677 String var1 = template.substring(i1 + 9, i2);
678 String value1 = ctx.getAttribute(var1);
679 log.info(" {}:{}", var1, value1);
682 n = Integer.parseInt(value1);
683 } catch (NumberFormatException e) {
684 log.info("value1 not set or not a number, n will remain set at zero");
687 newTemplate.append(template.substring(k, i1));
689 String rpt = template.substring(i2 + 1, i3);
691 for (int ii = 0; ii < n; ii++) {
692 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
693 if (ii == n - 1 && ss.trim().endsWith(",")) {
694 int i4 = ss.lastIndexOf(',');
696 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
699 newTemplate.append(ss);
706 return newTemplate.toString();
709 return expandRepeats(ctx, newTemplate.toString(), level + 1);
712 protected String readFile(String fileName) throws SvcLogicException {
714 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
715 return new String(encoded, "UTF-8");
716 } catch (IOException | SecurityException e) {
717 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
721 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
722 Parameters p = new Parameters();
723 p.restapiUser = fp.user;
724 p.restapiPassword = fp.password;
725 p.oAuthConsumerKey = fp.oAuthConsumerKey;
726 p.oAuthVersion = fp.oAuthVersion;
727 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
728 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
729 p.authtype = fp.authtype;
730 return addAuthType(c, p);
733 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
734 if (p.authtype == AuthType.Unspecified) {
735 if (p.restapiUser != null && p.restapiPassword != null) {
736 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
737 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
738 Feature oAuth1Feature =
739 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
740 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
741 client.register(oAuth1Feature);
745 if (p.authtype == AuthType.DIGEST) {
746 if (p.restapiUser != null && p.restapiPassword != null) {
747 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
749 throw new SvcLogicException(
750 "oAUTH authentication type selected but all restapiUser and restapiPassword "
751 + "parameters doesn't exist",
754 } else if (p.authtype == AuthType.BASIC) {
755 if (p.restapiUser != null && p.restapiPassword != null) {
756 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
758 throw new SvcLogicException(
759 "oAUTH authentication type selected but all restapiUser and restapiPassword "
760 + "parameters doesn't exist",
763 } else if (p.authtype == AuthType.OAUTH) {
764 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
765 Feature oAuth1Feature = OAuth1ClientSupport
766 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
767 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
768 client.register(oAuth1Feature);
770 throw new SvcLogicException(
771 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
772 + "and oAuthSignatureMethod parameters doesn't exist",
781 * Receives the http response for the http request sent.
783 * @param request request msg
784 * @param p parameters
785 * @return HTTP response
786 * @throws SvcLogicException when sending http request fails
788 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
790 SSLContext ssl = null;
791 if (p.ssl && p.restapiUrl.startsWith("https")) {
792 ssl = createSSLContext(p);
796 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
797 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
799 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
802 setClientTimeouts(client);
803 // Needed to support additional HTTP methods such as PATCH
804 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
805 client.register(new MetricLogClientFilter());
806 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
808 long t1 = System.currentTimeMillis();
810 HttpResponse r = new HttpResponse();
812 String accept = p.accept;
813 if (accept == null) {
814 accept = p.format == Format.XML ? "application/xml" : "application/json";
817 String contentType = p.contentType;
818 if (contentType == null) {
819 contentType = accept + ";charset=UTF-8";
822 if (!p.skipSending && !p.multipartFormData) {
824 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
826 if (p.format == Format.NONE) {
827 invocationBuilder.header("", "");
830 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
831 String[] keyValuePairs = p.customHttpHeaders.split(",");
832 for (String singlePair : keyValuePairs) {
833 int equalPosition = singlePair.indexOf('=');
834 invocationBuilder.header(singlePair.substring(0, equalPosition),
835 singlePair.substring(equalPosition + 1, singlePair.length()));
839 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
844 // When the HTTP operation has no body do not set the content-type
845 //setting content-type has caused errors with some servers when no body is present
846 if (request == null) {
847 response = invocationBuilder.method(p.httpMethod.toString());
849 log.info("Sending request below to url " + p.restapiUrl);
851 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
853 } catch (ProcessingException | IllegalStateException e) {
854 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
857 r.code = response.getStatus();
858 r.headers = response.getStringHeaders();
859 EntityTag etag = response.getEntityTag();
861 r.message = etag.getValue();
863 if (response.hasEntity() && r.code != 204) {
864 r.body = response.readEntity(String.class);
866 } else if (!p.skipSending && p.multipartFormData) {
868 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
870 MultiPart multiPart = new MultiPart();
871 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
873 FileDataBodyPart fileDataBodyPart =
874 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
875 multiPart.bodyPart(fileDataBodyPart);
878 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
880 if (p.format == Format.NONE) {
881 invocationBuilder.header("", "");
884 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
885 String[] keyValuePairs = p.customHttpHeaders.split(",");
886 for (String singlePair : keyValuePairs) {
887 int equalPosition = singlePair.indexOf('=');
888 invocationBuilder.header(singlePair.substring(0, equalPosition),
889 singlePair.substring(equalPosition + 1, singlePair.length()));
897 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
898 } catch (ProcessingException | IllegalStateException e) {
899 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
902 r.code = response.getStatus();
903 r.headers = response.getStringHeaders();
904 EntityTag etag = response.getEntityTag();
906 r.message = etag.getValue();
908 if (response.hasEntity() && r.code != 204) {
909 r.body = response.readEntity(String.class);
914 long t2 = System.currentTimeMillis();
915 log.info(responseReceivedMessage, t2 - t1);
916 log.info(responseHttpCodeMessage, r.code);
917 log.info("HTTP response message: {}", r.message);
918 logHeaders(r.headers);
919 log.info("HTTP response: {}", r.body);
924 protected SSLContext createSSLContext(Parameters p) {
925 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
926 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
927 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
928 KeyStore ks = KeyStore.getInstance("PKCS12");
929 char[] pwd = p.keyStorePassword.toCharArray();
932 SSLContext ctx = SSLContext.getInstance("TLS");
933 ctx.init(kmf.getKeyManagers(), null, null);
935 } catch (Exception e) {
936 log.error("Error creating SSLContext: {}", e.getMessage(), e);
941 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
944 resp.message = errorMessage;
945 String pp = prefix != null ? prefix + '.' : "";
946 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
947 ctx.setAttribute(pp + "response-message", resp.message);
950 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
951 String pp = prefix != null ? prefix + '.' : "";
952 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
953 ctx.setAttribute(pp + "response-message", r.message);
956 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
957 HttpResponse r = null;
959 FileParam p = getFileParameters(paramMap);
960 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
962 r = sendHttpData(data, p);
964 for (int i = 0; i < 10 && r.code == 301; i++) {
965 String newUrl = r.headers2.get("Location").get(0);
967 log.info("Got response code 301. Sending same request to URL: " + newUrl);
970 r = sendHttpData(data, p);
973 setResponseStatus(ctx, p.responsePrefix, r);
975 } catch (SvcLogicException | IOException e) {
976 log.error("Error sending the request: {}", e.getMessage(), e);
978 r = new HttpResponse();
980 r.message = e.getMessage();
981 String prefix = parseParam(paramMap, responsePrefix, false, null);
982 setResponseStatus(ctx, prefix, r);
985 if (r != null && r.code >= 300) {
986 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
990 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
991 FileParam p = new FileParam();
992 p.fileName = parseParam(paramMap, "fileName", true, null);
993 p.url = parseParam(paramMap, "url", true, null);
994 p.user = parseParam(paramMap, "user", false, null);
995 p.password = parseParam(paramMap, "password", false, null);
996 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
997 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
998 String skipSendingStr = paramMap.get(skipSendingMessage);
999 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1000 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1001 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1002 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1003 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1004 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1008 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1011 UebParam p = getUebParameters(paramMap);
1013 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1017 if (p.templateFileName == null) {
1018 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1019 p.templateFileName = defaultUebTemplateFileName;
1022 String reqTemplate = readFile(p.templateFileName);
1023 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1024 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1026 r = postOnUeb(req, p);
1027 setResponseStatus(ctx, p.responsePrefix, r);
1028 if (r.body != null) {
1029 ctx.setAttribute(pp + "httpResponse", r.body);
1032 } catch (SvcLogicException e) {
1033 log.error("Error sending the request: {}", e.getMessage(), e);
1035 r = new HttpResponse();
1037 r.message = e.getMessage();
1038 String prefix = parseParam(paramMap, responsePrefix, false, null);
1039 setResponseStatus(ctx, prefix, r);
1042 if (r.code >= 300) {
1043 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1047 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1048 URL url = new URL(p.url);
1049 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1051 log.info("Connection: " + con.getClass().getName());
1053 con.setRequestMethod(p.httpMethod.toString());
1054 con.setRequestProperty("Content-Type", "application/octet-stream");
1055 con.setRequestProperty("Accept", "*/*");
1056 con.setRequestProperty("Expect", "100-continue");
1057 con.setFixedLengthStreamingMode(data.length);
1058 con.setInstanceFollowRedirects(false);
1060 if (p.user != null && p.password != null) {
1061 String authString = p.user + ":" + p.password;
1062 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1063 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1066 con.setDoInput(true);
1067 con.setDoOutput(true);
1069 log.info("Sending file");
1070 long t1 = System.currentTimeMillis();
1072 HttpResponse r = new HttpResponse();
1075 if (!p.skipSending) {
1076 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1077 util.logBefore(con, ONAPComponents.DMAAP);
1081 boolean continue100failed = false;
1083 OutputStream os = con.getOutputStream();
1087 } catch (ProtocolException e) {
1088 continue100failed = true;
1091 r.code = con.getResponseCode();
1092 r.headers2 = con.getHeaderFields();
1094 if (r.code != 204 && !continue100failed) {
1095 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1097 StringBuffer response = new StringBuffer();
1098 while ((inputLine = in.readLine()) != null) {
1099 response.append(inputLine);
1103 r.body = response.toString();
1111 long t2 = System.currentTimeMillis();
1112 log.info("Response received. Time: {}", t2 - t1);
1113 log.info("HTTP response code: {}", r.code);
1114 log.info("HTTP response message: {}", r.message);
1115 logHeaders(r.headers2);
1116 log.info("HTTP response: {}", r.body);
1121 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1122 UebParam p = new UebParam();
1123 p.topic = parseParam(paramMap, "topic", true, null);
1124 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1125 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1126 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1127 String skipSendingStr = paramMap.get(skipSendingMessage);
1128 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1132 protected void logProperties(Map<String, Object> mm) {
1133 List<String> ll = new ArrayList<>();
1134 for (Object o : mm.keySet()) {
1137 Collections.sort(ll);
1139 log.info("Properties:");
1140 for (String name : ll) {
1141 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1145 protected void logHeaders(MultivaluedMap<String, String> mm) {
1146 log.info("HTTP response headers:");
1152 List<String> ll = new ArrayList<>();
1153 for (Object o : mm.keySet()) {
1156 Collections.sort(ll);
1158 for (String name : ll) {
1159 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1163 private void logHeaders(Map<String, List<String>> mm) {
1164 if (mm == null || mm.isEmpty()) {
1168 List<String> ll = new ArrayList<>();
1169 for (String s : mm.keySet()) {
1174 Collections.sort(ll);
1176 for (String name : ll) {
1177 List<String> v = mm.get(name);
1178 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1179 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1183 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1184 String[] urls = uebServers.split(" ");
1185 for (int i = 0; i < urls.length; i++) {
1186 if (!urls[i].endsWith("/")) {
1189 urls[i] += "events/" + p.topic;
1192 Client client = ClientBuilder.newBuilder().build();
1193 setClientTimeouts(client);
1194 WebTarget webTarget = client.target(urls[0]);
1196 log.info("UEB URL: {}", urls[0]);
1197 log.info("Sending request:");
1199 long t1 = System.currentTimeMillis();
1201 HttpResponse r = new HttpResponse();
1204 if (!p.skipSending) {
1205 String tt = "application/json";
1206 String tt1 = tt + ";charset=UTF-8";
1209 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1212 response = invocationBuilder.post(Entity.entity(request, tt1));
1213 } catch (ProcessingException e) {
1214 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1216 r.code = response.getStatus();
1217 r.headers = response.getStringHeaders();
1218 if (response.hasEntity()) {
1219 r.body = response.readEntity(String.class);
1223 long t2 = System.currentTimeMillis();
1224 log.info(responseReceivedMessage, t2 - t1);
1225 log.info(responseHttpCodeMessage, r.code);
1226 logHeaders(r.headers);
1227 log.info("HTTP response:\n {}", r.body);
1232 public void setUebServers(String uebServers) {
1233 this.uebServers = uebServers;
1236 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1237 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1240 protected void setClientTimeouts(Client client) {
1241 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1242 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1245 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1246 String stringValue = System.getProperty(propertyName);
1247 if (stringValue != null && stringValue.length() > 0) {
1249 return Integer.valueOf(stringValue);
1250 } catch (NumberFormatException e) {
1251 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1254 return defaultValue;
1257 protected static String[] getMultipleUrls(String restapiUrl) {
1258 List<String> urls = new ArrayList<>();
1260 for (int i = 0; i < restapiUrl.length(); i++) {
1261 if (restapiUrl.charAt(i) == ',') {
1262 if (i + 9 < restapiUrl.length()) {
1263 String part = restapiUrl.substring(i + 1, i + 9);
1264 if (part.equals("https://") || part.startsWith("http://")) {
1265 urls.add(restapiUrl.substring(start, i));
1269 } else if (i == restapiUrl.length() - 1) {
1270 urls.add(restapiUrl.substring(start, i + 1));
1273 String[] arr = new String[urls.size()];
1274 return urls.toArray(arr);
1277 protected static boolean containsMultipleUrls(String restapiUrl) {
1278 Matcher m = retryPattern.matcher(restapiUrl);
1282 private static class FileParam {
1284 public String fileName;
1287 public String password;
1288 public HttpMethod httpMethod;
1289 public String responsePrefix;
1290 public boolean skipSending;
1291 public String oAuthConsumerKey;
1292 public String oAuthConsumerSecret;
1293 public String oAuthSignatureMethod;
1294 public String oAuthVersion;
1295 public AuthType authtype;
1298 private static class UebParam {
1300 public String topic;
1301 public String templateFileName;
1302 public String rootVarName;
1303 public String responsePrefix;
1304 public boolean skipSending;