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);
245 * Validates the given URL in the parameters.
247 * @param restapiUrl rest api URL
248 * @throws SvcLogicException when URL validation fails
250 private static void validateUrl(String restapiUrl) throws SvcLogicException {
251 if (containsMultipleUrls(restapiUrl)) {
252 String[] urls = getMultipleUrls(restapiUrl);
253 for (String url : urls) {
258 URI.create(restapiUrl);
259 } catch (IllegalArgumentException e) {
260 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
266 * Returns the list of list name.
268 * @param paramMap parameters map
269 * @return list of list name
271 private static Set<String> getListNameList(Map<String, String> paramMap) {
272 Set<String> ll = new HashSet<>();
273 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
274 if (entry.getKey().startsWith("listName")) {
275 ll.add(entry.getValue());
282 * Parses the parameter string map of property, validates if required, assigns default value if
283 * present and returns the value.
285 * @param paramMap string param map
286 * @param name name of the property
287 * @param required if value required
288 * @param def default value
289 * @return value of the property
290 * @throws SvcLogicException if required parameter value is empty
292 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
293 throws SvcLogicException {
294 String s = paramMap.get(name);
296 if (s == null || s.trim().length() == 0) {
300 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
304 StringBuilder value = new StringBuilder();
306 int i1 = s.indexOf('%');
308 int i2 = s.indexOf('%', i1 + 1);
313 String varName = s.substring(i1 + 1, i2);
314 String varValue = System.getenv(varName);
315 if (varValue == null) {
316 varValue = "%" + varName + "%";
319 value.append(s.substring(i, i1));
320 value.append(varValue);
323 i1 = s.indexOf('%', i);
325 value.append(s.substring(i));
327 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
329 return value.toString();
332 private static Object maskPassword(String name, Object value) {
333 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
334 for (String pwdName : pwdNames) {
335 if (name.contains(pwdName)) {
343 * Allows Directed Graphs the ability to interact with REST APIs.
345 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
349 * <th>Mandatory/Optional</th>
350 * <th>description</th>
351 * <th>example values</th></thead> <tbody>
353 * <td>templateFileName</td>
355 * <td>full path to template file that can be used to build a request</td>
356 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
359 * <td>restapiUrl</td>
361 * <td>url to send the request to</td>
362 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
365 * <td>restapiUser</td>
367 * <td>user name to use for http basic authentication</td>
371 * <td>restapiPassword</td>
373 * <td>unencrypted password to use for http basic authentication</td>
374 * <td>plain_password</td>
377 * <td>oAuthConsumerKey</td>
379 * <td>Consumer key to use for http oAuth authentication</td>
383 * <td>oAuthConsumerSecret</td>
385 * <td>Consumer secret to use for http oAuth authentication</td>
386 * <td>plain_secret</td>
389 * <td>oAuthSignatureMethod</td>
391 * <td>Consumer method to use for http oAuth authentication</td>
395 * <td>oAuthVersion</td>
397 * <td>Version http oAuth authentication</td>
401 * <td>contentType</td>
403 * <td>http content type to set in the http header</td>
404 * <td>usually application/json or application/xml</td>
409 * <td>should match request body format</td>
410 * <td>json or xml</td>
413 * <td>httpMethod</td>
415 * <td>http method to use when sending the request</td>
416 * <td>get post put delete patch</td>
419 * <td>responsePrefix</td>
421 * <td>location the response will be written to in context memory</td>
422 * <td>tmp.restapi.result</td>
425 * <td>listName[i]</td>
427 * <td>Used for processing XML responses with repeating
428 * elements.</td>vpn-information.vrf-details
432 * <td>skipSending</td>
435 * <td>true or false</td>
438 * <td>convertResponse</td>
440 * <td>whether the response should be converted</td>
441 * <td>true or false</td>
444 * <td>customHttpHeaders</td>
446 * <td>a list additional http headers to be passed in, follow the format in the example</td>
447 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
450 * <td>dumpHeaders</td>
452 * <td>when true writes http header content to context memory</td>
453 * <td>true or false</td>
458 * <td>used to retrieve username, password and url if partner store exists</td>
462 * <td>returnRequestPayload</td>
464 * <td>used to return payload built in the request</td>
465 * <td>true or false</td>
469 * @param ctx Reference to context memory
470 * @throws SvcLogicException
472 * @see String#split(String, int)
474 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
475 sendRequest(paramMap, ctx, null);
478 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
479 throws SvcLogicException {
481 HttpResponse r = new HttpResponse();
483 handlePartner(paramMap);
484 Parameters p = getParameters(paramMap, new Parameters());
485 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
486 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
488 if (containsMultipleUrls(p.restapiUrl) && retryPolicy == null) {
489 String[] urls = getMultipleUrls(p.restapiUrl);
490 retryPolicy = new RetryPolicy(urls, urls.length * 2);
491 p.restapiUrl = urls[0];
493 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
496 if (p.templateFileName != null) {
497 String reqTemplate = readFile(p.templateFileName);
498 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
499 } else if (p.requestBody != null) {
502 r = sendHttpRequest(req, p);
503 setResponseStatus(ctx, p.responsePrefix, r);
505 if (p.dumpHeaders && r.headers != null) {
506 for (Entry<String, List<String>> a : r.headers.entrySet()) {
507 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
511 if (p.returnRequestPayload && req != null) {
512 ctx.setAttribute(pp + "httpRequest", req);
515 if (r.body != null && r.body.trim().length() > 0) {
516 ctx.setAttribute(pp + "httpResponse", r.body);
518 if (p.convertResponse) {
519 Map<String, String> mm = null;
520 if (p.format == Format.XML) {
521 mm = XmlParser.convertToProperties(r.body, p.listNameList);
522 } else if (p.format == Format.JSON) {
523 mm = JsonParser.convertToProperties(r.body);
527 for (Map.Entry<String, String> entry : mm.entrySet()) {
528 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
533 } catch (SvcLogicException e) {
534 boolean shouldRetry = false;
535 if (e.getCause() != null && (e.getCause() instanceof SocketException || (e.getCause().getCause() != null && e.getCause().getCause() instanceof SocketException))) {
539 log.error("Error sending the request: " + e.getMessage(), e);
540 String prefix = parseParam(paramMap, responsePrefix, false, null);
541 if (retryPolicy == null || !shouldRetry) {
542 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
544 log.debug(retryPolicy.getRetryMessage());
546 // calling getNextHostName increments the retry count so it should be called before shouldRetry
547 String retryString = retryPolicy.getNextHostName();
548 if (retryPolicy.shouldRetry()) {
549 paramMap.put(restapiUrlString, retryString);
550 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
552 sendRequest(paramMap, ctx, retryPolicy);
554 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
555 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
557 } catch (Exception ex) {
558 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
559 + "has failed with error message " + ex.getMessage();
560 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
565 if (r != null && r.code >= 300) {
566 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
570 protected void handlePartner(Map<String, String> paramMap) {
571 String partner = paramMap.get("partner");
572 if (partner != null && partner.length() > 0) {
573 PartnerDetails details = partnerStore.get(partner);
574 paramMap.put(restapiUserKey, details.username);
575 paramMap.put(restapiPasswordKey, details.password);
576 if (paramMap.get(restapiUrlString) == null) {
577 paramMap.put(restapiUrlString, details.url);
582 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
583 log.info("Building {} started", format);
584 long t1 = System.currentTimeMillis();
585 String originalTemplate = template;
587 template = expandRepeats(ctx, template, 1);
589 Map<String, String> mm = new HashMap<>();
590 for (String s : ctx.getAttributeKeySet()) {
591 mm.put(s, ctx.getAttribute(s));
594 StringBuilder ss = new StringBuilder();
596 while (i < template.length()) {
597 int i1 = template.indexOf("${", i);
599 ss.append(template.substring(i));
603 int i2 = template.indexOf('}', i1 + 2);
605 throw new SvcLogicException("Template error: Matching } not found");
608 String var1 = template.substring(i1 + 2, i2);
609 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
610 if (value1 == null || value1.trim().length() == 0) {
611 // delete the whole element (line)
612 int i3 = template.lastIndexOf('\n', i1);
616 int i4 = template.indexOf('\n', i1);
618 i4 = template.length();
622 ss.append(template.substring(i, i3));
626 ss.append(template.substring(i, i1)).append(value1);
631 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
632 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
634 if (format == Format.JSON) {
635 req = XmlJsonUtil.removeLastCommaJson(req);
638 long t2 = System.currentTimeMillis();
639 log.info("Building {} completed. Time: {}", format, t2 - t1);
644 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
645 StringBuilder newTemplate = new StringBuilder();
647 while (k < template.length()) {
648 int i1 = template.indexOf("${repeat:", k);
650 newTemplate.append(template.substring(k));
654 int i2 = template.indexOf(':', i1 + 9);
656 throw new SvcLogicException(
657 "Template error: Context variable name followed by : is required after repeat");
660 // Find the closing }, store in i3
664 while (nn > 0 && i < template.length()) {
665 i3 = template.indexOf('}', i);
667 throw new SvcLogicException("Template error: Matching } not found");
669 int i32 = template.indexOf('{', i);
670 if (i32 >= 0 && i32 < i3) {
679 String var1 = template.substring(i1 + 9, i2);
680 String value1 = ctx.getAttribute(var1);
681 log.info(" {}:{}", var1, value1);
684 n = Integer.parseInt(value1);
685 } catch (NumberFormatException e) {
686 log.info("value1 not set or not a number, n will remain set at zero");
689 newTemplate.append(template.substring(k, i1));
691 String rpt = template.substring(i2 + 1, i3);
693 for (int ii = 0; ii < n; ii++) {
694 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
695 if (ii == n - 1 && ss.trim().endsWith(",")) {
696 int i4 = ss.lastIndexOf(',');
698 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
701 newTemplate.append(ss);
708 return newTemplate.toString();
711 return expandRepeats(ctx, newTemplate.toString(), level + 1);
714 protected String readFile(String fileName) throws SvcLogicException {
716 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
717 return new String(encoded, "UTF-8");
718 } catch (IOException | SecurityException e) {
719 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
723 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
724 Parameters p = new Parameters();
725 p.restapiUser = fp.user;
726 p.restapiPassword = fp.password;
727 p.oAuthConsumerKey = fp.oAuthConsumerKey;
728 p.oAuthVersion = fp.oAuthVersion;
729 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
730 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
731 p.authtype = fp.authtype;
732 return addAuthType(c, p);
735 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
736 if (p.authtype == AuthType.Unspecified) {
737 if (p.restapiUser != null && p.restapiPassword != null) {
738 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
739 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
740 Feature oAuth1Feature =
741 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
742 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
743 client.register(oAuth1Feature);
747 if (p.authtype == AuthType.DIGEST) {
748 if (p.restapiUser != null && p.restapiPassword != null) {
749 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
751 throw new SvcLogicException(
752 "oAUTH authentication type selected but all restapiUser and restapiPassword "
753 + "parameters doesn't exist",
756 } else if (p.authtype == AuthType.BASIC) {
757 if (p.restapiUser != null && p.restapiPassword != null) {
758 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
760 throw new SvcLogicException(
761 "oAUTH authentication type selected but all restapiUser and restapiPassword "
762 + "parameters doesn't exist",
765 } else if (p.authtype == AuthType.OAUTH) {
766 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
767 Feature oAuth1Feature = OAuth1ClientSupport
768 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
769 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
770 client.register(oAuth1Feature);
772 throw new SvcLogicException(
773 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
774 + "and oAuthSignatureMethod parameters doesn't exist",
783 * Receives the http response for the http request sent.
785 * @param request request msg
786 * @param p parameters
787 * @return HTTP response
788 * @throws SvcLogicException when sending http request fails
790 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
792 SSLContext ssl = null;
793 if (p.ssl && p.restapiUrl.startsWith("https")) {
794 ssl = createSSLContext(p);
798 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
799 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier(new AcceptIpAddressHostNameVerifier()).build();
801 client = ClientBuilder.newBuilder().hostnameVerifier(new AcceptIpAddressHostNameVerifier()).build();
804 setClientTimeouts(client);
805 // Needed to support additional HTTP methods such as PATCH
806 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
807 client.register(new MetricLogClientFilter());
808 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
810 long t1 = System.currentTimeMillis();
812 HttpResponse r = new HttpResponse();
814 String accept = p.accept;
815 if (accept == null) {
816 accept = p.format == Format.XML ? "application/xml" : "application/json";
819 String contentType = p.contentType;
820 if (contentType == null) {
821 contentType = accept + ";charset=UTF-8";
824 if (!p.skipSending && !p.multipartFormData) {
826 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
828 if (p.format == Format.NONE) {
829 invocationBuilder.header("", "");
832 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
833 String[] keyValuePairs = p.customHttpHeaders.split(",");
834 for (String singlePair : keyValuePairs) {
835 int equalPosition = singlePair.indexOf('=');
836 invocationBuilder.header(singlePair.substring(0, equalPosition),
837 singlePair.substring(equalPosition + 1, singlePair.length()));
841 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
846 // When the HTTP operation has no body do not set the content-type
847 //setting content-type has caused errors with some servers when no body is present
848 if (request == null) {
849 response = invocationBuilder.method(p.httpMethod.toString());
851 log.info("Sending request below to url " + p.restapiUrl);
853 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
855 } catch (ProcessingException | IllegalStateException e) {
856 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
859 r.code = response.getStatus();
860 r.headers = response.getStringHeaders();
861 EntityTag etag = response.getEntityTag();
863 r.message = etag.getValue();
865 if (response.hasEntity() && r.code != 204) {
866 r.body = response.readEntity(String.class);
868 } else if (!p.skipSending && p.multipartFormData) {
870 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
872 MultiPart multiPart = new MultiPart();
873 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
875 FileDataBodyPart fileDataBodyPart =
876 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
877 multiPart.bodyPart(fileDataBodyPart);
880 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
882 if (p.format == Format.NONE) {
883 invocationBuilder.header("", "");
886 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
887 String[] keyValuePairs = p.customHttpHeaders.split(",");
888 for (String singlePair : keyValuePairs) {
889 int equalPosition = singlePair.indexOf('=');
890 invocationBuilder.header(singlePair.substring(0, equalPosition),
891 singlePair.substring(equalPosition + 1, singlePair.length()));
899 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
900 } catch (ProcessingException | IllegalStateException e) {
901 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
904 r.code = response.getStatus();
905 r.headers = response.getStringHeaders();
906 EntityTag etag = response.getEntityTag();
908 r.message = etag.getValue();
910 if (response.hasEntity() && r.code != 204) {
911 r.body = response.readEntity(String.class);
916 long t2 = System.currentTimeMillis();
917 log.info(responseReceivedMessage, t2 - t1);
918 log.info(responseHttpCodeMessage, r.code);
919 log.info("HTTP response message: {}", r.message);
920 logHeaders(r.headers);
921 log.info("HTTP response: {}", r.body);
926 protected SSLContext createSSLContext(Parameters p) {
927 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
928 HttpsURLConnection.setDefaultHostnameVerifier(new AcceptIpAddressHostNameVerifier());
929 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
930 KeyStore ks = KeyStore.getInstance("PKCS12");
931 char[] pwd = p.keyStorePassword.toCharArray();
934 SSLContext ctx = SSLContext.getInstance("TLS");
935 ctx.init(kmf.getKeyManagers(), null, null);
937 } catch (Exception e) {
938 log.error("Error creating SSLContext: {}", e.getMessage(), e);
943 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
946 resp.message = errorMessage;
947 String pp = prefix != null ? prefix + '.' : "";
948 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
949 ctx.setAttribute(pp + "response-message", resp.message);
952 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
953 String pp = prefix != null ? prefix + '.' : "";
954 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
955 ctx.setAttribute(pp + "response-message", r.message);
958 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
959 HttpResponse r = null;
961 FileParam p = getFileParameters(paramMap);
962 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
964 r = sendHttpData(data, p);
966 for (int i = 0; i < 10 && r.code == 301; i++) {
967 String newUrl = r.headers2.get("Location").get(0);
969 log.info("Got response code 301. Sending same request to URL: " + newUrl);
972 r = sendHttpData(data, p);
975 setResponseStatus(ctx, p.responsePrefix, r);
977 } catch (SvcLogicException | IOException e) {
978 log.error("Error sending the request: {}", e.getMessage(), e);
980 r = new HttpResponse();
982 r.message = e.getMessage();
983 String prefix = parseParam(paramMap, responsePrefix, false, null);
984 setResponseStatus(ctx, prefix, r);
987 if (r != null && r.code >= 300) {
988 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
992 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
993 FileParam p = new FileParam();
994 p.fileName = parseParam(paramMap, "fileName", true, null);
995 p.url = parseParam(paramMap, "url", true, null);
996 p.user = parseParam(paramMap, "user", false, null);
997 p.password = parseParam(paramMap, "password", false, null);
998 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
999 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1000 String skipSendingStr = paramMap.get(skipSendingMessage);
1001 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1002 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1003 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1004 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1005 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1006 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1010 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1013 UebParam p = getUebParameters(paramMap);
1015 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1019 if (p.templateFileName == null) {
1020 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1021 p.templateFileName = defaultUebTemplateFileName;
1024 String reqTemplate = readFile(p.templateFileName);
1025 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1026 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1028 r = postOnUeb(req, p);
1029 setResponseStatus(ctx, p.responsePrefix, r);
1030 if (r.body != null) {
1031 ctx.setAttribute(pp + "httpResponse", r.body);
1034 } catch (SvcLogicException e) {
1035 log.error("Error sending the request: {}", e.getMessage(), e);
1037 r = new HttpResponse();
1039 r.message = e.getMessage();
1040 String prefix = parseParam(paramMap, responsePrefix, false, null);
1041 setResponseStatus(ctx, prefix, r);
1044 if (r.code >= 300) {
1045 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1049 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1050 URL url = new URL(p.url);
1051 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1053 log.info("Connection: " + con.getClass().getName());
1055 con.setRequestMethod(p.httpMethod.toString());
1056 con.setRequestProperty("Content-Type", "application/octet-stream");
1057 con.setRequestProperty("Accept", "*/*");
1058 con.setRequestProperty("Expect", "100-continue");
1059 con.setFixedLengthStreamingMode(data.length);
1060 con.setInstanceFollowRedirects(false);
1062 if (p.user != null && p.password != null) {
1063 String authString = p.user + ":" + p.password;
1064 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1065 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1068 con.setDoInput(true);
1069 con.setDoOutput(true);
1071 log.info("Sending file");
1072 long t1 = System.currentTimeMillis();
1074 HttpResponse r = new HttpResponse();
1077 if (!p.skipSending) {
1078 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1079 util.logBefore(con, ONAPComponents.DMAAP);
1083 boolean continue100failed = false;
1085 OutputStream os = con.getOutputStream();
1089 } catch (ProtocolException e) {
1090 continue100failed = true;
1093 r.code = con.getResponseCode();
1094 r.headers2 = con.getHeaderFields();
1096 if (r.code != 204 && !continue100failed) {
1097 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1099 StringBuffer response = new StringBuffer();
1100 while ((inputLine = in.readLine()) != null) {
1101 response.append(inputLine);
1105 r.body = response.toString();
1113 long t2 = System.currentTimeMillis();
1114 log.info("Response received. Time: {}", t2 - t1);
1115 log.info("HTTP response code: {}", r.code);
1116 log.info("HTTP response message: {}", r.message);
1117 logHeaders(r.headers2);
1118 log.info("HTTP response: {}", r.body);
1123 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1124 UebParam p = new UebParam();
1125 p.topic = parseParam(paramMap, "topic", true, null);
1126 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1127 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1128 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1129 String skipSendingStr = paramMap.get(skipSendingMessage);
1130 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1134 protected void logProperties(Map<String, Object> mm) {
1135 List<String> ll = new ArrayList<>();
1136 for (Object o : mm.keySet()) {
1139 Collections.sort(ll);
1141 log.info("Properties:");
1142 for (String name : ll) {
1143 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1147 protected void logHeaders(MultivaluedMap<String, String> mm) {
1148 log.info("HTTP response headers:");
1154 List<String> ll = new ArrayList<>();
1155 for (Object o : mm.keySet()) {
1158 Collections.sort(ll);
1160 for (String name : ll) {
1161 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1165 private void logHeaders(Map<String, List<String>> mm) {
1166 if (mm == null || mm.isEmpty()) {
1170 List<String> ll = new ArrayList<>();
1171 for (String s : mm.keySet()) {
1176 Collections.sort(ll);
1178 for (String name : ll) {
1179 List<String> v = mm.get(name);
1180 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1181 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1185 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1186 String[] urls = uebServers.split(" ");
1187 for (int i = 0; i < urls.length; i++) {
1188 if (!urls[i].endsWith("/")) {
1191 urls[i] += "events/" + p.topic;
1194 Client client = ClientBuilder.newBuilder().build();
1195 setClientTimeouts(client);
1196 WebTarget webTarget = client.target(urls[0]);
1198 log.info("UEB URL: {}", urls[0]);
1199 log.info("Sending request:");
1201 long t1 = System.currentTimeMillis();
1203 HttpResponse r = new HttpResponse();
1206 if (!p.skipSending) {
1207 String tt = "application/json";
1208 String tt1 = tt + ";charset=UTF-8";
1211 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1214 response = invocationBuilder.post(Entity.entity(request, tt1));
1215 } catch (ProcessingException e) {
1216 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1218 r.code = response.getStatus();
1219 r.headers = response.getStringHeaders();
1220 if (response.hasEntity()) {
1221 r.body = response.readEntity(String.class);
1225 long t2 = System.currentTimeMillis();
1226 log.info(responseReceivedMessage, t2 - t1);
1227 log.info(responseHttpCodeMessage, r.code);
1228 logHeaders(r.headers);
1229 log.info("HTTP response:\n {}", r.body);
1234 public void setUebServers(String uebServers) {
1235 this.uebServers = uebServers;
1238 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1239 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1242 protected void setClientTimeouts(Client client) {
1243 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1244 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1247 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1248 String stringValue = System.getProperty(propertyName);
1249 if (stringValue != null && stringValue.length() > 0) {
1251 return Integer.valueOf(stringValue);
1252 } catch (NumberFormatException e) {
1253 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1256 return defaultValue;
1259 protected static String[] getMultipleUrls(String restapiUrl) {
1260 List<String> urls = new ArrayList<>();
1262 for (int i = 0; i < restapiUrl.length(); i++) {
1263 if (restapiUrl.charAt(i) == ',') {
1264 if (i + 9 < restapiUrl.length()) {
1265 String part = restapiUrl.substring(i + 1, i + 9);
1266 if (part.equals("https://") || part.startsWith("http://")) {
1267 urls.add(restapiUrl.substring(start, i));
1271 } else if (i == restapiUrl.length() - 1) {
1272 urls.add(restapiUrl.substring(start, i + 1));
1275 String[] arr = new String[urls.size()];
1276 return urls.toArray(arr);
1279 protected static boolean containsMultipleUrls(String restapiUrl) {
1280 Matcher m = retryPattern.matcher(restapiUrl);
1284 private static class FileParam {
1286 public String fileName;
1289 public String password;
1290 public HttpMethod httpMethod;
1291 public String responsePrefix;
1292 public boolean skipSending;
1293 public String oAuthConsumerKey;
1294 public String oAuthConsumerSecret;
1295 public String oAuthSignatureMethod;
1296 public String oAuthVersion;
1297 public AuthType authtype;
1300 private static class UebParam {
1302 public String topic;
1303 public String templateFileName;
1304 public String rootVarName;
1305 public String responsePrefix;
1306 public boolean skipSending;