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.ccsdk.sli.core.utils.common.AcceptIpAddressHostNameVerifier;
85 import org.onap.ccsdk.sli.core.utils.common.EnvProperties;
86 import org.onap.logging.filter.base.HttpURLConnectionMetricUtil;
87 import org.onap.logging.filter.base.MetricLogClientFilter;
88 import org.onap.logging.filter.base.ONAPComponents;
89 import org.onap.logging.ref.slf4j.ONAPLogConstants;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
94 public class RestapiCallNode implements SvcLogicJavaPlugin {
96 protected static final String PARTNERS_FILE_NAME = "partners.json";
97 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
98 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
99 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
100 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
101 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
103 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
104 private String uebServers;
105 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
107 private String responseReceivedMessage = "Response received. Time: {}";
108 private String responseHttpCodeMessage = "HTTP response code: {}";
109 private String requestPostingException = "Exception while posting http request to client ";
110 protected static final String skipSendingMessage = "skipSending";
111 protected static final String responsePrefix = "responsePrefix";
112 protected static final String restapiUrlString = "restapiUrl";
113 protected static final String restapiUserKey = "restapiUser";
114 protected static final String restapiPasswordKey = "restapiPassword";
115 protected Integer httpConnectTimeout;
116 protected Integer httpReadTimeout;
118 protected HashMap<String, PartnerDetails> partnerStore;
119 private static final Pattern retryPattern = Pattern.compile(".*,(http|https):.*");
121 public RestapiCallNode() {
122 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
124 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
125 JSONObject partners = new JSONObject(jsonString);
126 partnerStore = new HashMap<>();
127 loadPartners(partners);
128 log.info("Partners support enabled");
129 } catch (Exception e) {
130 log.warn("Partners file could not be read, Partner support will not be enabled. " + e.getMessage());
133 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
134 Properties props = new EnvProperties();
136 uebServers = props.getProperty("servers");
137 log.info("UEB support enabled");
138 } catch (Exception e) {
139 log.warn("UEB properties could not be read, UEB support will not be enabled. " + e.getMessage());
141 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
142 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
145 @SuppressWarnings("unchecked")
146 protected void loadPartners(JSONObject partners) {
147 Iterator<String> keys = partners.keys();
148 String partnerUserKey = "user";
149 String partnerPasswordKey = "password";
150 String partnerUrlKey = "url";
152 while (keys.hasNext()) {
153 String partnerKey = keys.next();
155 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
156 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
158 if (partnerObject.has(partnerUrlKey)) {
159 url = partnerObject.getString(partnerUrlKey);
161 String userName = partnerObject.getString(partnerUserKey);
162 String password = partnerObject.getString(partnerPasswordKey);
163 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
164 partnerStore.put(partnerKey, details);
165 log.info("mapped partner using partner key " + partnerKey);
167 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
169 } catch (JSONException e) {
170 log.info("Couldn't map the partner using partner key " + partnerKey, e);
175 /* Unobfuscate param value */
176 private static String getObfuscatedVal(String paramValue) {
177 String resValue = paramValue;
178 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
180 String paramStr = paramValue.substring(2, paramValue.length()-1);
181 if (paramStr != null && paramStr.length() > 0)
183 String val = System.getenv(paramStr);
184 if (val != null && val.length() > 0)
187 log.info("Obfuscated value RESET for param value:" + paramValue);
195 * Returns parameters from the parameter map.
197 * @param paramMap parameter map
198 * @param p parameters instance
199 * @return parameters filed instance
200 * @throws SvcLogicException when svc logic exception occurs
202 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
204 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
205 p.requestBody = parseParam(paramMap, "requestBody", false, null);
206 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
207 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
208 if (p.restapiUrlSuffix != null) {
209 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
212 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
213 validateUrl(p.restapiUrl);
215 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
216 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
217 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
218 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
219 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
220 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
221 p.contentType = parseParam(paramMap, "contentType", false, null);
222 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
223 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
224 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
225 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
226 p.listNameList = getListNameList(paramMap);
227 String skipSendingStr = paramMap.get(skipSendingMessage);
228 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
229 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
230 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
231 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
232 p.ssl = p.keyStoreFileName != null && p.keyStorePassword != null;
233 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
234 p.partner = parseParam(paramMap, "partner", false, null);
235 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
236 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
237 p.accept = parseParam(paramMap, "accept", false, null);
238 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
239 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
240 p.targetEntity = parseParam(paramMap, "targetEntity", false, null);
241 p.disableHostVerification = valueOf(parseParam(paramMap, "disableHostVerification", false, "true"));
246 * Validates the given URL in the parameters.
248 * @param restapiUrl rest api URL
249 * @throws SvcLogicException when URL validation fails
251 private static void validateUrl(String restapiUrl) throws SvcLogicException {
252 if (containsMultipleUrls(restapiUrl)) {
253 String[] urls = getMultipleUrls(restapiUrl);
254 for (String url : urls) {
259 URI.create(restapiUrl);
260 } catch (IllegalArgumentException e) {
261 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
267 * Returns the list of list name.
269 * @param paramMap parameters map
270 * @return list of list name
272 private static Set<String> getListNameList(Map<String, String> paramMap) {
273 Set<String> ll = new HashSet<>();
274 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
275 if (entry.getKey().startsWith("listName")) {
276 ll.add(entry.getValue());
283 * Parses the parameter string map of property, validates if required, assigns default value if
284 * present and returns the value.
286 * @param paramMap string param map
287 * @param name name of the property
288 * @param required if value required
289 * @param def default value
290 * @return value of the property
291 * @throws SvcLogicException if required parameter value is empty
293 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
294 throws SvcLogicException {
295 String s = paramMap.get(name);
297 if (s == null || s.trim().length() == 0) {
301 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
305 StringBuilder value = new StringBuilder();
307 int i1 = s.indexOf('%');
309 int i2 = s.indexOf('%', i1 + 1);
314 String varName = s.substring(i1 + 1, i2);
315 String varValue = System.getenv(varName);
316 if (varValue == null) {
317 varValue = "%" + varName + "%";
320 value.append(s.substring(i, i1));
321 value.append(varValue);
324 i1 = s.indexOf('%', i);
326 value.append(s.substring(i));
328 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
330 return value.toString();
333 private static Object maskPassword(String name, Object value) {
334 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
335 for (String pwdName : pwdNames) {
336 if (name.contains(pwdName)) {
344 * Allows Directed Graphs the ability to interact with REST APIs.
346 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
350 * <th>Mandatory/Optional</th>
351 * <th>description</th>
352 * <th>example values</th></thead> <tbody>
354 * <td>templateFileName</td>
356 * <td>full path to template file that can be used to build a request</td>
357 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
360 * <td>restapiUrl</td>
362 * <td>url to send the request to</td>
363 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
366 * <td>restapiUser</td>
368 * <td>user name to use for http basic authentication</td>
372 * <td>restapiPassword</td>
374 * <td>unencrypted password to use for http basic authentication</td>
375 * <td>plain_password</td>
378 * <td>oAuthConsumerKey</td>
380 * <td>Consumer key to use for http oAuth authentication</td>
384 * <td>oAuthConsumerSecret</td>
386 * <td>Consumer secret to use for http oAuth authentication</td>
387 * <td>plain_secret</td>
390 * <td>oAuthSignatureMethod</td>
392 * <td>Consumer method to use for http oAuth authentication</td>
396 * <td>oAuthVersion</td>
398 * <td>Version http oAuth authentication</td>
402 * <td>contentType</td>
404 * <td>http content type to set in the http header</td>
405 * <td>usually application/json or application/xml</td>
410 * <td>should match request body format</td>
411 * <td>json or xml</td>
414 * <td>httpMethod</td>
416 * <td>http method to use when sending the request</td>
417 * <td>get post put delete patch</td>
420 * <td>responsePrefix</td>
422 * <td>location the response will be written to in context memory</td>
423 * <td>tmp.restapi.result</td>
426 * <td>listName[i]</td>
428 * <td>Used for processing XML responses with repeating
429 * elements.</td>vpn-information.vrf-details
433 * <td>skipSending</td>
436 * <td>true or false</td>
439 * <td>convertResponse</td>
441 * <td>whether the response should be converted</td>
442 * <td>true or false</td>
445 * <td>customHttpHeaders</td>
447 * <td>a list additional http headers to be passed in, follow the format in the example</td>
448 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
451 * <td>dumpHeaders</td>
453 * <td>when true writes http header content to context memory</td>
454 * <td>true or false</td>
459 * <td>used to retrieve username, password and url if partner store exists</td>
463 * <td>returnRequestPayload</td>
465 * <td>used to return payload built in the request</td>
466 * <td>true or false</td>
470 * @param ctx Reference to context memory
471 * @throws SvcLogicException
473 * @see String#split(String, int)
475 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
476 sendRequest(paramMap, ctx, null);
479 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
480 throws SvcLogicException {
482 HttpResponse r = new HttpResponse();
484 handlePartner(paramMap);
485 Parameters p = getParameters(paramMap, new Parameters());
486 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
487 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
489 if (containsMultipleUrls(p.restapiUrl) && retryPolicy == null) {
490 String[] urls = getMultipleUrls(p.restapiUrl);
491 retryPolicy = new RetryPolicy(urls, urls.length * 2);
492 p.restapiUrl = urls[0];
494 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
497 if (p.templateFileName != null) {
498 String reqTemplate = readFile(p.templateFileName);
499 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
500 } else if (p.requestBody != null) {
503 r = sendHttpRequest(req, p);
504 setResponseStatus(ctx, p.responsePrefix, r);
506 if (p.dumpHeaders && r.headers != null) {
507 for (Entry<String, List<String>> a : r.headers.entrySet()) {
508 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
512 if (p.returnRequestPayload && req != null) {
513 ctx.setAttribute(pp + "httpRequest", req);
516 if (r.body != null && r.body.trim().length() > 0) {
517 ctx.setAttribute(pp + "httpResponse", r.body);
519 if (p.convertResponse) {
520 Map<String, String> mm = null;
521 if (p.format == Format.XML) {
522 mm = XmlParser.convertToProperties(r.body, p.listNameList);
523 } else if (p.format == Format.JSON) {
524 mm = JsonParser.convertToProperties(r.body);
528 for (Map.Entry<String, String> entry : mm.entrySet()) {
529 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
534 } catch (SvcLogicException e) {
535 boolean shouldRetry = false;
536 if (e.getCause() != null && (e.getCause() instanceof SocketException || (e.getCause().getCause() != null && e.getCause().getCause() instanceof SocketException))) {
540 log.error("Error sending the request: " + e.getMessage(), e);
541 String prefix = parseParam(paramMap, responsePrefix, false, null);
542 if (retryPolicy == null || !shouldRetry) {
543 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
545 log.debug(retryPolicy.getRetryMessage());
547 // calling getNextHostName increments the retry count so it should be called before shouldRetry
548 String retryString = retryPolicy.getNextHostName();
549 if (retryPolicy.shouldRetry()) {
550 paramMap.put(restapiUrlString, retryString);
551 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
553 sendRequest(paramMap, ctx, retryPolicy);
555 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
556 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
558 } catch (Exception ex) {
559 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
560 + "has failed with error message " + ex.getMessage();
561 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
566 if (r != null && r.code >= 300) {
567 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
571 protected void handlePartner(Map<String, String> paramMap) {
572 String partner = paramMap.get("partner");
573 if (partner != null && partner.length() > 0) {
574 PartnerDetails details = partnerStore.get(partner);
575 paramMap.put(restapiUserKey, details.username);
576 paramMap.put(restapiPasswordKey, details.password);
577 if (paramMap.get(restapiUrlString) == null) {
578 paramMap.put(restapiUrlString, details.url);
583 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
584 log.info("Building {} started", format);
585 long t1 = System.currentTimeMillis();
586 String originalTemplate = template;
588 template = expandRepeats(ctx, template, 1);
590 Map<String, String> mm = new HashMap<>();
591 for (String s : ctx.getAttributeKeySet()) {
592 mm.put(s, ctx.getAttribute(s));
595 StringBuilder ss = new StringBuilder();
597 while (i < template.length()) {
598 int i1 = template.indexOf("${", i);
600 ss.append(template.substring(i));
604 int i2 = template.indexOf('}', i1 + 2);
606 throw new SvcLogicException("Template error: Matching } not found");
609 String var1 = template.substring(i1 + 2, i2);
610 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
611 if (value1 == null || value1.trim().length() == 0) {
612 // delete the whole element (line)
613 int i3 = template.lastIndexOf('\n', i1);
617 int i4 = template.indexOf('\n', i1);
619 i4 = template.length();
623 ss.append(template.substring(i, i3));
627 ss.append(template.substring(i, i1)).append(value1);
632 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
633 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
635 if (format == Format.JSON) {
636 req = XmlJsonUtil.removeLastCommaJson(req);
639 long t2 = System.currentTimeMillis();
640 log.info("Building {} completed. Time: {}", format, t2 - t1);
645 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
646 StringBuilder newTemplate = new StringBuilder();
648 while (k < template.length()) {
649 int i1 = template.indexOf("${repeat:", k);
651 newTemplate.append(template.substring(k));
655 int i2 = template.indexOf(':', i1 + 9);
657 throw new SvcLogicException(
658 "Template error: Context variable name followed by : is required after repeat");
661 // Find the closing }, store in i3
665 while (nn > 0 && i < template.length()) {
666 i3 = template.indexOf('}', i);
668 throw new SvcLogicException("Template error: Matching } not found");
670 int i32 = template.indexOf('{', i);
671 if (i32 >= 0 && i32 < i3) {
680 String var1 = template.substring(i1 + 9, i2);
681 String value1 = ctx.getAttribute(var1);
682 log.info(" {}:{}", var1, value1);
685 n = Integer.parseInt(value1);
686 } catch (NumberFormatException e) {
687 log.info("value1 not set or not a number, n will remain set at zero");
690 newTemplate.append(template.substring(k, i1));
692 String rpt = template.substring(i2 + 1, i3);
694 for (int ii = 0; ii < n; ii++) {
695 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
696 if (ii == n - 1 && ss.trim().endsWith(",")) {
697 int i4 = ss.lastIndexOf(',');
699 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
702 newTemplate.append(ss);
709 return newTemplate.toString();
712 return expandRepeats(ctx, newTemplate.toString(), level + 1);
715 protected String readFile(String fileName) throws SvcLogicException {
717 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
718 return new String(encoded, "UTF-8");
719 } catch (IOException | SecurityException e) {
720 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
724 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
725 Parameters p = new Parameters();
726 p.restapiUser = fp.user;
727 p.restapiPassword = fp.password;
728 p.oAuthConsumerKey = fp.oAuthConsumerKey;
729 p.oAuthVersion = fp.oAuthVersion;
730 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
731 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
732 p.authtype = fp.authtype;
733 return addAuthType(c, p);
736 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
737 if (p.authtype == AuthType.Unspecified) {
738 if (p.restapiUser != null && p.restapiPassword != null) {
739 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
740 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
741 Feature oAuth1Feature =
742 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
743 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
744 client.register(oAuth1Feature);
748 if (p.authtype == AuthType.DIGEST) {
749 if (p.restapiUser != null && p.restapiPassword != null) {
750 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
752 throw new SvcLogicException(
753 "oAUTH authentication type selected but all restapiUser and restapiPassword "
754 + "parameters doesn't exist",
757 } else if (p.authtype == AuthType.BASIC) {
758 if (p.restapiUser != null && p.restapiPassword != null) {
759 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
761 throw new SvcLogicException(
762 "oAUTH authentication type selected but all restapiUser and restapiPassword "
763 + "parameters doesn't exist",
766 } else if (p.authtype == AuthType.OAUTH) {
767 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
768 Feature oAuth1Feature = OAuth1ClientSupport
769 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
770 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
771 client.register(oAuth1Feature);
773 throw new SvcLogicException(
774 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
775 + "and oAuthSignatureMethod parameters doesn't exist",
784 * Receives the http response for the http request sent.
786 * @param request request msg
787 * @param p parameters
788 * @return HTTP response
789 * @throws SvcLogicException when sending http request fails
791 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
793 SSLContext ssl = null;
794 if (p.ssl && p.restapiUrl.startsWith("https")) {
795 ssl = createSSLContext(p);
799 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
800 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier(new AcceptIpAddressHostNameVerifier()).build();
802 client = ClientBuilder.newBuilder().hostnameVerifier(new AcceptIpAddressHostNameVerifier()).build();
805 setClientTimeouts(client);
806 // Needed to support additional HTTP methods such as PATCH
807 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
808 client.register(new MetricLogClientFilter());
809 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
811 long t1 = System.currentTimeMillis();
813 HttpResponse r = new HttpResponse();
815 String accept = p.accept;
816 if (accept == null) {
817 accept = p.format == Format.XML ? "application/xml" : "application/json";
820 String contentType = p.contentType;
821 if (contentType == null) {
822 contentType = accept + ";charset=UTF-8";
825 if (!p.skipSending && !p.multipartFormData) {
827 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
829 if (p.format == Format.NONE) {
830 invocationBuilder.header("", "");
833 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
834 String[] keyValuePairs = p.customHttpHeaders.split(",");
835 for (String singlePair : keyValuePairs) {
836 int equalPosition = singlePair.indexOf('=');
837 invocationBuilder.header(singlePair.substring(0, equalPosition),
838 singlePair.substring(equalPosition + 1, singlePair.length()));
842 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
847 // When the HTTP operation has no body do not set the content-type
848 //setting content-type has caused errors with some servers when no body is present
849 if (request == null) {
850 response = invocationBuilder.method(p.httpMethod.toString());
852 log.info("Sending request below to url " + p.restapiUrl);
854 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
856 } catch (ProcessingException | IllegalStateException e) {
857 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
860 r.code = response.getStatus();
861 r.headers = response.getStringHeaders();
862 EntityTag etag = response.getEntityTag();
864 r.message = etag.getValue();
866 if (response.hasEntity() && r.code != 204) {
867 r.body = response.readEntity(String.class);
869 } else if (!p.skipSending && p.multipartFormData) {
871 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
873 MultiPart multiPart = new MultiPart();
874 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
876 FileDataBodyPart fileDataBodyPart =
877 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
878 multiPart.bodyPart(fileDataBodyPart);
881 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
883 if (p.format == Format.NONE) {
884 invocationBuilder.header("", "");
887 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
888 String[] keyValuePairs = p.customHttpHeaders.split(",");
889 for (String singlePair : keyValuePairs) {
890 int equalPosition = singlePair.indexOf('=');
891 invocationBuilder.header(singlePair.substring(0, equalPosition),
892 singlePair.substring(equalPosition + 1, singlePair.length()));
900 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
901 } catch (ProcessingException | IllegalStateException e) {
902 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
905 r.code = response.getStatus();
906 r.headers = response.getStringHeaders();
907 EntityTag etag = response.getEntityTag();
909 r.message = etag.getValue();
911 if (response.hasEntity() && r.code != 204) {
912 r.body = response.readEntity(String.class);
917 long t2 = System.currentTimeMillis();
918 log.info(responseReceivedMessage, t2 - t1);
919 log.info(responseHttpCodeMessage, r.code);
920 log.info("HTTP response message: {}", r.message);
921 logHeaders(r.headers);
922 log.info("HTTP response: {}", r.body);
927 protected SSLContext createSSLContext(Parameters p) {
928 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
929 HttpsURLConnection.setDefaultHostnameVerifier(new AcceptIpAddressHostNameVerifier(p.disableHostVerification));
930 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
931 KeyStore ks = KeyStore.getInstance("PKCS12");
932 char[] pwd = p.keyStorePassword.toCharArray();
935 SSLContext ctx = SSLContext.getInstance("TLS");
936 ctx.init(kmf.getKeyManagers(), null, null);
938 } catch (Exception e) {
939 log.error("Error creating SSLContext: {}", e.getMessage(), e);
944 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
947 resp.message = errorMessage;
948 String pp = prefix != null ? prefix + '.' : "";
949 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
950 ctx.setAttribute(pp + "response-message", resp.message);
953 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
954 String pp = prefix != null ? prefix + '.' : "";
955 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
956 ctx.setAttribute(pp + "response-message", r.message);
959 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
960 HttpResponse r = null;
962 FileParam p = getFileParameters(paramMap);
963 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
965 r = sendHttpData(data, p);
967 for (int i = 0; i < 10 && r.code == 301; i++) {
968 String newUrl = r.headers2.get("Location").get(0);
970 log.info("Got response code 301. Sending same request to URL: " + newUrl);
973 r = sendHttpData(data, p);
976 setResponseStatus(ctx, p.responsePrefix, r);
978 } catch (SvcLogicException | IOException e) {
979 log.error("Error sending the request: {}", e.getMessage(), e);
981 r = new HttpResponse();
983 r.message = e.getMessage();
984 String prefix = parseParam(paramMap, responsePrefix, false, null);
985 setResponseStatus(ctx, prefix, r);
988 if (r != null && r.code >= 300) {
989 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
993 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
994 FileParam p = new FileParam();
995 p.fileName = parseParam(paramMap, "fileName", true, null);
996 p.url = parseParam(paramMap, "url", true, null);
997 p.user = parseParam(paramMap, "user", false, null);
998 p.password = parseParam(paramMap, "password", false, null);
999 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1000 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1001 String skipSendingStr = paramMap.get(skipSendingMessage);
1002 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1003 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1004 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1005 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1006 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1007 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1011 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1014 UebParam p = getUebParameters(paramMap);
1016 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1020 if (p.templateFileName == null) {
1021 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1022 p.templateFileName = defaultUebTemplateFileName;
1025 String reqTemplate = readFile(p.templateFileName);
1026 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1027 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1029 r = postOnUeb(req, p);
1030 setResponseStatus(ctx, p.responsePrefix, r);
1031 if (r.body != null) {
1032 ctx.setAttribute(pp + "httpResponse", r.body);
1035 } catch (SvcLogicException e) {
1036 log.error("Error sending the request: {}", e.getMessage(), e);
1038 r = new HttpResponse();
1040 r.message = e.getMessage();
1041 String prefix = parseParam(paramMap, responsePrefix, false, null);
1042 setResponseStatus(ctx, prefix, r);
1045 if (r.code >= 300) {
1046 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1050 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1051 URL url = new URL(p.url);
1052 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1054 log.info("Connection: " + con.getClass().getName());
1056 con.setRequestMethod(p.httpMethod.toString());
1057 con.setRequestProperty("Content-Type", "application/octet-stream");
1058 con.setRequestProperty("Accept", "*/*");
1059 con.setRequestProperty("Expect", "100-continue");
1060 con.setFixedLengthStreamingMode(data.length);
1061 con.setInstanceFollowRedirects(false);
1063 if (p.user != null && p.password != null) {
1064 String authString = p.user + ":" + p.password;
1065 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1066 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1069 con.setDoInput(true);
1070 con.setDoOutput(true);
1072 log.info("Sending file");
1073 long t1 = System.currentTimeMillis();
1075 HttpResponse r = new HttpResponse();
1078 if (!p.skipSending) {
1079 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1080 util.logBefore(con, ONAPComponents.DMAAP);
1084 boolean continue100failed = false;
1086 OutputStream os = con.getOutputStream();
1090 } catch (ProtocolException e) {
1091 continue100failed = true;
1094 r.code = con.getResponseCode();
1095 r.headers2 = con.getHeaderFields();
1097 if (r.code != 204 && !continue100failed) {
1098 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1100 StringBuffer response = new StringBuffer();
1101 while ((inputLine = in.readLine()) != null) {
1102 response.append(inputLine);
1106 r.body = response.toString();
1114 long t2 = System.currentTimeMillis();
1115 log.info("Response received. Time: {}", t2 - t1);
1116 log.info("HTTP response code: {}", r.code);
1117 log.info("HTTP response message: {}", r.message);
1118 logHeaders(r.headers2);
1119 log.info("HTTP response: {}", r.body);
1124 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1125 UebParam p = new UebParam();
1126 p.topic = parseParam(paramMap, "topic", true, null);
1127 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1128 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1129 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1130 String skipSendingStr = paramMap.get(skipSendingMessage);
1131 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1135 protected void logProperties(Map<String, Object> mm) {
1136 List<String> ll = new ArrayList<>();
1137 for (Object o : mm.keySet()) {
1140 Collections.sort(ll);
1142 log.info("Properties:");
1143 for (String name : ll) {
1144 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1148 protected void logHeaders(MultivaluedMap<String, String> mm) {
1149 log.info("HTTP response headers:");
1155 List<String> ll = new ArrayList<>();
1156 for (Object o : mm.keySet()) {
1159 Collections.sort(ll);
1161 for (String name : ll) {
1162 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1166 private void logHeaders(Map<String, List<String>> mm) {
1167 if (mm == null || mm.isEmpty()) {
1171 List<String> ll = new ArrayList<>();
1172 for (String s : mm.keySet()) {
1177 Collections.sort(ll);
1179 for (String name : ll) {
1180 List<String> v = mm.get(name);
1181 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1182 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1186 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1187 String[] urls = uebServers.split(" ");
1188 for (int i = 0; i < urls.length; i++) {
1189 if (!urls[i].endsWith("/")) {
1192 urls[i] += "events/" + p.topic;
1195 Client client = ClientBuilder.newBuilder().build();
1196 setClientTimeouts(client);
1197 WebTarget webTarget = client.target(urls[0]);
1199 log.info("UEB URL: {}", urls[0]);
1200 log.info("Sending request:");
1202 long t1 = System.currentTimeMillis();
1204 HttpResponse r = new HttpResponse();
1207 if (!p.skipSending) {
1208 String tt = "application/json";
1209 String tt1 = tt + ";charset=UTF-8";
1212 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1215 response = invocationBuilder.post(Entity.entity(request, tt1));
1216 } catch (ProcessingException e) {
1217 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1219 r.code = response.getStatus();
1220 r.headers = response.getStringHeaders();
1221 if (response.hasEntity()) {
1222 r.body = response.readEntity(String.class);
1226 long t2 = System.currentTimeMillis();
1227 log.info(responseReceivedMessage, t2 - t1);
1228 log.info(responseHttpCodeMessage, r.code);
1229 logHeaders(r.headers);
1230 log.info("HTTP response:\n {}", r.body);
1235 public void setUebServers(String uebServers) {
1236 this.uebServers = uebServers;
1239 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1240 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1243 protected void setClientTimeouts(Client client) {
1244 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1245 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1248 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1249 String stringValue = System.getProperty(propertyName);
1250 if (stringValue != null && stringValue.length() > 0) {
1252 return Integer.valueOf(stringValue);
1253 } catch (NumberFormatException e) {
1254 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1257 return defaultValue;
1260 protected static String[] getMultipleUrls(String restapiUrl) {
1261 List<String> urls = new ArrayList<>();
1263 for (int i = 0; i < restapiUrl.length(); i++) {
1264 if (restapiUrl.charAt(i) == ',') {
1265 if (i + 9 < restapiUrl.length()) {
1266 String part = restapiUrl.substring(i + 1, i + 9);
1267 if (part.equals("https://") || part.startsWith("http://")) {
1268 urls.add(restapiUrl.substring(start, i));
1272 } else if (i == restapiUrl.length() - 1) {
1273 urls.add(restapiUrl.substring(start, i + 1));
1276 String[] arr = new String[urls.size()];
1277 return urls.toArray(arr);
1280 protected static boolean containsMultipleUrls(String restapiUrl) {
1281 Matcher m = retryPattern.matcher(restapiUrl);
1285 private static class FileParam {
1287 public String fileName;
1290 public String password;
1291 public HttpMethod httpMethod;
1292 public String responsePrefix;
1293 public boolean skipSending;
1294 public String oAuthConsumerKey;
1295 public String oAuthConsumerSecret;
1296 public String oAuthSignatureMethod;
1297 public String oAuthVersion;
1298 public AuthType authtype;
1301 private static class UebParam {
1303 public String topic;
1304 public String templateFileName;
1305 public String rootVarName;
1306 public String responsePrefix;
1307 public boolean skipSending;