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.InetSocketAddress;
36 import java.net.MalformedURLException;
37 import java.net.ProtocolException;
38 import java.net.Proxy;
39 import java.net.SocketException;
42 import java.nio.file.Files;
43 import java.nio.file.Paths;
44 import java.security.KeyStore;
45 import java.util.ArrayList;
46 import java.util.Base64;
47 import java.util.Collections;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Iterator;
51 import java.util.List;
53 import java.util.Map.Entry;
54 import java.util.Properties;
56 import java.util.regex.Matcher;
57 import java.util.regex.Pattern;
58 import javax.net.ssl.HttpsURLConnection;
59 import javax.net.ssl.KeyManagerFactory;
60 import javax.net.ssl.SSLContext;
61 import javax.ws.rs.ProcessingException;
62 import javax.ws.rs.client.Client;
63 import javax.ws.rs.client.ClientBuilder;
64 import javax.ws.rs.client.Entity;
65 import javax.ws.rs.client.Invocation;
66 import javax.ws.rs.client.WebTarget;
67 import javax.ws.rs.core.EntityTag;
68 import javax.ws.rs.core.Feature;
69 import javax.ws.rs.core.MediaType;
70 import javax.ws.rs.core.MultivaluedMap;
71 import javax.ws.rs.core.Response;
72 import javax.ws.rs.core.UriBuilder;
73 import org.apache.commons.lang3.StringUtils;
74 import org.codehaus.jettison.json.JSONException;
75 import org.codehaus.jettison.json.JSONObject;
76 import org.glassfish.jersey.client.ClientProperties;
77 import org.glassfish.jersey.client.ClientConfig;
78 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
79 import org.glassfish.jersey.client.HttpUrlConnectorProvider.ConnectionFactory;
80 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
81 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
82 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
83 import org.glassfish.jersey.media.multipart.MultiPart;
84 import org.glassfish.jersey.media.multipart.MultiPartFeature;
85 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
86 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
87 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
88 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
89 import org.onap.ccsdk.sli.core.utils.common.AcceptIpAddressHostNameVerifier;
90 import org.onap.ccsdk.sli.core.utils.common.EnvProperties;
91 import org.onap.logging.filter.base.HttpURLConnectionMetricUtil;
92 import org.onap.logging.filter.base.MetricLogClientFilter;
93 import org.onap.logging.filter.base.ONAPComponents;
94 import org.onap.logging.ref.slf4j.ONAPLogConstants;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
99 public class RestapiCallNode implements SvcLogicJavaPlugin {
101 protected static final String PARTNERS_FILE_NAME = "partners.json";
102 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
103 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
104 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
105 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
106 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
108 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
109 private String uebServers;
110 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
112 private String responseReceivedMessage = "Response received. Time: {}";
113 private String responseHttpCodeMessage = "HTTP response code: {}";
114 private String requestPostingException = "Exception while posting http request to client ";
115 protected static final String skipSendingMessage = "skipSending";
116 protected static final String responsePrefix = "responsePrefix";
117 protected static final String restapiUrlString = "restapiUrl";
118 protected static final String restapiUserKey = "restapiUser";
119 protected static final String restapiPasswordKey = "restapiPassword";
120 protected Integer httpConnectTimeout;
121 protected Integer httpReadTimeout;
123 protected HashMap<String, PartnerDetails> partnerStore;
124 private static final Pattern retryPattern = Pattern.compile(".*,(http|https):.*");
126 public RestapiCallNode() {
127 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
129 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
130 JSONObject partners = new JSONObject(jsonString);
131 partnerStore = new HashMap<>();
132 loadPartners(partners);
133 log.info("Partners support enabled");
134 } catch (Exception e) {
135 log.warn("Partners file could not be read, Partner support will not be enabled. " + e.getMessage());
138 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
139 Properties props = new EnvProperties();
141 uebServers = props.getProperty("servers");
142 log.info("UEB support enabled");
143 } catch (Exception e) {
144 log.warn("UEB properties could not be read, UEB support will not be enabled. " + e.getMessage());
146 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
147 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
150 @SuppressWarnings("unchecked")
151 protected void loadPartners(JSONObject partners) {
152 Iterator<String> keys = partners.keys();
153 String partnerUserKey = "user";
154 String partnerPasswordKey = "password";
155 String partnerUrlKey = "url";
157 while (keys.hasNext()) {
158 String partnerKey = keys.next();
160 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
161 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
163 if (partnerObject.has(partnerUrlKey)) {
164 url = partnerObject.getString(partnerUrlKey);
166 String userName = partnerObject.getString(partnerUserKey);
167 String password = partnerObject.getString(partnerPasswordKey);
168 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
169 partnerStore.put(partnerKey, details);
170 log.info("mapped partner using partner key " + partnerKey);
172 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
174 } catch (JSONException e) {
175 log.info("Couldn't map the partner using partner key " + partnerKey, e);
180 /* Unobfuscate param value */
181 private static String getObfuscatedVal(String paramValue) {
182 String resValue = paramValue;
183 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
185 String paramStr = paramValue.substring(2, paramValue.length()-1);
186 if (paramStr != null && paramStr.length() > 0)
188 String val = System.getenv(paramStr);
189 if (val != null && val.length() > 0)
192 log.info("Obfuscated value RESET for param value:" + paramValue);
200 * Returns parameters from the parameter map.
202 * @param paramMap parameter map
203 * @param p parameters instance
204 * @return parameters filed instance
205 * @throws SvcLogicException when svc logic exception occurs
207 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
209 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
210 p.requestBody = parseParam(paramMap, "requestBody", false, null);
211 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
212 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
213 if (p.restapiUrlSuffix != null) {
214 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
217 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
218 validateUrl(p.restapiUrl);
220 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
221 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
222 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
223 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
224 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
225 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
226 p.contentType = parseParam(paramMap, "contentType", false, null);
227 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
228 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
229 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
230 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
231 p.listNameList = getListNameList(paramMap);
232 String skipSendingStr = paramMap.get(skipSendingMessage);
233 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
234 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
235 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
236 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
237 p.ssl = p.keyStoreFileName != null && p.keyStorePassword != null;
238 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
239 p.partner = parseParam(paramMap, "partner", false, null);
240 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
241 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
242 p.accept = parseParam(paramMap, "accept", false, null);
243 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
244 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
245 p.targetEntity = parseParam(paramMap, "targetEntity", false, null);
246 p.disableHostVerification = valueOf(parseParam(paramMap, "disableHostVerification", false, "true"));
247 p.proxyUrl = parseParam(paramMap, "proxyUrl", false, null);
252 * Validates the given URL in the parameters.
254 * @param restapiUrl rest api URL
255 * @throws SvcLogicException when URL validation fails
257 private static void validateUrl(String restapiUrl) throws SvcLogicException {
258 if (containsMultipleUrls(restapiUrl)) {
259 String[] urls = getMultipleUrls(restapiUrl);
260 for (String url : urls) {
265 URI.create(restapiUrl);
266 } catch (IllegalArgumentException e) {
267 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
273 * Returns the list of list name.
275 * @param paramMap parameters map
276 * @return list of list name
278 private static Set<String> getListNameList(Map<String, String> paramMap) {
279 Set<String> ll = new HashSet<>();
280 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
281 if (entry.getKey().startsWith("listName")) {
282 ll.add(entry.getValue());
289 * Parses the parameter string map of property, validates if required, assigns default value if
290 * present and returns the value.
292 * @param paramMap string param map
293 * @param name name of the property
294 * @param required if value required
295 * @param def default value
296 * @return value of the property
297 * @throws SvcLogicException if required parameter value is empty
299 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
300 throws SvcLogicException {
301 String s = paramMap.get(name);
303 if (s == null || s.trim().length() == 0) {
307 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
311 StringBuilder value = new StringBuilder();
313 int i1 = s.indexOf('%');
315 int i2 = s.indexOf('%', i1 + 1);
320 String varName = s.substring(i1 + 1, i2);
321 String varValue = System.getenv(varName);
322 if (varValue == null) {
323 varValue = "%" + varName + "%";
326 value.append(s.substring(i, i1));
327 value.append(varValue);
330 i1 = s.indexOf('%', i);
332 value.append(s.substring(i));
334 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
336 return value.toString();
339 private static Object maskPassword(String name, Object value) {
340 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
341 for (String pwdName : pwdNames) {
342 if (name.contains(pwdName)) {
350 * Allows Directed Graphs the ability to interact with REST APIs.
352 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
356 * <th>Mandatory/Optional</th>
357 * <th>description</th>
358 * <th>example values</th></thead> <tbody>
360 * <td>templateFileName</td>
362 * <td>full path to template file that can be used to build a request</td>
363 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
366 * <td>restapiUrl</td>
368 * <td>url to send the request to</td>
369 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
372 * <td>restapiUser</td>
374 * <td>user name to use for http basic authentication</td>
378 * <td>restapiPassword</td>
380 * <td>unencrypted password to use for http basic authentication</td>
381 * <td>plain_password</td>
384 * <td>oAuthConsumerKey</td>
386 * <td>Consumer key to use for http oAuth authentication</td>
390 * <td>oAuthConsumerSecret</td>
392 * <td>Consumer secret to use for http oAuth authentication</td>
393 * <td>plain_secret</td>
396 * <td>oAuthSignatureMethod</td>
398 * <td>Consumer method to use for http oAuth authentication</td>
402 * <td>oAuthVersion</td>
404 * <td>Version http oAuth authentication</td>
408 * <td>contentType</td>
410 * <td>http content type to set in the http header</td>
411 * <td>usually application/json or application/xml</td>
416 * <td>should match request body format</td>
417 * <td>json or xml</td>
420 * <td>httpMethod</td>
422 * <td>http method to use when sending the request</td>
423 * <td>get post put delete patch</td>
426 * <td>responsePrefix</td>
428 * <td>location the response will be written to in context memory</td>
429 * <td>tmp.restapi.result</td>
432 * <td>listName[i]</td>
434 * <td>Used for processing XML responses with repeating
435 * elements.</td>vpn-information.vrf-details
439 * <td>skipSending</td>
442 * <td>true or false</td>
445 * <td>convertResponse</td>
447 * <td>whether the response should be converted</td>
448 * <td>true or false</td>
451 * <td>customHttpHeaders</td>
453 * <td>a list additional http headers to be passed in, follow the format in the example</td>
454 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
457 * <td>dumpHeaders</td>
459 * <td>when true writes http header content to context memory</td>
460 * <td>true or false</td>
465 * <td>used to retrieve username, password and url if partner store exists</td>
469 * <td>returnRequestPayload</td>
471 * <td>used to return payload built in the request</td>
472 * <td>true or false</td>
476 * @param ctx Reference to context memory
477 * @throws SvcLogicException
479 * @see String#split(String, int)
481 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
482 sendRequest(paramMap, ctx, null);
485 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
486 throws SvcLogicException {
488 HttpResponse r = new HttpResponse();
490 handlePartner(paramMap);
491 Parameters p = getParameters(paramMap, new Parameters());
492 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
493 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
495 if (containsMultipleUrls(p.restapiUrl) && retryPolicy == null) {
496 String[] urls = getMultipleUrls(p.restapiUrl);
497 retryPolicy = new RetryPolicy(urls, urls.length * 2);
498 p.restapiUrl = urls[0];
500 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
503 if (p.templateFileName != null) {
504 String reqTemplate = readFile(p.templateFileName);
505 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
506 } else if (p.requestBody != null) {
509 r = sendHttpRequest(req, p);
510 setResponseStatus(ctx, p.responsePrefix, r);
512 if (p.dumpHeaders && r.headers != null) {
513 for (Entry<String, List<String>> a : r.headers.entrySet()) {
514 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
518 if (p.returnRequestPayload && req != null) {
519 ctx.setAttribute(pp + "httpRequest", req);
522 if (r.body != null && r.body.trim().length() > 0) {
523 ctx.setAttribute(pp + "httpResponse", r.body);
525 if (p.convertResponse) {
526 Map<String, String> mm = null;
527 if (p.format == Format.XML) {
528 mm = XmlParser.convertToProperties(r.body, p.listNameList);
529 } else if (p.format == Format.JSON) {
530 mm = JsonParser.convertToProperties(r.body);
534 for (Map.Entry<String, String> entry : mm.entrySet()) {
535 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
540 } catch (SvcLogicException e) {
541 boolean shouldRetry = false;
542 if (e.getCause() != null && (e.getCause() instanceof SocketException || (e.getCause().getCause() != null && e.getCause().getCause() instanceof SocketException))) {
546 log.error("Error sending the request: " + e.getMessage(), e);
547 String prefix = parseParam(paramMap, responsePrefix, false, null);
548 if (retryPolicy == null || !shouldRetry) {
549 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
551 log.debug(retryPolicy.getRetryMessage());
553 // calling getNextHostName increments the retry count so it should be called before shouldRetry
554 String retryString = retryPolicy.getNextHostName();
555 if (retryPolicy.shouldRetry()) {
556 paramMap.put(restapiUrlString, retryString);
557 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
559 sendRequest(paramMap, ctx, retryPolicy);
561 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
562 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
564 } catch (Exception ex) {
565 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
566 + "has failed with error message " + ex.getMessage();
567 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
572 if (r != null && r.code >= 300) {
573 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
577 protected void handlePartner(Map<String, String> paramMap) {
578 String partner = paramMap.get("partner");
579 if (partner != null && partner.length() > 0) {
580 PartnerDetails details = partnerStore.get(partner);
581 paramMap.put(restapiUserKey, details.username);
582 paramMap.put(restapiPasswordKey, details.password);
583 if (paramMap.get(restapiUrlString) == null) {
584 paramMap.put(restapiUrlString, details.url);
589 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
590 log.info("Building {} started", format);
591 long t1 = System.currentTimeMillis();
592 String originalTemplate = template;
594 template = expandRepeats(ctx, template, 1);
596 Map<String, String> mm = new HashMap<>();
597 for (String s : ctx.getAttributeKeySet()) {
598 mm.put(s, ctx.getAttribute(s));
601 StringBuilder ss = new StringBuilder();
603 while (i < template.length()) {
604 int i1 = template.indexOf("${", i);
606 ss.append(template.substring(i));
610 int i2 = template.indexOf('}', i1 + 2);
612 throw new SvcLogicException("Template error: Matching } not found");
615 String var1 = template.substring(i1 + 2, i2);
616 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
617 if (value1 == null) {
618 // delete the whole element (line)
619 int i3 = template.lastIndexOf('\n', i1);
623 int i4 = template.indexOf('\n', i1);
625 i4 = template.length();
629 ss.append(template.substring(i, i3));
633 ss.append(template.substring(i, i1)).append(value1);
638 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
639 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
641 if (format == Format.JSON) {
642 req = XmlJsonUtil.removeLastCommaJson(req);
645 long t2 = System.currentTimeMillis();
646 log.info("Building {} completed. Time: {}", format, t2 - t1);
651 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
652 StringBuilder newTemplate = new StringBuilder();
654 while (k < template.length()) {
655 int i1 = template.indexOf("${repeat:", k);
657 newTemplate.append(template.substring(k));
661 int i2 = template.indexOf(':', i1 + 9);
663 throw new SvcLogicException(
664 "Template error: Context variable name followed by : is required after repeat");
667 // Find the closing }, store in i3
671 while (nn > 0 && i < template.length()) {
672 i3 = template.indexOf('}', i);
674 throw new SvcLogicException("Template error: Matching } not found");
676 int i32 = template.indexOf('{', i);
677 if (i32 >= 0 && i32 < i3) {
686 String var1 = template.substring(i1 + 9, i2);
687 String value1 = ctx.getAttribute(var1);
688 log.info(" {}:{}", var1, value1);
691 n = Integer.parseInt(value1);
692 } catch (NumberFormatException e) {
693 log.info("value1 not set or not a number, n will remain set at zero");
696 newTemplate.append(template.substring(k, i1));
698 String rpt = template.substring(i2 + 1, i3);
700 for (int ii = 0; ii < n; ii++) {
701 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
702 if (ii == n - 1 && ss.trim().endsWith(",")) {
703 int i4 = ss.lastIndexOf(',');
705 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
708 newTemplate.append(ss);
715 return newTemplate.toString();
718 return expandRepeats(ctx, newTemplate.toString(), level + 1);
721 protected String readFile(String fileName) throws SvcLogicException {
723 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
724 return new String(encoded, "UTF-8");
725 } catch (IOException | SecurityException e) {
726 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
730 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
731 Parameters p = new Parameters();
732 p.restapiUser = fp.user;
733 p.restapiPassword = fp.password;
734 p.oAuthConsumerKey = fp.oAuthConsumerKey;
735 p.oAuthVersion = fp.oAuthVersion;
736 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
737 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
738 p.authtype = fp.authtype;
739 return addAuthType(c, p);
742 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
743 if (p.authtype == AuthType.Unspecified) {
744 if (p.restapiUser != null && p.restapiPassword != null) {
745 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
746 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
747 Feature oAuth1Feature =
748 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
749 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
750 client.register(oAuth1Feature);
754 if (p.authtype == AuthType.DIGEST) {
755 if (p.restapiUser != null && p.restapiPassword != null) {
756 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
758 throw new SvcLogicException(
759 "oAUTH authentication type selected but all restapiUser and restapiPassword "
760 + "parameters doesn't exist",
763 } else if (p.authtype == AuthType.BASIC) {
764 if (p.restapiUser != null && p.restapiPassword != null) {
765 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
767 throw new SvcLogicException(
768 "oAUTH authentication type selected but all restapiUser and restapiPassword "
769 + "parameters doesn't exist",
772 } else if (p.authtype == AuthType.OAUTH) {
773 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
774 Feature oAuth1Feature = OAuth1ClientSupport
775 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
776 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
777 client.register(oAuth1Feature);
779 throw new SvcLogicException(
780 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
781 + "and oAuthSignatureMethod parameters doesn't exist",
790 * Receives the http response for the http request sent.
792 * @param request request msg
793 * @param p parameters
794 * @return HTTP response
795 * @throws SvcLogicException when sending http request fails
797 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
799 ClientConfig config = new ClientConfig();
800 if(!StringUtils.isEmpty(p.proxyUrl)) {
802 URL proxyUrl = new URL(p.proxyUrl);
803 HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
804 config.connectorProvider(cp);
806 new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()));
808 cp.connectionFactory(new ConnectionFactory() {
810 public HttpURLConnection getConnection(URL url) throws IOException {
811 return (HttpURLConnection) url.openConnection(proxy);
814 } catch (MalformedURLException e) {
815 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
819 SSLContext ssl = null;
820 if (p.ssl && p.restapiUrl.startsWith("https")) {
821 ssl = createSSLContext(p);
824 ClientBuilder builder =
825 ClientBuilder.newBuilder().hostnameVerifier(new AcceptIpAddressHostNameVerifier());
828 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
829 builder = builder.sslContext(ssl);
831 if (config != null) {
832 builder = builder.withConfig(config);
835 Client client = builder.build();
837 setClientTimeouts(client);
838 // Needed to support additional HTTP methods such as PATCH
839 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
840 client.register(new MetricLogClientFilter());
841 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
843 long t1 = System.currentTimeMillis();
845 HttpResponse r = new HttpResponse();
847 String accept = p.accept;
848 if (accept == null) {
849 accept = p.format == Format.XML ? "application/xml" : "application/json";
852 String contentType = p.contentType;
853 if (contentType == null) {
854 contentType = accept + ";charset=UTF-8";
857 if (!p.skipSending && !p.multipartFormData) {
858 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
860 if (p.format == Format.NONE) {
861 invocationBuilder.header("", "");
864 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
865 String[] keyValuePairs = p.customHttpHeaders.split(",");
866 for (String singlePair : keyValuePairs) {
867 int equalPosition = singlePair.indexOf('=');
868 invocationBuilder.header(singlePair.substring(0, equalPosition),
869 singlePair.substring(equalPosition + 1, singlePair.length()));
873 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
878 // When the HTTP operation has no body do not set the content-type
879 //setting content-type has caused errors with some servers when no body is present
880 if (request == null) {
881 response = invocationBuilder.method(p.httpMethod.toString());
884 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
886 } catch (ProcessingException | IllegalStateException e) {
887 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
890 r.code = response.getStatus();
891 r.headers = response.getStringHeaders();
892 EntityTag etag = response.getEntityTag();
894 r.message = etag.getValue();
896 if (response.hasEntity() && r.code != 204) {
897 r.body = response.readEntity(String.class);
899 } else if (!p.skipSending && p.multipartFormData) {
900 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
902 MultiPart multiPart = new MultiPart();
903 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
905 FileDataBodyPart fileDataBodyPart =
906 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
907 multiPart.bodyPart(fileDataBodyPart);
910 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
912 if (p.format == Format.NONE) {
913 invocationBuilder.header("", "");
916 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
917 String[] keyValuePairs = p.customHttpHeaders.split(",");
918 for (String singlePair : keyValuePairs) {
919 int equalPosition = singlePair.indexOf('=');
920 invocationBuilder.header(singlePair.substring(0, equalPosition),
921 singlePair.substring(equalPosition + 1, singlePair.length()));
929 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
930 } catch (ProcessingException | IllegalStateException e) {
931 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
934 r.code = response.getStatus();
935 r.headers = response.getStringHeaders();
936 EntityTag etag = response.getEntityTag();
938 r.message = etag.getValue();
940 if (response.hasEntity() && r.code != 204) {
941 r.body = response.readEntity(String.class);
946 long t2 = System.currentTimeMillis();
947 log.info(responseReceivedMessage, t2 - t1);
948 log.info(responseHttpCodeMessage, r.code);
949 log.info("HTTP response message: {}", r.message);
950 logHeaders(r.headers);
951 log.info("HTTP response: {}", r.body);
956 protected SSLContext createSSLContext(Parameters p) {
957 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
958 HttpsURLConnection.setDefaultHostnameVerifier(new AcceptIpAddressHostNameVerifier(p.disableHostVerification));
959 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
960 KeyStore ks = KeyStore.getInstance("PKCS12");
961 char[] pwd = p.keyStorePassword.toCharArray();
964 SSLContext ctx = SSLContext.getInstance("TLS");
965 ctx.init(kmf.getKeyManagers(), null, null);
967 } catch (Exception e) {
968 log.error("Error creating SSLContext: {}", e.getMessage(), e);
973 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
976 resp.message = errorMessage;
977 String pp = prefix != null ? prefix + '.' : "";
978 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
979 ctx.setAttribute(pp + "response-message", resp.message);
982 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
983 String pp = prefix != null ? prefix + '.' : "";
984 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
985 ctx.setAttribute(pp + "response-message", r.message);
988 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
989 HttpResponse r = null;
991 FileParam p = getFileParameters(paramMap);
992 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
994 r = sendHttpData(data, p);
996 for (int i = 0; i < 10 && r.code == 301; i++) {
997 String newUrl = r.headers2.get("Location").get(0);
999 log.info("Got response code 301. Sending same request to URL: " + newUrl);
1002 r = sendHttpData(data, p);
1005 setResponseStatus(ctx, p.responsePrefix, r);
1007 } catch (SvcLogicException | IOException e) {
1008 log.error("Error sending the request: {}", e.getMessage(), e);
1010 r = new HttpResponse();
1012 r.message = e.getMessage();
1013 String prefix = parseParam(paramMap, responsePrefix, false, null);
1014 setResponseStatus(ctx, prefix, r);
1017 if (r != null && r.code >= 300) {
1018 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1022 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
1023 FileParam p = new FileParam();
1024 p.fileName = parseParam(paramMap, "fileName", true, null);
1025 p.url = parseParam(paramMap, "url", true, null);
1026 p.user = parseParam(paramMap, "user", false, null);
1027 p.password = parseParam(paramMap, "password", false, null);
1028 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1029 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1030 String skipSendingStr = paramMap.get(skipSendingMessage);
1031 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1032 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1033 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1034 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1035 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1036 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1040 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1043 UebParam p = getUebParameters(paramMap);
1045 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1049 if (p.templateFileName == null) {
1050 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1051 p.templateFileName = defaultUebTemplateFileName;
1054 String reqTemplate = readFile(p.templateFileName);
1055 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1056 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1058 r = postOnUeb(req, p);
1059 setResponseStatus(ctx, p.responsePrefix, r);
1060 if (r.body != null) {
1061 ctx.setAttribute(pp + "httpResponse", r.body);
1064 } catch (SvcLogicException e) {
1065 log.error("Error sending the request: {}", e.getMessage(), e);
1067 r = new HttpResponse();
1069 r.message = e.getMessage();
1070 String prefix = parseParam(paramMap, responsePrefix, false, null);
1071 setResponseStatus(ctx, prefix, r);
1074 if (r.code >= 300) {
1075 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1079 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1080 URL url = new URL(p.url);
1081 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1083 log.info("Connection: " + con.getClass().getName());
1085 con.setRequestMethod(p.httpMethod.toString());
1086 con.setRequestProperty("Content-Type", "application/octet-stream");
1087 con.setRequestProperty("Accept", "*/*");
1088 con.setRequestProperty("Expect", "100-continue");
1089 con.setFixedLengthStreamingMode(data.length);
1090 con.setInstanceFollowRedirects(false);
1092 if (p.user != null && p.password != null) {
1093 String authString = p.user + ":" + p.password;
1094 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1095 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1098 con.setDoInput(true);
1099 con.setDoOutput(true);
1101 log.info("Sending file");
1102 long t1 = System.currentTimeMillis();
1104 HttpResponse r = new HttpResponse();
1107 if (!p.skipSending) {
1108 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1109 util.logBefore(con, ONAPComponents.DMAAP);
1113 boolean continue100failed = false;
1115 OutputStream os = con.getOutputStream();
1119 } catch (ProtocolException e) {
1120 continue100failed = true;
1123 r.code = con.getResponseCode();
1124 r.headers2 = con.getHeaderFields();
1126 if (r.code != 204 && !continue100failed) {
1127 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1129 StringBuffer response = new StringBuffer();
1130 while ((inputLine = in.readLine()) != null) {
1131 response.append(inputLine);
1135 r.body = response.toString();
1143 long t2 = System.currentTimeMillis();
1144 log.info("Response received. Time: {}", t2 - t1);
1145 log.info("HTTP response code: {}", r.code);
1146 log.info("HTTP response message: {}", r.message);
1147 logHeaders(r.headers2);
1148 log.info("HTTP response: {}", r.body);
1153 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1154 UebParam p = new UebParam();
1155 p.topic = parseParam(paramMap, "topic", true, null);
1156 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1157 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1158 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1159 String skipSendingStr = paramMap.get(skipSendingMessage);
1160 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1164 protected void logProperties(Map<String, Object> mm) {
1165 List<String> ll = new ArrayList<>();
1166 for (Object o : mm.keySet()) {
1169 Collections.sort(ll);
1171 log.info("Properties:");
1172 for (String name : ll) {
1173 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1177 protected void logHeaders(MultivaluedMap<String, String> mm) {
1178 log.info("HTTP response headers:");
1184 List<String> ll = new ArrayList<>();
1185 for (Object o : mm.keySet()) {
1188 Collections.sort(ll);
1190 for (String name : ll) {
1191 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1195 private void logHeaders(Map<String, List<String>> mm) {
1196 if (mm == null || mm.isEmpty()) {
1200 List<String> ll = new ArrayList<>();
1201 for (String s : mm.keySet()) {
1206 Collections.sort(ll);
1208 for (String name : ll) {
1209 List<String> v = mm.get(name);
1210 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1211 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1215 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1216 String[] urls = uebServers.split(" ");
1217 for (int i = 0; i < urls.length; i++) {
1218 if (!urls[i].endsWith("/")) {
1221 urls[i] += "events/" + p.topic;
1224 Client client = ClientBuilder.newBuilder().build();
1225 setClientTimeouts(client);
1226 WebTarget webTarget = client.target(urls[0]);
1228 log.info("UEB URL: {}", urls[0]);
1229 log.info("Sending request:");
1231 long t1 = System.currentTimeMillis();
1233 HttpResponse r = new HttpResponse();
1236 if (!p.skipSending) {
1237 String tt = "application/json";
1238 String tt1 = tt + ";charset=UTF-8";
1241 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1244 response = invocationBuilder.post(Entity.entity(request, tt1));
1245 } catch (ProcessingException e) {
1246 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1248 r.code = response.getStatus();
1249 r.headers = response.getStringHeaders();
1250 if (response.hasEntity()) {
1251 r.body = response.readEntity(String.class);
1255 long t2 = System.currentTimeMillis();
1256 log.info(responseReceivedMessage, t2 - t1);
1257 log.info(responseHttpCodeMessage, r.code);
1258 logHeaders(r.headers);
1259 log.info("HTTP response:\n {}", r.body);
1264 public void setUebServers(String uebServers) {
1265 this.uebServers = uebServers;
1268 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1269 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1272 protected void setClientTimeouts(Client client) {
1273 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1274 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1277 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1278 String stringValue = System.getProperty(propertyName);
1279 if (stringValue != null && stringValue.length() > 0) {
1281 return Integer.valueOf(stringValue);
1282 } catch (NumberFormatException e) {
1283 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1286 return defaultValue;
1289 protected static String[] getMultipleUrls(String restapiUrl) {
1290 List<String> urls = new ArrayList<>();
1292 for (int i = 0; i < restapiUrl.length(); i++) {
1293 if (restapiUrl.charAt(i) == ',') {
1294 if (i + 9 < restapiUrl.length()) {
1295 String part = restapiUrl.substring(i + 1, i + 9);
1296 if (part.equals("https://") || part.startsWith("http://")) {
1297 urls.add(restapiUrl.substring(start, i));
1301 } else if (i == restapiUrl.length() - 1) {
1302 urls.add(restapiUrl.substring(start, i + 1));
1305 String[] arr = new String[urls.size()];
1306 return urls.toArray(arr);
1309 protected static boolean containsMultipleUrls(String restapiUrl) {
1310 Matcher m = retryPattern.matcher(restapiUrl);
1314 private static class FileParam {
1316 public String fileName;
1319 public String password;
1320 public HttpMethod httpMethod;
1321 public String responsePrefix;
1322 public boolean skipSending;
1323 public String oAuthConsumerKey;
1324 public String oAuthConsumerSecret;
1325 public String oAuthSignatureMethod;
1326 public String oAuthVersion;
1327 public AuthType authtype;
1330 private static class UebParam {
1332 public String topic;
1333 public String templateFileName;
1334 public String rootVarName;
1335 public String responsePrefix;
1336 public boolean skipSending;