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;
56 import javax.net.ssl.HttpsURLConnection;
57 import javax.net.ssl.KeyManagerFactory;
58 import javax.net.ssl.SSLContext;
59 import javax.ws.rs.ProcessingException;
60 import javax.ws.rs.client.Client;
61 import javax.ws.rs.client.ClientBuilder;
62 import javax.ws.rs.client.Entity;
63 import javax.ws.rs.client.Invocation;
64 import javax.ws.rs.client.WebTarget;
65 import javax.ws.rs.core.EntityTag;
66 import javax.ws.rs.core.Feature;
67 import javax.ws.rs.core.MediaType;
68 import javax.ws.rs.core.MultivaluedMap;
69 import javax.ws.rs.core.Response;
70 import javax.ws.rs.core.UriBuilder;
71 import org.apache.commons.lang3.StringUtils;
72 import org.codehaus.jettison.json.JSONException;
73 import org.codehaus.jettison.json.JSONObject;
74 import org.glassfish.jersey.client.ClientProperties;
75 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
76 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
77 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
78 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
79 import org.glassfish.jersey.media.multipart.MultiPart;
80 import org.glassfish.jersey.media.multipart.MultiPartFeature;
81 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
82 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
83 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
84 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
85 import org.onap.logging.filter.base.HttpURLConnectionMetricUtil;
86 import org.onap.logging.filter.base.MetricLogClientFilter;
87 import org.onap.logging.filter.base.ONAPComponents;
88 import org.onap.logging.ref.slf4j.ONAPLogConstants;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 public class RestapiCallNode implements SvcLogicJavaPlugin {
95 protected static final String PARTNERS_FILE_NAME = "partners.json";
96 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
97 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
98 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
99 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
100 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
102 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
103 private String uebServers;
104 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
106 private String responseReceivedMessage = "Response received. Time: {}";
107 private String responseHttpCodeMessage = "HTTP response code: {}";
108 private String requestPostingException = "Exception while posting http request to client ";
109 protected static final String skipSendingMessage = "skipSending";
110 protected static final String responsePrefix = "responsePrefix";
111 protected static final String restapiUrlString = "restapiUrl";
112 protected static final String restapiUserKey = "restapiUser";
113 protected static final String restapiPasswordKey = "restapiPassword";
114 protected Integer httpConnectTimeout;
115 protected Integer httpReadTimeout;
117 protected HashMap<String, PartnerDetails> partnerStore;
118 private static final Pattern retryPattern = Pattern.compile(".*,(http|https):.*");
120 public RestapiCallNode() {
121 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
123 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
124 JSONObject partners = new JSONObject(jsonString);
125 partnerStore = new HashMap<>();
126 loadPartners(partners);
127 log.info("Partners support enabled");
128 } catch (Exception e) {
129 log.warn("Partners file could not be read, Partner support will not be enabled.", e);
132 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
133 Properties props = new Properties();
135 uebServers = props.getProperty("servers");
136 log.info("UEB support enabled");
137 } catch (Exception e) {
138 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
140 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
141 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
144 @SuppressWarnings("unchecked")
145 protected void loadPartners(JSONObject partners) {
146 Iterator<String> keys = partners.keys();
147 String partnerUserKey = "user";
148 String partnerPasswordKey = "password";
149 String partnerUrlKey = "url";
151 while (keys.hasNext()) {
152 String partnerKey = keys.next();
154 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
155 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
157 if (partnerObject.has(partnerUrlKey)) {
158 url = partnerObject.getString(partnerUrlKey);
160 String userName = partnerObject.getString(partnerUserKey);
161 String password = partnerObject.getString(partnerPasswordKey);
162 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
163 partnerStore.put(partnerKey, details);
164 log.info("mapped partner using partner key " + partnerKey);
166 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
168 } catch (JSONException e) {
169 log.info("Couldn't map the partner using partner key " + partnerKey, e);
174 /* Unobfuscate param value */
175 private static String getObfuscatedVal(String paramValue) {
176 String resValue = paramValue;
177 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
179 String paramStr = paramValue.substring(2, paramValue.length()-1);
180 if (paramStr != null && paramStr.length() > 0)
182 String val = System.getenv(paramStr);
183 if (val != null && val.length() > 0)
186 log.info("Obfuscated value RESET for param value:" + paramValue);
194 * Returns parameters from the parameter map.
196 * @param paramMap parameter map
197 * @param p parameters instance
198 * @return parameters filed instance
199 * @throws SvcLogicException when svc logic exception occurs
201 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
203 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
204 p.requestBody = parseParam(paramMap, "requestBody", false, null);
205 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
206 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
207 if (p.restapiUrlSuffix != null) {
208 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
211 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
212 validateUrl(p.restapiUrl);
214 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
215 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
216 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
217 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
218 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
219 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
220 p.contentType = parseParam(paramMap, "contentType", false, null);
221 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
222 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
223 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
224 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
225 p.listNameList = getListNameList(paramMap);
226 String skipSendingStr = paramMap.get(skipSendingMessage);
227 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
228 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
229 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
230 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
231 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
232 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
233 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
234 && p.keyStorePassword != null;
235 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
236 p.partner = parseParam(paramMap, "partner", false, null);
237 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
238 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
239 p.accept = parseParam(paramMap, "accept", false, null);
240 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
241 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
242 p.targetEntity = parseParam(paramMap, "targetEntity", false, null);
247 * Validates the given URL in the parameters.
249 * @param restapiUrl rest api URL
250 * @throws SvcLogicException when URL validation fails
252 private static void validateUrl(String restapiUrl) throws SvcLogicException {
253 if (containsMultipleUrls(restapiUrl)) {
254 String[] urls = getMultipleUrls(restapiUrl);
255 for (String url : urls) {
260 URI.create(restapiUrl);
261 } catch (IllegalArgumentException e) {
262 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
268 * Returns the list of list name.
270 * @param paramMap parameters map
271 * @return list of list name
273 private static Set<String> getListNameList(Map<String, String> paramMap) {
274 Set<String> ll = new HashSet<>();
275 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
276 if (entry.getKey().startsWith("listName")) {
277 ll.add(entry.getValue());
284 * Parses the parameter string map of property, validates if required, assigns default value if
285 * present and returns the value.
287 * @param paramMap string param map
288 * @param name name of the property
289 * @param required if value required
290 * @param def default value
291 * @return value of the property
292 * @throws SvcLogicException if required parameter value is empty
294 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
295 throws SvcLogicException {
296 String s = paramMap.get(name);
298 if (s == null || s.trim().length() == 0) {
302 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
306 StringBuilder value = new StringBuilder();
308 int i1 = s.indexOf('%');
310 int i2 = s.indexOf('%', i1 + 1);
315 String varName = s.substring(i1 + 1, i2);
316 String varValue = System.getenv(varName);
317 if (varValue == null) {
318 varValue = "%" + varName + "%";
321 value.append(s.substring(i, i1));
322 value.append(varValue);
325 i1 = s.indexOf('%', i);
327 value.append(s.substring(i));
329 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
331 return value.toString();
334 private static Object maskPassword(String name, Object value) {
335 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
336 for (String pwdName : pwdNames) {
337 if (name.contains(pwdName)) {
345 * Allows Directed Graphs the ability to interact with REST APIs.
347 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
351 * <th>Mandatory/Optional</th>
352 * <th>description</th>
353 * <th>example values</th></thead> <tbody>
355 * <td>templateFileName</td>
357 * <td>full path to template file that can be used to build a request</td>
358 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
361 * <td>restapiUrl</td>
363 * <td>url to send the request to</td>
364 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
367 * <td>restapiUser</td>
369 * <td>user name to use for http basic authentication</td>
373 * <td>restapiPassword</td>
375 * <td>unencrypted password to use for http basic authentication</td>
376 * <td>plain_password</td>
379 * <td>oAuthConsumerKey</td>
381 * <td>Consumer key to use for http oAuth authentication</td>
385 * <td>oAuthConsumerSecret</td>
387 * <td>Consumer secret to use for http oAuth authentication</td>
388 * <td>plain_secret</td>
391 * <td>oAuthSignatureMethod</td>
393 * <td>Consumer method to use for http oAuth authentication</td>
397 * <td>oAuthVersion</td>
399 * <td>Version http oAuth authentication</td>
403 * <td>contentType</td>
405 * <td>http content type to set in the http header</td>
406 * <td>usually application/json or application/xml</td>
411 * <td>should match request body format</td>
412 * <td>json or xml</td>
415 * <td>httpMethod</td>
417 * <td>http method to use when sending the request</td>
418 * <td>get post put delete patch</td>
421 * <td>responsePrefix</td>
423 * <td>location the response will be written to in context memory</td>
424 * <td>tmp.restapi.result</td>
427 * <td>listName[i]</td>
429 * <td>Used for processing XML responses with repeating
430 * elements.</td>vpn-information.vrf-details
434 * <td>skipSending</td>
437 * <td>true or false</td>
440 * <td>convertResponse</td>
442 * <td>whether the response should be converted</td>
443 * <td>true or false</td>
446 * <td>customHttpHeaders</td>
448 * <td>a list additional http headers to be passed in, follow the format in the example</td>
449 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
452 * <td>dumpHeaders</td>
454 * <td>when true writes http header content to context memory</td>
455 * <td>true or false</td>
460 * <td>used to retrieve username, password and url if partner store exists</td>
464 * <td>returnRequestPayload</td>
466 * <td>used to return payload built in the request</td>
467 * <td>true or false</td>
471 * @param ctx Reference to context memory
472 * @throws SvcLogicException
474 * @see String#split(String, int)
476 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
477 sendRequest(paramMap, ctx, null);
480 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
481 throws SvcLogicException {
483 HttpResponse r = new HttpResponse();
485 handlePartner(paramMap);
486 Parameters p = getParameters(paramMap, new Parameters());
487 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
488 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
490 if (containsMultipleUrls(p.restapiUrl) && retryPolicy == null) {
491 String[] urls = getMultipleUrls(p.restapiUrl);
492 retryPolicy = new RetryPolicy(urls, urls.length * 2);
493 p.restapiUrl = urls[0];
495 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
498 if (p.templateFileName != null) {
499 String reqTemplate = readFile(p.templateFileName);
500 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
501 } else if (p.requestBody != null) {
504 r = sendHttpRequest(req, p);
505 setResponseStatus(ctx, p.responsePrefix, r);
507 if (p.dumpHeaders && r.headers != null) {
508 for (Entry<String, List<String>> a : r.headers.entrySet()) {
509 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
513 if (p.returnRequestPayload && req != null) {
514 ctx.setAttribute(pp + "httpRequest", req);
517 if (r.body != null && r.body.trim().length() > 0) {
518 ctx.setAttribute(pp + "httpResponse", r.body);
520 if (p.convertResponse) {
521 Map<String, String> mm = null;
522 if (p.format == Format.XML) {
523 mm = XmlParser.convertToProperties(r.body, p.listNameList);
524 } else if (p.format == Format.JSON) {
525 mm = JsonParser.convertToProperties(r.body);
529 for (Map.Entry<String, String> entry : mm.entrySet()) {
530 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
535 } catch (SvcLogicException e) {
536 boolean shouldRetry = false;
537 if (e.getCause().getCause() instanceof SocketException) {
541 log.error("Error sending the request: " + e.getMessage(), e);
542 String prefix = parseParam(paramMap, responsePrefix, false, null);
543 if (retryPolicy == null || !shouldRetry) {
544 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
546 log.debug(retryPolicy.getRetryMessage());
548 // calling getNextHostName increments the retry count so it should be called before shouldRetry
549 String retryString = retryPolicy.getNextHostName();
550 if (retryPolicy.shouldRetry()) {
551 paramMap.put(restapiUrlString, retryString);
552 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
554 sendRequest(paramMap, ctx, retryPolicy);
556 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
557 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
559 } catch (Exception ex) {
560 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
561 + "has failed with error message " + ex.getMessage();
562 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
567 if (r != null && r.code >= 300) {
568 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
572 protected void handlePartner(Map<String, String> paramMap) {
573 String partner = paramMap.get("partner");
574 if (partner != null && partner.length() > 0) {
575 PartnerDetails details = partnerStore.get(partner);
576 paramMap.put(restapiUserKey, details.username);
577 paramMap.put(restapiPasswordKey, details.password);
578 if (paramMap.get(restapiUrlString) == null) {
579 paramMap.put(restapiUrlString, details.url);
584 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
585 log.info("Building {} started", format);
586 long t1 = System.currentTimeMillis();
587 String originalTemplate = template;
589 template = expandRepeats(ctx, template, 1);
591 Map<String, String> mm = new HashMap<>();
592 for (String s : ctx.getAttributeKeySet()) {
593 mm.put(s, ctx.getAttribute(s));
596 StringBuilder ss = new StringBuilder();
598 while (i < template.length()) {
599 int i1 = template.indexOf("${", i);
601 ss.append(template.substring(i));
605 int i2 = template.indexOf('}', i1 + 2);
607 throw new SvcLogicException("Template error: Matching } not found");
610 String var1 = template.substring(i1 + 2, i2);
611 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
612 if (value1 == null || value1.trim().length() == 0) {
613 // delete the whole element (line)
614 int i3 = template.lastIndexOf('\n', i1);
618 int i4 = template.indexOf('\n', i1);
620 i4 = template.length();
624 ss.append(template.substring(i, i3));
628 ss.append(template.substring(i, i1)).append(value1);
633 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
634 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
636 if (format == Format.JSON) {
637 req = XmlJsonUtil.removeLastCommaJson(req);
640 long t2 = System.currentTimeMillis();
641 log.info("Building {} completed. Time: {}", format, t2 - t1);
646 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
647 StringBuilder newTemplate = new StringBuilder();
649 while (k < template.length()) {
650 int i1 = template.indexOf("${repeat:", k);
652 newTemplate.append(template.substring(k));
656 int i2 = template.indexOf(':', i1 + 9);
658 throw new SvcLogicException(
659 "Template error: Context variable name followed by : is required after repeat");
662 // Find the closing }, store in i3
666 while (nn > 0 && i < template.length()) {
667 i3 = template.indexOf('}', i);
669 throw new SvcLogicException("Template error: Matching } not found");
671 int i32 = template.indexOf('{', i);
672 if (i32 >= 0 && i32 < i3) {
681 String var1 = template.substring(i1 + 9, i2);
682 String value1 = ctx.getAttribute(var1);
683 log.info(" {}:{}", var1, value1);
686 n = Integer.parseInt(value1);
687 } catch (NumberFormatException e) {
688 log.info("value1 not set or not a number, n will remain set at zero");
691 newTemplate.append(template.substring(k, i1));
693 String rpt = template.substring(i2 + 1, i3);
695 for (int ii = 0; ii < n; ii++) {
696 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
697 if (ii == n - 1 && ss.trim().endsWith(",")) {
698 int i4 = ss.lastIndexOf(',');
700 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
703 newTemplate.append(ss);
710 return newTemplate.toString();
713 return expandRepeats(ctx, newTemplate.toString(), level + 1);
716 protected String readFile(String fileName) throws SvcLogicException {
718 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
719 return new String(encoded, "UTF-8");
720 } catch (IOException | SecurityException e) {
721 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
725 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
726 Parameters p = new Parameters();
727 p.restapiUser = fp.user;
728 p.restapiPassword = fp.password;
729 p.oAuthConsumerKey = fp.oAuthConsumerKey;
730 p.oAuthVersion = fp.oAuthVersion;
731 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
732 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
733 p.authtype = fp.authtype;
734 return addAuthType(c, p);
737 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
738 if (p.authtype == AuthType.Unspecified) {
739 if (p.restapiUser != null && p.restapiPassword != null) {
740 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
741 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
742 Feature oAuth1Feature =
743 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
744 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
745 client.register(oAuth1Feature);
749 if (p.authtype == AuthType.DIGEST) {
750 if (p.restapiUser != null && p.restapiPassword != null) {
751 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
753 throw new SvcLogicException(
754 "oAUTH authentication type selected but all restapiUser and restapiPassword "
755 + "parameters doesn't exist",
758 } else if (p.authtype == AuthType.BASIC) {
759 if (p.restapiUser != null && p.restapiPassword != null) {
760 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
762 throw new SvcLogicException(
763 "oAUTH authentication type selected but all restapiUser and restapiPassword "
764 + "parameters doesn't exist",
767 } else if (p.authtype == AuthType.OAUTH) {
768 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
769 Feature oAuth1Feature = OAuth1ClientSupport
770 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
771 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
772 client.register(oAuth1Feature);
774 throw new SvcLogicException(
775 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
776 + "and oAuthSignatureMethod parameters doesn't exist",
785 * Receives the http response for the http request sent.
787 * @param request request msg
788 * @param p parameters
789 * @return HTTP response
790 * @throws SvcLogicException when sending http request fails
792 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
794 SSLContext ssl = null;
795 if (p.ssl && p.restapiUrl.startsWith("https")) {
796 ssl = createSSLContext(p);
801 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
802 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
804 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
806 setClientTimeouts(client);
807 // Needed to support additional HTTP methods such as PATCH
808 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
809 client.register(new MetricLogClientFilter());
810 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
812 long t1 = System.currentTimeMillis();
814 HttpResponse r = new HttpResponse();
816 String accept = p.accept;
817 if (accept == null) {
818 accept = p.format == Format.XML ? "application/xml" : "application/json";
821 String contentType = p.contentType;
822 if (contentType == null) {
823 contentType = accept + ";charset=UTF-8";
826 if (!p.skipSending && !p.multipartFormData) {
828 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
830 if (p.format == Format.NONE) {
831 invocationBuilder.header("", "");
834 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
835 String[] keyValuePairs = p.customHttpHeaders.split(",");
836 for (String singlePair : keyValuePairs) {
837 int equalPosition = singlePair.indexOf('=');
838 invocationBuilder.header(singlePair.substring(0, equalPosition),
839 singlePair.substring(equalPosition + 1, singlePair.length()));
843 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
848 // When the HTTP operation has no body do not set the content-type
849 //setting content-type has caused errors with some servers when no body is present
850 if (request == null) {
851 response = invocationBuilder.method(p.httpMethod.toString());
853 log.info("Sending request below to url " + p.restapiUrl);
855 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
857 } catch (ProcessingException | IllegalStateException e) {
858 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
861 r.code = response.getStatus();
862 r.headers = response.getStringHeaders();
863 EntityTag etag = response.getEntityTag();
865 r.message = etag.getValue();
867 if (response.hasEntity() && r.code != 204) {
868 r.body = response.readEntity(String.class);
870 } else if (!p.skipSending && p.multipartFormData) {
872 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
874 MultiPart multiPart = new MultiPart();
875 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
877 FileDataBodyPart fileDataBodyPart =
878 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
879 multiPart.bodyPart(fileDataBodyPart);
882 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
884 if (p.format == Format.NONE) {
885 invocationBuilder.header("", "");
888 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
889 String[] keyValuePairs = p.customHttpHeaders.split(",");
890 for (String singlePair : keyValuePairs) {
891 int equalPosition = singlePair.indexOf('=');
892 invocationBuilder.header(singlePair.substring(0, equalPosition),
893 singlePair.substring(equalPosition + 1, singlePair.length()));
901 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
902 } catch (ProcessingException | IllegalStateException e) {
903 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
906 r.code = response.getStatus();
907 r.headers = response.getStringHeaders();
908 EntityTag etag = response.getEntityTag();
910 r.message = etag.getValue();
912 if (response.hasEntity() && r.code != 204) {
913 r.body = response.readEntity(String.class);
918 long t2 = System.currentTimeMillis();
919 log.info(responseReceivedMessage, t2 - t1);
920 log.info(responseHttpCodeMessage, r.code);
921 log.info("HTTP response message: {}", r.message);
922 logHeaders(r.headers);
923 log.info("HTTP response: {}", r.body);
928 protected SSLContext createSSLContext(Parameters p) {
929 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
930 System.setProperty("jsse.enableSNIExtension", "false");
931 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
932 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
934 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
936 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
937 KeyStore ks = KeyStore.getInstance("PKCS12");
938 char[] pwd = p.keyStorePassword.toCharArray();
942 SSLContext ctx = SSLContext.getInstance("TLS");
943 ctx.init(kmf.getKeyManagers(), null, null);
945 } catch (Exception e) {
946 log.error("Error creating SSLContext: {}", e.getMessage(), e);
951 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
954 resp.message = errorMessage;
955 String pp = prefix != null ? prefix + '.' : "";
956 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
957 ctx.setAttribute(pp + "response-message", resp.message);
960 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
961 String pp = prefix != null ? prefix + '.' : "";
962 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
963 ctx.setAttribute(pp + "response-message", r.message);
966 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
967 HttpResponse r = null;
969 FileParam p = getFileParameters(paramMap);
970 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
972 r = sendHttpData(data, p);
974 for (int i = 0; i < 10 && r.code == 301; i++) {
975 String newUrl = r.headers2.get("Location").get(0);
977 log.info("Got response code 301. Sending same request to URL: " + newUrl);
980 r = sendHttpData(data, p);
983 setResponseStatus(ctx, p.responsePrefix, r);
985 } catch (SvcLogicException | IOException e) {
986 log.error("Error sending the request: {}", e.getMessage(), e);
988 r = new HttpResponse();
990 r.message = e.getMessage();
991 String prefix = parseParam(paramMap, responsePrefix, false, null);
992 setResponseStatus(ctx, prefix, r);
995 if (r != null && r.code >= 300) {
996 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1000 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
1001 FileParam p = new FileParam();
1002 p.fileName = parseParam(paramMap, "fileName", true, null);
1003 p.url = parseParam(paramMap, "url", true, null);
1004 p.user = parseParam(paramMap, "user", false, null);
1005 p.password = parseParam(paramMap, "password", false, null);
1006 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1007 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1008 String skipSendingStr = paramMap.get(skipSendingMessage);
1009 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1010 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1011 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1012 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1013 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1014 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1018 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1021 UebParam p = getUebParameters(paramMap);
1023 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1027 if (p.templateFileName == null) {
1028 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1029 p.templateFileName = defaultUebTemplateFileName;
1032 String reqTemplate = readFile(p.templateFileName);
1033 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1034 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1036 r = postOnUeb(req, p);
1037 setResponseStatus(ctx, p.responsePrefix, r);
1038 if (r.body != null) {
1039 ctx.setAttribute(pp + "httpResponse", r.body);
1042 } catch (SvcLogicException e) {
1043 log.error("Error sending the request: {}", e.getMessage(), e);
1045 r = new HttpResponse();
1047 r.message = e.getMessage();
1048 String prefix = parseParam(paramMap, responsePrefix, false, null);
1049 setResponseStatus(ctx, prefix, r);
1052 if (r.code >= 300) {
1053 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1057 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1058 URL url = new URL(p.url);
1059 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1061 log.info("Connection: " + con.getClass().getName());
1063 con.setRequestMethod(p.httpMethod.toString());
1064 con.setRequestProperty("Content-Type", "application/octet-stream");
1065 con.setRequestProperty("Accept", "*/*");
1066 con.setRequestProperty("Expect", "100-continue");
1067 con.setFixedLengthStreamingMode(data.length);
1068 con.setInstanceFollowRedirects(false);
1070 if (p.user != null && p.password != null) {
1071 String authString = p.user + ":" + p.password;
1072 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1073 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1076 con.setDoInput(true);
1077 con.setDoOutput(true);
1079 log.info("Sending file");
1080 long t1 = System.currentTimeMillis();
1082 HttpResponse r = new HttpResponse();
1085 if (!p.skipSending) {
1086 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1087 util.logBefore(con, ONAPComponents.DMAAP);
1091 boolean continue100failed = false;
1093 OutputStream os = con.getOutputStream();
1097 } catch (ProtocolException e) {
1098 continue100failed = true;
1101 r.code = con.getResponseCode();
1102 r.headers2 = con.getHeaderFields();
1104 if (r.code != 204 && !continue100failed) {
1105 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1107 StringBuffer response = new StringBuffer();
1108 while ((inputLine = in.readLine()) != null) {
1109 response.append(inputLine);
1113 r.body = response.toString();
1121 long t2 = System.currentTimeMillis();
1122 log.info("Response received. Time: {}", t2 - t1);
1123 log.info("HTTP response code: {}", r.code);
1124 log.info("HTTP response message: {}", r.message);
1125 logHeaders(r.headers2);
1126 log.info("HTTP response: {}", r.body);
1131 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1132 UebParam p = new UebParam();
1133 p.topic = parseParam(paramMap, "topic", true, null);
1134 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1135 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1136 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1137 String skipSendingStr = paramMap.get(skipSendingMessage);
1138 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1142 protected void logProperties(Map<String, Object> mm) {
1143 List<String> ll = new ArrayList<>();
1144 for (Object o : mm.keySet()) {
1147 Collections.sort(ll);
1149 log.info("Properties:");
1150 for (String name : ll) {
1151 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1155 protected void logHeaders(MultivaluedMap<String, String> mm) {
1156 log.info("HTTP response headers:");
1162 List<String> ll = new ArrayList<>();
1163 for (Object o : mm.keySet()) {
1166 Collections.sort(ll);
1168 for (String name : ll) {
1169 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1173 private void logHeaders(Map<String, List<String>> mm) {
1174 if (mm == null || mm.isEmpty()) {
1178 List<String> ll = new ArrayList<>();
1179 for (String s : mm.keySet()) {
1184 Collections.sort(ll);
1186 for (String name : ll) {
1187 List<String> v = mm.get(name);
1188 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1189 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1193 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1194 String[] urls = uebServers.split(" ");
1195 for (int i = 0; i < urls.length; i++) {
1196 if (!urls[i].endsWith("/")) {
1199 urls[i] += "events/" + p.topic;
1202 Client client = ClientBuilder.newBuilder().build();
1203 setClientTimeouts(client);
1204 WebTarget webTarget = client.target(urls[0]);
1206 log.info("UEB URL: {}", urls[0]);
1207 log.info("Sending request:");
1209 long t1 = System.currentTimeMillis();
1211 HttpResponse r = new HttpResponse();
1214 if (!p.skipSending) {
1215 String tt = "application/json";
1216 String tt1 = tt + ";charset=UTF-8";
1219 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1222 response = invocationBuilder.post(Entity.entity(request, tt1));
1223 } catch (ProcessingException e) {
1224 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1226 r.code = response.getStatus();
1227 r.headers = response.getStringHeaders();
1228 if (response.hasEntity()) {
1229 r.body = response.readEntity(String.class);
1233 long t2 = System.currentTimeMillis();
1234 log.info(responseReceivedMessage, t2 - t1);
1235 log.info(responseHttpCodeMessage, r.code);
1236 logHeaders(r.headers);
1237 log.info("HTTP response:\n {}", r.body);
1242 public void setUebServers(String uebServers) {
1243 this.uebServers = uebServers;
1246 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1247 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1250 protected void setClientTimeouts(Client client) {
1251 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1252 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1255 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1256 String stringValue = System.getProperty(propertyName);
1257 if (stringValue != null && stringValue.length() > 0) {
1259 return Integer.valueOf(stringValue);
1260 } catch (NumberFormatException e) {
1261 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1264 return defaultValue;
1267 protected static String[] getMultipleUrls(String restapiUrl) {
1268 List<String> urls = new ArrayList<String>();
1270 for (int i = 0; i < restapiUrl.length(); i++) {
1271 if (restapiUrl.charAt(i) == ',') {
1272 if (i + 9 < restapiUrl.length()) {
1273 String part = restapiUrl.substring(i + 1, i + 9);
1274 if (part.equals("https://") || part.startsWith("http://")) {
1275 urls.add(restapiUrl.substring(start, i));
1279 } else if (i == restapiUrl.length() - 1) {
1280 urls.add(restapiUrl.substring(start, i + 1));
1283 String[] arr = new String[urls.size()];
1284 return urls.toArray(arr);
1287 protected static boolean containsMultipleUrls(String restapiUrl) {
1288 Matcher m = retryPattern.matcher(restapiUrl);
1292 private static class FileParam {
1294 public String fileName;
1297 public String password;
1298 public HttpMethod httpMethod;
1299 public String responsePrefix;
1300 public boolean skipSending;
1301 public String oAuthConsumerKey;
1302 public String oAuthConsumerSecret;
1303 public String oAuthSignatureMethod;
1304 public String oAuthVersion;
1305 public AuthType authtype;
1308 private static class UebParam {
1310 public String topic;
1311 public String templateFileName;
1312 public String rootVarName;
1313 public String responsePrefix;
1314 public boolean skipSending;