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 javax.net.ssl.HttpsURLConnection;
54 import javax.net.ssl.KeyManagerFactory;
55 import javax.net.ssl.SSLContext;
56 import javax.ws.rs.ProcessingException;
57 import javax.ws.rs.client.Client;
58 import javax.ws.rs.client.ClientBuilder;
59 import javax.ws.rs.client.Entity;
60 import javax.ws.rs.client.Invocation;
61 import javax.ws.rs.client.WebTarget;
62 import javax.ws.rs.core.EntityTag;
63 import javax.ws.rs.core.Feature;
64 import javax.ws.rs.core.MediaType;
65 import javax.ws.rs.core.MultivaluedMap;
66 import javax.ws.rs.core.Response;
67 import javax.ws.rs.core.UriBuilder;
68 import org.apache.commons.lang3.StringUtils;
69 import org.codehaus.jettison.json.JSONException;
70 import org.codehaus.jettison.json.JSONObject;
71 import org.glassfish.jersey.client.ClientProperties;
72 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
73 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
74 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
75 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
76 import org.glassfish.jersey.media.multipart.MultiPart;
77 import org.glassfish.jersey.media.multipart.MultiPartFeature;
78 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
79 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
80 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
81 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
82 import org.onap.logging.filter.base.HttpURLConnectionMetricUtil;
83 import org.onap.logging.filter.base.MetricLogClientFilter;
84 import org.onap.logging.filter.base.ONAPComponents;
85 import org.onap.logging.ref.slf4j.ONAPLogConstants;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
90 public class RestapiCallNode implements SvcLogicJavaPlugin {
92 protected static final String PARTNERS_FILE_NAME = "partners.json";
93 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
94 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
95 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
96 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
97 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
99 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
100 private String uebServers;
101 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
103 private String responseReceivedMessage = "Response received. Time: {}";
104 private String responseHttpCodeMessage = "HTTP response code: {}";
105 private String requestPostingException = "Exception while posting http request to client ";
106 protected static final String skipSendingMessage = "skipSending";
107 protected static final String responsePrefix = "responsePrefix";
108 protected static final String restapiUrlString = "restapiUrl";
109 protected static final String restapiUserKey = "restapiUser";
110 protected static final String restapiPasswordKey = "restapiPassword";
111 protected Integer httpConnectTimeout;
112 protected Integer httpReadTimeout;
114 protected HashMap<String, PartnerDetails> partnerStore;
116 public RestapiCallNode() {
117 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
119 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
120 JSONObject partners = new JSONObject(jsonString);
121 partnerStore = new HashMap<>();
122 loadPartners(partners);
123 log.info("Partners support enabled");
124 } catch (Exception e) {
125 log.warn("Partners file could not be read, Partner support will not be enabled.", e);
128 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
129 Properties props = new Properties();
131 uebServers = props.getProperty("servers");
132 log.info("UEB support enabled");
133 } catch (Exception e) {
134 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
136 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
137 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
140 @SuppressWarnings("unchecked")
141 protected void loadPartners(JSONObject partners) {
142 Iterator<String> keys = partners.keys();
143 String partnerUserKey = "user";
144 String partnerPasswordKey = "password";
145 String partnerUrlKey = "url";
147 while (keys.hasNext()) {
148 String partnerKey = keys.next();
150 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
151 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
153 if (partnerObject.has(partnerUrlKey)) {
154 url = partnerObject.getString(partnerUrlKey);
156 String userName = partnerObject.getString(partnerUserKey);
157 String password = partnerObject.getString(partnerPasswordKey);
158 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
159 partnerStore.put(partnerKey, details);
160 log.info("mapped partner using partner key " + partnerKey);
162 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
164 } catch (JSONException e) {
165 log.info("Couldn't map the partner using partner key " + partnerKey, e);
170 /* Unobfuscate param value */
171 private static String getObfuscatedVal(String paramValue) {
172 String resValue = paramValue;
173 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
175 String paramStr = paramValue.substring(2, paramValue.length()-1);
176 if (paramStr != null && paramStr.length() > 0)
178 String val = System.getenv(paramStr);
179 if (val != null && val.length() > 0)
182 log.info("Obfuscated value RESET for param value:" + paramValue);
190 * Returns parameters from the parameter map.
192 * @param paramMap parameter map
193 * @param p parameters instance
194 * @return parameters filed instance
195 * @throws SvcLogicException when svc logic exception occurs
197 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
199 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
200 p.requestBody = parseParam(paramMap, "requestBody", false, null);
201 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
202 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
203 if (p.restapiUrlSuffix != null) {
204 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
207 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
208 validateUrl(p.restapiUrl);
210 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
211 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
212 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
213 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
214 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
215 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
216 p.contentType = parseParam(paramMap, "contentType", false, null);
217 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
218 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
219 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
220 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
221 p.listNameList = getListNameList(paramMap);
222 String skipSendingStr = paramMap.get(skipSendingMessage);
223 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
224 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
225 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
226 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
227 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
228 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
229 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
230 && p.keyStorePassword != null;
231 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
232 p.partner = parseParam(paramMap, "partner", false, null);
233 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
234 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
235 p.accept = parseParam(paramMap, "accept", false, null);
236 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
237 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
238 p.targetEntity = parseParam(paramMap, "targetEntity", false, null);
243 * Validates the given URL in the parameters.
245 * @param restapiUrl rest api URL
246 * @throws SvcLogicException when URL validation fails
248 private static void validateUrl(String restapiUrl) throws SvcLogicException {
249 if (restapiUrl.contains(",")) {
250 String[] urls = restapiUrl.split(",");
251 for (String url : urls) {
256 URI.create(restapiUrl);
257 } catch (IllegalArgumentException e) {
258 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
264 * Returns the list of list name.
266 * @param paramMap parameters map
267 * @return list of list name
269 private static Set<String> getListNameList(Map<String, String> paramMap) {
270 Set<String> ll = new HashSet<>();
271 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
272 if (entry.getKey().startsWith("listName")) {
273 ll.add(entry.getValue());
280 * Parses the parameter string map of property, validates if required, assigns default value if
281 * present and returns the value.
283 * @param paramMap string param map
284 * @param name name of the property
285 * @param required if value required
286 * @param def default value
287 * @return value of the property
288 * @throws SvcLogicException if required parameter value is empty
290 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
291 throws SvcLogicException {
292 String s = paramMap.get(name);
294 if (s == null || s.trim().length() == 0) {
298 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
302 StringBuilder value = new StringBuilder();
304 int i1 = s.indexOf('%');
306 int i2 = s.indexOf('%', i1 + 1);
311 String varName = s.substring(i1 + 1, i2);
312 String varValue = System.getenv(varName);
313 if (varValue == null) {
314 varValue = "%" + varName + "%";
317 value.append(s.substring(i, i1));
318 value.append(varValue);
321 i1 = s.indexOf('%', i);
323 value.append(s.substring(i));
325 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
327 return value.toString();
330 private static Object maskPassword(String name, Object value) {
331 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
332 for (String pwdName : pwdNames) {
333 if (name.contains(pwdName)) {
341 * Allows Directed Graphs the ability to interact with REST APIs.
343 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
347 * <th>Mandatory/Optional</th>
348 * <th>description</th>
349 * <th>example values</th></thead> <tbody>
351 * <td>templateFileName</td>
353 * <td>full path to template file that can be used to build a request</td>
354 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
357 * <td>restapiUrl</td>
359 * <td>url to send the request to</td>
360 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
363 * <td>restapiUser</td>
365 * <td>user name to use for http basic authentication</td>
369 * <td>restapiPassword</td>
371 * <td>unencrypted password to use for http basic authentication</td>
372 * <td>plain_password</td>
375 * <td>oAuthConsumerKey</td>
377 * <td>Consumer key to use for http oAuth authentication</td>
381 * <td>oAuthConsumerSecret</td>
383 * <td>Consumer secret to use for http oAuth authentication</td>
384 * <td>plain_secret</td>
387 * <td>oAuthSignatureMethod</td>
389 * <td>Consumer method to use for http oAuth authentication</td>
393 * <td>oAuthVersion</td>
395 * <td>Version http oAuth authentication</td>
399 * <td>contentType</td>
401 * <td>http content type to set in the http header</td>
402 * <td>usually application/json or application/xml</td>
407 * <td>should match request body format</td>
408 * <td>json or xml</td>
411 * <td>httpMethod</td>
413 * <td>http method to use when sending the request</td>
414 * <td>get post put delete patch</td>
417 * <td>responsePrefix</td>
419 * <td>location the response will be written to in context memory</td>
420 * <td>tmp.restapi.result</td>
423 * <td>listName[i]</td>
425 * <td>Used for processing XML responses with repeating
426 * elements.</td>vpn-information.vrf-details
430 * <td>skipSending</td>
433 * <td>true or false</td>
436 * <td>convertResponse</td>
438 * <td>whether the response should be converted</td>
439 * <td>true or false</td>
442 * <td>customHttpHeaders</td>
444 * <td>a list additional http headers to be passed in, follow the format in the example</td>
445 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
448 * <td>dumpHeaders</td>
450 * <td>when true writes http header content to context memory</td>
451 * <td>true or false</td>
456 * <td>used to retrieve username, password and url if partner store exists</td>
460 * <td>returnRequestPayload</td>
462 * <td>used to return payload built in the request</td>
463 * <td>true or false</td>
467 * @param ctx Reference to context memory
468 * @throws SvcLogicException
470 * @see String#split(String, int)
472 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
473 sendRequest(paramMap, ctx, null);
476 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
477 throws SvcLogicException {
479 HttpResponse r = new HttpResponse();
481 handlePartner(paramMap);
482 Parameters p = getParameters(paramMap, new Parameters());
483 if(p.targetEntity != null && !p.targetEntity.isEmpty()) {
484 MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, p.targetEntity);
486 if (p.restapiUrl.contains(",") && retryPolicy == null) {
487 String[] urls = p.restapiUrl.split(",");
488 retryPolicy = new RetryPolicy(urls, urls.length * 2);
489 p.restapiUrl = urls[0];
491 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
494 if (p.templateFileName != null) {
495 String reqTemplate = readFile(p.templateFileName);
496 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
497 } else if (p.requestBody != null) {
500 r = sendHttpRequest(req, p);
501 setResponseStatus(ctx, p.responsePrefix, r);
503 if (p.dumpHeaders && r.headers != null) {
504 for (Entry<String, List<String>> a : r.headers.entrySet()) {
505 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
509 if (p.returnRequestPayload && req != null) {
510 ctx.setAttribute(pp + "httpRequest", req);
513 if (r.body != null && r.body.trim().length() > 0) {
514 ctx.setAttribute(pp + "httpResponse", r.body);
516 if (p.convertResponse) {
517 Map<String, String> mm = null;
518 if (p.format == Format.XML) {
519 mm = XmlParser.convertToProperties(r.body, p.listNameList);
520 } else if (p.format == Format.JSON) {
521 mm = JsonParser.convertToProperties(r.body);
525 for (Map.Entry<String, String> entry : mm.entrySet()) {
526 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
531 } catch (SvcLogicException e) {
532 boolean shouldRetry = false;
533 if (e.getCause().getCause() instanceof SocketException) {
537 log.error("Error sending the request: " + e.getMessage(), e);
538 String prefix = parseParam(paramMap, responsePrefix, false, null);
539 if (retryPolicy == null || !shouldRetry) {
540 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
542 log.debug(retryPolicy.getRetryMessage());
544 // calling getNextHostName increments the retry count so it should be called before shouldRetry
545 String retryString = retryPolicy.getNextHostName();
546 if (retryPolicy.shouldRetry()) {
547 paramMap.put(restapiUrlString, retryString);
548 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
550 sendRequest(paramMap, ctx, retryPolicy);
552 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
553 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
555 } catch (Exception ex) {
556 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
557 + "has failed with error message " + ex.getMessage();
558 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
563 if (r != null && r.code >= 300) {
564 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
568 protected void handlePartner(Map<String, String> paramMap) {
569 String partner = paramMap.get("partner");
570 if (partner != null && partner.length() > 0) {
571 PartnerDetails details = partnerStore.get(partner);
572 paramMap.put(restapiUserKey, details.username);
573 paramMap.put(restapiPasswordKey, details.password);
574 if (paramMap.get(restapiUrlString) == null) {
575 paramMap.put(restapiUrlString, details.url);
580 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
581 log.info("Building {} started", format);
582 long t1 = System.currentTimeMillis();
583 String originalTemplate = template;
585 template = expandRepeats(ctx, template, 1);
587 Map<String, String> mm = new HashMap<>();
588 for (String s : ctx.getAttributeKeySet()) {
589 mm.put(s, ctx.getAttribute(s));
592 StringBuilder ss = new StringBuilder();
594 while (i < template.length()) {
595 int i1 = template.indexOf("${", i);
597 ss.append(template.substring(i));
601 int i2 = template.indexOf('}', i1 + 2);
603 throw new SvcLogicException("Template error: Matching } not found");
606 String var1 = template.substring(i1 + 2, i2);
607 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
608 if (value1 == null || value1.trim().length() == 0) {
609 // delete the whole element (line)
610 int i3 = template.lastIndexOf('\n', i1);
614 int i4 = template.indexOf('\n', i1);
616 i4 = template.length();
620 ss.append(template.substring(i, i3));
624 ss.append(template.substring(i, i1)).append(value1);
629 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
630 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
632 if (format == Format.JSON) {
633 req = XmlJsonUtil.removeLastCommaJson(req);
636 long t2 = System.currentTimeMillis();
637 log.info("Building {} completed. Time: {}", format, t2 - t1);
642 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
643 StringBuilder newTemplate = new StringBuilder();
645 while (k < template.length()) {
646 int i1 = template.indexOf("${repeat:", k);
648 newTemplate.append(template.substring(k));
652 int i2 = template.indexOf(':', i1 + 9);
654 throw new SvcLogicException(
655 "Template error: Context variable name followed by : is required after repeat");
658 // Find the closing }, store in i3
662 while (nn > 0 && i < template.length()) {
663 i3 = template.indexOf('}', i);
665 throw new SvcLogicException("Template error: Matching } not found");
667 int i32 = template.indexOf('{', i);
668 if (i32 >= 0 && i32 < i3) {
677 String var1 = template.substring(i1 + 9, i2);
678 String value1 = ctx.getAttribute(var1);
679 log.info(" {}:{}", var1, value1);
682 n = Integer.parseInt(value1);
683 } catch (NumberFormatException e) {
684 log.info("value1 not set or not a number, n will remain set at zero");
687 newTemplate.append(template.substring(k, i1));
689 String rpt = template.substring(i2 + 1, i3);
691 for (int ii = 0; ii < n; ii++) {
692 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
693 if (ii == n - 1 && ss.trim().endsWith(",")) {
694 int i4 = ss.lastIndexOf(',');
696 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
699 newTemplate.append(ss);
706 return newTemplate.toString();
709 return expandRepeats(ctx, newTemplate.toString(), level + 1);
712 protected String readFile(String fileName) throws SvcLogicException {
714 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
715 return new String(encoded, "UTF-8");
716 } catch (IOException | SecurityException e) {
717 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
721 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
722 Parameters p = new Parameters();
723 p.restapiUser = fp.user;
724 p.restapiPassword = fp.password;
725 p.oAuthConsumerKey = fp.oAuthConsumerKey;
726 p.oAuthVersion = fp.oAuthVersion;
727 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
728 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
729 p.authtype = fp.authtype;
730 return addAuthType(c, p);
733 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
734 if (p.authtype == AuthType.Unspecified) {
735 if (p.restapiUser != null && p.restapiPassword != null) {
736 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
737 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
738 Feature oAuth1Feature =
739 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
740 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
741 client.register(oAuth1Feature);
745 if (p.authtype == AuthType.DIGEST) {
746 if (p.restapiUser != null && p.restapiPassword != null) {
747 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
749 throw new SvcLogicException(
750 "oAUTH authentication type selected but all restapiUser and restapiPassword "
751 + "parameters doesn't exist",
754 } else if (p.authtype == AuthType.BASIC) {
755 if (p.restapiUser != null && p.restapiPassword != null) {
756 client.register(HttpAuthenticationFeature.basic(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.OAUTH) {
764 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
765 Feature oAuth1Feature = OAuth1ClientSupport
766 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
767 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
768 client.register(oAuth1Feature);
770 throw new SvcLogicException(
771 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
772 + "and oAuthSignatureMethod parameters doesn't exist",
781 * Receives the http response for the http request sent.
783 * @param request request msg
784 * @param p parameters
785 * @return HTTP response
786 * @throws SvcLogicException when sending http request fails
788 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
790 SSLContext ssl = null;
791 if (p.ssl && p.restapiUrl.startsWith("https")) {
792 ssl = createSSLContext(p);
797 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
798 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
800 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
802 setClientTimeouts(client);
803 // Needed to support additional HTTP methods such as PATCH
804 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
805 client.register(new MetricLogClientFilter());
806 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
808 long t1 = System.currentTimeMillis();
810 HttpResponse r = new HttpResponse();
812 String accept = p.accept;
813 if (accept == null) {
814 accept = p.format == Format.XML ? "application/xml" : "application/json";
817 String contentType = p.contentType;
818 if (contentType == null) {
819 contentType = accept + ";charset=UTF-8";
822 if (!p.skipSending && !p.multipartFormData) {
824 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
826 if (p.format == Format.NONE) {
827 invocationBuilder.header("", "");
830 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
831 String[] keyValuePairs = p.customHttpHeaders.split(",");
832 for (String singlePair : keyValuePairs) {
833 int equalPosition = singlePair.indexOf('=');
834 invocationBuilder.header(singlePair.substring(0, equalPosition),
835 singlePair.substring(equalPosition + 1, singlePair.length()));
839 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
844 // When the HTTP operation has no body do not set the content-type
845 //setting content-type has caused errors with some servers when no body is present
846 if (request == null) {
847 response = invocationBuilder.method(p.httpMethod.toString());
849 log.info("Sending request below to url " + p.restapiUrl);
851 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
853 } catch (ProcessingException | IllegalStateException e) {
854 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
857 r.code = response.getStatus();
858 r.headers = response.getStringHeaders();
859 EntityTag etag = response.getEntityTag();
861 r.message = etag.getValue();
863 if (response.hasEntity() && r.code != 204) {
864 r.body = response.readEntity(String.class);
866 } else if (!p.skipSending && p.multipartFormData) {
868 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
870 MultiPart multiPart = new MultiPart();
871 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
873 FileDataBodyPart fileDataBodyPart =
874 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
875 multiPart.bodyPart(fileDataBodyPart);
878 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
880 if (p.format == Format.NONE) {
881 invocationBuilder.header("", "");
884 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
885 String[] keyValuePairs = p.customHttpHeaders.split(",");
886 for (String singlePair : keyValuePairs) {
887 int equalPosition = singlePair.indexOf('=');
888 invocationBuilder.header(singlePair.substring(0, equalPosition),
889 singlePair.substring(equalPosition + 1, singlePair.length()));
897 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
898 } catch (ProcessingException | IllegalStateException e) {
899 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
902 r.code = response.getStatus();
903 r.headers = response.getStringHeaders();
904 EntityTag etag = response.getEntityTag();
906 r.message = etag.getValue();
908 if (response.hasEntity() && r.code != 204) {
909 r.body = response.readEntity(String.class);
914 long t2 = System.currentTimeMillis();
915 log.info(responseReceivedMessage, t2 - t1);
916 log.info(responseHttpCodeMessage, r.code);
917 log.info("HTTP response message: {}", r.message);
918 logHeaders(r.headers);
919 log.info("HTTP response: {}", r.body);
924 protected SSLContext createSSLContext(Parameters p) {
925 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
926 System.setProperty("jsse.enableSNIExtension", "false");
927 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
928 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
930 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
932 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
933 KeyStore ks = KeyStore.getInstance("PKCS12");
934 char[] pwd = p.keyStorePassword.toCharArray();
938 SSLContext ctx = SSLContext.getInstance("TLS");
939 ctx.init(kmf.getKeyManagers(), null, null);
941 } catch (Exception e) {
942 log.error("Error creating SSLContext: {}", e.getMessage(), e);
947 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
950 resp.message = errorMessage;
951 String pp = prefix != null ? prefix + '.' : "";
952 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
953 ctx.setAttribute(pp + "response-message", resp.message);
956 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
957 String pp = prefix != null ? prefix + '.' : "";
958 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
959 ctx.setAttribute(pp + "response-message", r.message);
962 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
963 HttpResponse r = null;
965 FileParam p = getFileParameters(paramMap);
966 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
968 r = sendHttpData(data, p);
970 for (int i = 0; i < 10 && r.code == 301; i++) {
971 String newUrl = r.headers2.get("Location").get(0);
973 log.info("Got response code 301. Sending same request to URL: " + newUrl);
976 r = sendHttpData(data, p);
979 setResponseStatus(ctx, p.responsePrefix, r);
981 } catch (SvcLogicException | IOException e) {
982 log.error("Error sending the request: {}", e.getMessage(), e);
984 r = new HttpResponse();
986 r.message = e.getMessage();
987 String prefix = parseParam(paramMap, responsePrefix, false, null);
988 setResponseStatus(ctx, prefix, r);
991 if (r != null && r.code >= 300) {
992 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
996 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
997 FileParam p = new FileParam();
998 p.fileName = parseParam(paramMap, "fileName", true, null);
999 p.url = parseParam(paramMap, "url", true, null);
1000 p.user = parseParam(paramMap, "user", false, null);
1001 p.password = parseParam(paramMap, "password", false, null);
1002 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
1003 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1004 String skipSendingStr = paramMap.get(skipSendingMessage);
1005 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1006 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
1007 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
1008 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
1009 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
1010 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
1014 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
1017 UebParam p = getUebParameters(paramMap);
1019 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
1023 if (p.templateFileName == null) {
1024 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
1025 p.templateFileName = defaultUebTemplateFileName;
1028 String reqTemplate = readFile(p.templateFileName);
1029 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1030 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1032 r = postOnUeb(req, p);
1033 setResponseStatus(ctx, p.responsePrefix, r);
1034 if (r.body != null) {
1035 ctx.setAttribute(pp + "httpResponse", r.body);
1038 } catch (SvcLogicException e) {
1039 log.error("Error sending the request: {}", e.getMessage(), e);
1041 r = new HttpResponse();
1043 r.message = e.getMessage();
1044 String prefix = parseParam(paramMap, responsePrefix, false, null);
1045 setResponseStatus(ctx, prefix, r);
1048 if (r.code >= 300) {
1049 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1053 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws IOException {
1054 URL url = new URL(p.url);
1055 HttpURLConnection con = (HttpURLConnection) url.openConnection();
1057 log.info("Connection: " + con.getClass().getName());
1059 con.setRequestMethod(p.httpMethod.toString());
1060 con.setRequestProperty("Content-Type", "application/octet-stream");
1061 con.setRequestProperty("Accept", "*/*");
1062 con.setRequestProperty("Expect", "100-continue");
1063 con.setFixedLengthStreamingMode(data.length);
1064 con.setInstanceFollowRedirects(false);
1066 if (p.user != null && p.password != null) {
1067 String authString = p.user + ":" + p.password;
1068 String authStringEnc = Base64.getEncoder().encodeToString(authString.getBytes());
1069 con.setRequestProperty("Authorization", "Basic " + authStringEnc);
1072 con.setDoInput(true);
1073 con.setDoOutput(true);
1075 log.info("Sending file");
1076 long t1 = System.currentTimeMillis();
1078 HttpResponse r = new HttpResponse();
1081 if (!p.skipSending) {
1082 HttpURLConnectionMetricUtil util = new HttpURLConnectionMetricUtil();
1083 util.logBefore(con, ONAPComponents.DMAAP);
1087 boolean continue100failed = false;
1089 OutputStream os = con.getOutputStream();
1093 } catch (ProtocolException e) {
1094 continue100failed = true;
1097 r.code = con.getResponseCode();
1098 r.headers2 = con.getHeaderFields();
1100 if (r.code != 204 && !continue100failed) {
1101 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
1103 StringBuffer response = new StringBuffer();
1104 while ((inputLine = in.readLine()) != null) {
1105 response.append(inputLine);
1109 r.body = response.toString();
1117 long t2 = System.currentTimeMillis();
1118 log.info("Response received. Time: {}", t2 - t1);
1119 log.info("HTTP response code: {}", r.code);
1120 log.info("HTTP response message: {}", r.message);
1121 logHeaders(r.headers2);
1122 log.info("HTTP response: {}", r.body);
1127 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1128 UebParam p = new UebParam();
1129 p.topic = parseParam(paramMap, "topic", true, null);
1130 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1131 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1132 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1133 String skipSendingStr = paramMap.get(skipSendingMessage);
1134 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1138 protected void logProperties(Map<String, Object> mm) {
1139 List<String> ll = new ArrayList<>();
1140 for (Object o : mm.keySet()) {
1143 Collections.sort(ll);
1145 log.info("Properties:");
1146 for (String name : ll) {
1147 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1151 protected void logHeaders(MultivaluedMap<String, String> mm) {
1152 log.info("HTTP response headers:");
1158 List<String> ll = new ArrayList<>();
1159 for (Object o : mm.keySet()) {
1162 Collections.sort(ll);
1164 for (String name : ll) {
1165 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1169 private void logHeaders(Map<String, List<String>> mm) {
1170 if (mm == null || mm.isEmpty()) {
1174 List<String> ll = new ArrayList<>();
1175 for (String s : mm.keySet()) {
1180 Collections.sort(ll);
1182 for (String name : ll) {
1183 List<String> v = mm.get(name);
1184 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1185 log.info("--- " + name + ": " + (v.size() == 1 ? v.get(0) : v));
1189 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1190 String[] urls = uebServers.split(" ");
1191 for (int i = 0; i < urls.length; i++) {
1192 if (!urls[i].endsWith("/")) {
1195 urls[i] += "events/" + p.topic;
1198 Client client = ClientBuilder.newBuilder().build();
1199 setClientTimeouts(client);
1200 WebTarget webTarget = client.target(urls[0]);
1202 log.info("UEB URL: {}", urls[0]);
1203 log.info("Sending request:");
1205 long t1 = System.currentTimeMillis();
1207 HttpResponse r = new HttpResponse();
1210 if (!p.skipSending) {
1211 String tt = "application/json";
1212 String tt1 = tt + ";charset=UTF-8";
1215 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1218 response = invocationBuilder.post(Entity.entity(request, tt1));
1219 } catch (ProcessingException e) {
1220 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1222 r.code = response.getStatus();
1223 r.headers = response.getStringHeaders();
1224 if (response.hasEntity()) {
1225 r.body = response.readEntity(String.class);
1229 long t2 = System.currentTimeMillis();
1230 log.info(responseReceivedMessage, t2 - t1);
1231 log.info(responseHttpCodeMessage, r.code);
1232 logHeaders(r.headers);
1233 log.info("HTTP response:\n {}", r.body);
1238 public void setUebServers(String uebServers) {
1239 this.uebServers = uebServers;
1242 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1243 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1246 protected void setClientTimeouts(Client client) {
1247 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1248 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1251 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1252 String stringValue = System.getProperty(propertyName);
1253 if (stringValue != null && stringValue.length() > 0) {
1255 return Integer.valueOf(stringValue);
1256 } catch (NumberFormatException e) {
1257 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1260 return defaultValue;
1264 private static class FileParam {
1266 public String fileName;
1269 public String password;
1270 public HttpMethod httpMethod;
1271 public String responsePrefix;
1272 public boolean skipSending;
1273 public String oAuthConsumerKey;
1274 public String oAuthConsumerSecret;
1275 public String oAuthSignatureMethod;
1276 public String oAuthVersion;
1277 public AuthType authtype;
1280 private static class UebParam {
1282 public String topic;
1283 public String templateFileName;
1284 public String rootVarName;
1285 public String responsePrefix;
1286 public boolean skipSending;