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 boolean keepEmpty = var1.startsWith("~");
617 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
618 if (value1 == null || (value1.trim().length() == 0 && !keepEmpty)) {
619 // delete the whole element (line)
620 int i3 = template.lastIndexOf('\n', i1);
624 int i4 = template.indexOf('\n', i1);
626 i4 = template.length();
630 ss.append(template.substring(i, i3));
634 ss.append(template.substring(i, i1)).append(value1);
639 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
640 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
642 if (format == Format.JSON) {
643 req = XmlJsonUtil.removeLastCommaJson(req);
646 long t2 = System.currentTimeMillis();
647 log.info("Building {} completed. Time: {}", format, t2 - t1);
652 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
653 StringBuilder newTemplate = new StringBuilder();
655 while (k < template.length()) {
656 int i1 = template.indexOf("${repeat:", k);
658 newTemplate.append(template.substring(k));
662 int i2 = template.indexOf(':', i1 + 9);
664 throw new SvcLogicException(
665 "Template error: Context variable name followed by : is required after repeat");
668 // Find the closing }, store in i3
672 while (nn > 0 && i < template.length()) {
673 i3 = template.indexOf('}', i);
675 throw new SvcLogicException("Template error: Matching } not found");
677 int i32 = template.indexOf('{', i);
678 if (i32 >= 0 && i32 < i3) {
687 String var1 = template.substring(i1 + 9, i2);
688 String value1 = ctx.getAttribute(var1);
689 log.info(" {}:{}", var1, value1);
692 n = Integer.parseInt(value1);
693 } catch (NumberFormatException e) {
694 log.info("value1 not set or not a number, n will remain set at zero");
697 newTemplate.append(template.substring(k, i1));
699 String rpt = template.substring(i2 + 1, i3);
701 for (int ii = 0; ii < n; ii++) {
702 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
703 if (ii == n - 1 && ss.trim().endsWith(",")) {
704 int i4 = ss.lastIndexOf(',');
706 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
709 newTemplate.append(ss);
716 return newTemplate.toString();
719 return expandRepeats(ctx, newTemplate.toString(), level + 1);
722 protected String readFile(String fileName) throws SvcLogicException {
724 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
725 return new String(encoded, "UTF-8");
726 } catch (IOException | SecurityException e) {
727 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
731 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
732 Parameters p = new Parameters();
733 p.restapiUser = fp.user;
734 p.restapiPassword = fp.password;
735 p.oAuthConsumerKey = fp.oAuthConsumerKey;
736 p.oAuthVersion = fp.oAuthVersion;
737 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
738 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
739 p.authtype = fp.authtype;
740 return addAuthType(c, p);
743 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
744 if (p.authtype == AuthType.Unspecified) {
745 if (p.restapiUser != null && p.restapiPassword != null) {
746 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
747 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
748 Feature oAuth1Feature =
749 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
750 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
751 client.register(oAuth1Feature);
755 if (p.authtype == AuthType.DIGEST) {
756 if (p.restapiUser != null && p.restapiPassword != null) {
757 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
759 throw new SvcLogicException(
760 "oAUTH authentication type selected but all restapiUser and restapiPassword "
761 + "parameters doesn't exist",
764 } else if (p.authtype == AuthType.BASIC) {
765 if (p.restapiUser != null && p.restapiPassword != null) {
766 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
768 throw new SvcLogicException(
769 "oAUTH authentication type selected but all restapiUser and restapiPassword "
770 + "parameters doesn't exist",
773 } else if (p.authtype == AuthType.OAUTH) {
774 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
775 Feature oAuth1Feature = OAuth1ClientSupport
776 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
777 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
778 client.register(oAuth1Feature);
780 throw new SvcLogicException(
781 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
782 + "and oAuthSignatureMethod parameters doesn't exist",
791 * Receives the http response for the http request sent.
793 * @param request request msg
794 * @param p parameters
795 * @return HTTP response
796 * @throws SvcLogicException when sending http request fails
798 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
800 ClientConfig config = new ClientConfig();
801 if(!StringUtils.isEmpty(p.proxyUrl)) {
803 URL proxyUrl = new URL(p.proxyUrl);
804 HttpUrlConnectorProvider cp = new HttpUrlConnectorProvider();
805 config.connectorProvider(cp);
807 new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()));
809 cp.connectionFactory(new ConnectionFactory() {
811 public HttpURLConnection getConnection(URL url) throws IOException {
812 return (HttpURLConnection) url.openConnection(proxy);
815 } catch (MalformedURLException e) {
816 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
820 SSLContext ssl = null;
821 if (p.ssl && p.restapiUrl.startsWith("https")) {
822 ssl = createSSLContext(p);
825 ClientBuilder builder =
826 ClientBuilder.newBuilder().hostnameVerifier(new AcceptIpAddressHostNameVerifier());
829 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
830 builder = builder.sslContext(ssl);
832 if (config != null) {
833 builder = builder.withConfig(config);
836 Client client = builder.build();
838 setClientTimeouts(client);
839 // Needed to support additional HTTP methods such as PATCH
840 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
841 client.register(new MetricLogClientFilter());
842 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
844 long t1 = System.currentTimeMillis();
846 HttpResponse r = new HttpResponse();
848 String accept = p.accept;
849 if (accept == null) {
850 accept = p.format == Format.XML ? "application/xml" : "application/json";
853 String contentType = p.contentType;
854 if (contentType == null) {
855 contentType = accept + ";charset=UTF-8";
858 if (!p.skipSending && !p.multipartFormData) {
859 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
861 if (p.format == Format.NONE) {
862 invocationBuilder.header("", "");
865 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
866 String[] keyValuePairs = p.customHttpHeaders.split(",");
867 for (String singlePair : keyValuePairs) {
868 int equalPosition = singlePair.indexOf('=');
869 invocationBuilder.header(singlePair.substring(0, equalPosition),
870 singlePair.substring(equalPosition + 1, singlePair.length()));
874 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
879 // When the HTTP operation has no body do not set the content-type
880 //setting content-type has caused errors with some servers when no body is present
881 if (request == null) {
882 response = invocationBuilder.method(p.httpMethod.toString());
885 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
887 } catch (ProcessingException | IllegalStateException e) {
888 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
891 r.code = response.getStatus();
892 r.headers = response.getStringHeaders();
893 EntityTag etag = response.getEntityTag();
895 r.message = etag.getValue();
897 if (response.hasEntity() && r.code != 204) {
898 r.body = response.readEntity(String.class);
900 } else if (!p.skipSending && p.multipartFormData) {
901 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
903 MultiPart multiPart = new MultiPart();
904 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
906 FileDataBodyPart fileDataBodyPart =
907 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
908 multiPart.bodyPart(fileDataBodyPart);
911 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
913 if (p.format == Format.NONE) {
914 invocationBuilder.header("", "");
917 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
918 String[] keyValuePairs = p.customHttpHeaders.split(",");
919 for (String singlePair : keyValuePairs) {
920 int equalPosition = singlePair.indexOf('=');
921 invocationBuilder.header(singlePair.substring(0, equalPosition),
922 singlePair.substring(equalPosition + 1, singlePair.length()));
930 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
931 } catch (ProcessingException | IllegalStateException e) {
932 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
935 r.code = response.getStatus();
936 r.headers = response.getStringHeaders();
937 EntityTag etag = response.getEntityTag();
939 r.message = etag.getValue();
941 if (response.hasEntity() && r.code != 204) {
942 r.body = response.readEntity(String.class);
947 long t2 = System.currentTimeMillis();
948 log.info(responseReceivedMessage, t2 - t1);
949 log.info(responseHttpCodeMessage, r.code);
950 log.info("HTTP response message: {}", r.message);
951 logHeaders(r.headers);
952 log.info("HTTP response: {}", r.body);
957 protected SSLContext createSSLContext(Parameters p) {
958 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
959 HttpsURLConnection.setDefaultHostnameVerifier(new AcceptIpAddressHostNameVerifier(p.disableHostVerification));
960 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
961 KeyStore ks = KeyStore.getInstance("PKCS12");
962 char[] pwd = p.keyStorePassword.toCharArray();
965 SSLContext ctx = SSLContext.getInstance("TLS");
966 ctx.init(kmf.getKeyManagers(), null, null);
968 } catch (Exception e) {
969 log.error("Error creating SSLContext: {}", e.getMessage(), e);
974 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
977 resp.message = errorMessage;
978 String pp = prefix != null ? prefix + '.' : "";
979 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
980 ctx.setAttribute(pp + "response-message", resp.message);
983 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
984 String pp = prefix != null ? prefix + '.' : "";
985 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
986 ctx.setAttribute(pp + "response-message", r.message);
989 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
990 HttpResponse r = null;
992 FileParam p = getFileParameters(paramMap);
993 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
995 r = sendHttpData(data, p);
997 for (int i = 0; i < 10 && r.code == 301; i++) {
998 String newUrl = r.headers2.get("Location").get(0);
1000 log.info("Got response code 301. Sending same request to URL: " + newUrl);
1003 r = sendHttpData(data, p);
1006 setResponseStatus(ctx, p.responsePrefix, r);
1008 } catch (SvcLogicException | IOException e) {
1009 log.error("Error sending the request: {}", e.getMessage(), e);
1011 r = new HttpResponse();
1013 r.message = e.getMessage();
1014 String prefix = parseParam(paramMap, responsePrefix, false, null);
1015 setResponseStatus(ctx, prefix, r);
1018 if (r != null && r.code >= 300) {
1019 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1023 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
1024 FileParam p = new FileParam();
1025 p.fileName = parseParam(paramMap, "fileName", true, null);
1026 p.url = parseParam(paramMap, "url", true, null);
1027 p.user = parseParam(paramMap, "user", false, null);
1028 p.password = parseParam(paramMap, "password", false, null);
1029 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1030 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1031 String skipSendingStr = paramMap.get(skipSendingMessage);
1032 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1033 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1034 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1035 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1036 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1037 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1041 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1044 UebParam p = getUebParameters(paramMap);
1046 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1050 if (p.templateFileName == null) {
1051 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1052 p.templateFileName = defaultUebTemplateFileName;
1055 String reqTemplate = readFile(p.templateFileName);
1056 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1057 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1059 r = postOnUeb(req, p);
1060 setResponseStatus(ctx, p.responsePrefix, r);
1061 if (r.body != null) {
1062 ctx.setAttribute(pp + "httpResponse", r.body);
1065 } catch (SvcLogicException e) {
1066 log.error("Error sending the request: {}", e.getMessage(), e);
1068 r = new HttpResponse();
1070 r.message = e.getMessage();
1071 String prefix = parseParam(paramMap, responsePrefix, false, null);
1072 setResponseStatus(ctx, prefix, r);
1075 if (r.code >= 300) {
1076 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1080 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1081 URL url = new URL(p.url);
1082 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1084 log.info("Connection: " + con.getClass().getName());
1086 con.setRequestMethod(p.httpMethod.toString());
1087 con.setRequestProperty("Content-Type", "application/octet-stream");
1088 con.setRequestProperty("Accept", "*/*");
1089 con.setRequestProperty("Expect", "100-continue");
1090 con.setFixedLengthStreamingMode(data.length);
1091 con.setInstanceFollowRedirects(false);
1093 if (p.user != null && p.password != null) {
1094 String authString = p.user + ":" + p.password;
1095 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1096 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1099 con.setDoInput(true);
1100 con.setDoOutput(true);
1102 log.info("Sending file");
1103 long t1 = System.currentTimeMillis();
1105 HttpResponse r = new HttpResponse();
1108 if (!p.skipSending) {
1109 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1110 util.logBefore(con, ONAPComponents.DMAAP);
1114 boolean continue100failed = false;
1116 OutputStream os = con.getOutputStream();
1120 } catch (ProtocolException e) {
1121 continue100failed = true;
1124 r.code = con.getResponseCode();
1125 r.headers2 = con.getHeaderFields();
1127 if (r.code != 204 && !continue100failed) {
1128 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1130 StringBuffer response = new StringBuffer();
1131 while ((inputLine = in.readLine()) != null) {
1132 response.append(inputLine);
1136 r.body = response.toString();
1144 long t2 = System.currentTimeMillis();
1145 log.info("Response received. Time: {}", t2 - t1);
1146 log.info("HTTP response code: {}", r.code);
1147 log.info("HTTP response message: {}", r.message);
1148 logHeaders(r.headers2);
1149 log.info("HTTP response: {}", r.body);
1154 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1155 UebParam p = new UebParam();
1156 p.topic = parseParam(paramMap, "topic", true, null);
1157 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1158 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1159 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1160 String skipSendingStr = paramMap.get(skipSendingMessage);
1161 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1165 protected void logProperties(Map<String, Object> mm) {
1166 List<String> ll = new ArrayList<>();
1167 for (Object o : mm.keySet()) {
1170 Collections.sort(ll);
1172 log.info("Properties:");
1173 for (String name : ll) {
1174 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1178 protected void logHeaders(MultivaluedMap<String, String> mm) {
1179 log.info("HTTP response headers:");
1185 List<String> ll = new ArrayList<>();
1186 for (Object o : mm.keySet()) {
1189 Collections.sort(ll);
1191 for (String name : ll) {
1192 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1196 private void logHeaders(Map<String, List<String>> mm) {
1197 if (mm == null || mm.isEmpty()) {
1201 List<String> ll = new ArrayList<>();
1202 for (String s : mm.keySet()) {
1207 Collections.sort(ll);
1209 for (String name : ll) {
1210 List<String> v = mm.get(name);
1211 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1212 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1216 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1217 String[] urls = uebServers.split(" ");
1218 for (int i = 0; i < urls.length; i++) {
1219 if (!urls[i].endsWith("/")) {
1222 urls[i] += "events/" + p.topic;
1225 Client client = ClientBuilder.newBuilder().build();
1226 setClientTimeouts(client);
1227 WebTarget webTarget = client.target(urls[0]);
1229 log.info("UEB URL: {}", urls[0]);
1230 log.info("Sending request:");
1232 long t1 = System.currentTimeMillis();
1234 HttpResponse r = new HttpResponse();
1237 if (!p.skipSending) {
1238 String tt = "application/json";
1239 String tt1 = tt + ";charset=UTF-8";
1242 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1245 response = invocationBuilder.post(Entity.entity(request, tt1));
1246 } catch (ProcessingException e) {
1247 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1249 r.code = response.getStatus();
1250 r.headers = response.getStringHeaders();
1251 if (response.hasEntity()) {
1252 r.body = response.readEntity(String.class);
1256 long t2 = System.currentTimeMillis();
1257 log.info(responseReceivedMessage, t2 - t1);
1258 log.info(responseHttpCodeMessage, r.code);
1259 logHeaders(r.headers);
1260 log.info("HTTP response:\n {}", r.body);
1265 public void setUebServers(String uebServers) {
1266 this.uebServers = uebServers;
1269 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1270 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1273 protected void setClientTimeouts(Client client) {
1274 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1275 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1278 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1279 String stringValue = System.getProperty(propertyName);
1280 if (stringValue != null && stringValue.length() > 0) {
1282 return Integer.valueOf(stringValue);
1283 } catch (NumberFormatException e) {
1284 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1287 return defaultValue;
1290 protected static String[] getMultipleUrls(String restapiUrl) {
1291 List<String> urls = new ArrayList<>();
1293 for (int i = 0; i < restapiUrl.length(); i++) {
1294 if (restapiUrl.charAt(i) == ',') {
1295 if (i + 9 < restapiUrl.length()) {
1296 String part = restapiUrl.substring(i + 1, i + 9);
1297 if (part.equals("https://") || part.startsWith("http://")) {
1298 urls.add(restapiUrl.substring(start, i));
1302 } else if (i == restapiUrl.length() - 1) {
1303 urls.add(restapiUrl.substring(start, i + 1));
1306 String[] arr = new String[urls.size()];
1307 return urls.toArray(arr);
1310 protected static boolean containsMultipleUrls(String restapiUrl) {
1311 Matcher m = retryPattern.matcher(restapiUrl);
1315 private static class FileParam {
1317 public String fileName;
1320 public String password;
1321 public HttpMethod httpMethod;
1322 public String responsePrefix;
1323 public boolean skipSending;
1324 public String oAuthConsumerKey;
1325 public String oAuthConsumerSecret;
1326 public String oAuthSignatureMethod;
1327 public String oAuthVersion;
1328 public AuthType authtype;
1331 private static class UebParam {
1333 public String topic;
1334 public String templateFileName;
1335 public String rootVarName;
1336 public String responsePrefix;
1337 public boolean skipSending;