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;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.net.SocketException;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.security.KeyStore;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.Iterator;
41 import java.util.List;
43 import java.util.Map.Entry;
44 import java.util.Properties;
46 import javax.net.ssl.HttpsURLConnection;
47 import javax.net.ssl.KeyManagerFactory;
48 import javax.net.ssl.SSLContext;
49 import javax.ws.rs.ProcessingException;
50 import javax.ws.rs.client.Client;
51 import javax.ws.rs.client.ClientBuilder;
52 import javax.ws.rs.client.Entity;
53 import javax.ws.rs.client.Invocation;
54 import javax.ws.rs.client.WebTarget;
55 import javax.ws.rs.core.EntityTag;
56 import javax.ws.rs.core.Feature;
57 import javax.ws.rs.core.MediaType;
58 import javax.ws.rs.core.MultivaluedMap;
59 import javax.ws.rs.core.Response;
60 import org.apache.commons.lang3.StringUtils;
61 import org.codehaus.jettison.json.JSONException;
62 import org.codehaus.jettison.json.JSONObject;
63 import org.glassfish.jersey.client.ClientProperties;
64 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
65 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
66 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
67 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
68 import org.glassfish.jersey.media.multipart.MultiPart;
69 import org.glassfish.jersey.media.multipart.MultiPartFeature;
70 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
71 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
72 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
73 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 public class RestapiCallNode implements SvcLogicJavaPlugin {
79 protected static final String PARTNERS_FILE_NAME = "partners.json";
80 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
81 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
82 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
83 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
84 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
86 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
87 private String uebServers;
88 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
90 private String responseReceivedMessage = "Response received. Time: {}";
91 private String responseHttpCodeMessage = "HTTP response code: {}";
92 private String requestPostingException = "Exception while posting http request to client ";
93 protected static final String skipSendingMessage = "skipSending";
94 protected static final String responsePrefix = "responsePrefix";
95 protected static final String restapiUrlString = "restapiUrl";
96 protected static final String restapiUserKey = "restapiUser";
97 protected static final String restapiPasswordKey = "restapiPassword";
98 protected Integer httpConnectTimeout;
99 protected Integer httpReadTimeout;
101 protected HashMap<String, PartnerDetails> partnerStore;
103 public RestapiCallNode() {
104 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
106 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
107 JSONObject partners = new JSONObject(jsonString);
108 partnerStore = new HashMap<>();
109 loadPartners(partners);
110 log.info("Partners support enabled");
111 } catch (Exception e) {
112 log.warn("Partners file could not be read, Partner support will not be enabled.", e);
115 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
116 Properties props = new Properties();
118 uebServers = props.getProperty("servers");
119 log.info("UEB support enabled");
120 } catch (Exception e) {
121 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
123 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
124 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
127 protected void loadPartners(JSONObject partners) {
128 Iterator<String> keys = partners.keys();
129 String partnerUserKey = "user";
130 String partnerPasswordKey = "password";
131 String partnerUrlKey = "url";
133 while (keys.hasNext()) {
134 String partnerKey = keys.next();
136 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
137 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
139 if (partnerObject.has(partnerUrlKey)) {
140 url = partnerObject.getString(partnerUrlKey);
142 String userName = partnerObject.getString(partnerUserKey);
143 String password = partnerObject.getString(partnerPasswordKey);
144 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
145 partnerStore.put(partnerKey, details);
146 log.info("mapped partner using partner key " + partnerKey);
148 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
150 } catch (JSONException e) {
151 log.info("Couldn't map the partner using partner key " + partnerKey, e);
156 /* Unobfuscate param value */
157 private static String getObfuscatedVal(String paramValue) {
158 String resValue = paramValue;
159 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
161 String paramStr = paramValue.substring(2, paramValue.length()-1);
162 if (paramStr != null && paramStr.length() > 0)
164 String val = System.getenv(paramStr);
165 if (val != null && val.length() > 0)
168 log.info("Obfuscated value RESET for param value:" + paramValue);
176 * Returns parameters from the parameter map.
178 * @param paramMap parameter map
179 * @param p parameters instance
180 * @return parameters filed instance
181 * @throws SvcLogicException when svc logic exception occurs
183 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
185 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
186 p.requestBody = parseParam(paramMap, "requestBody", false, null);
187 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
188 validateUrl(p.restapiUrl);
189 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
190 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
191 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
192 if (p.restapiUrlSuffix != null) {
193 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
194 validateUrl(p.restapiUrl);
196 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
197 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
198 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
199 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
200 p.contentType = parseParam(paramMap, "contentType", false, null);
201 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
202 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
203 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
204 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
205 p.listNameList = getListNameList(paramMap);
206 String skipSendingStr = paramMap.get(skipSendingMessage);
207 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
208 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
209 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
210 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
211 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
212 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
213 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
214 && p.keyStorePassword != null;
215 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
216 p.partner = parseParam(paramMap, "partner", false, null);
217 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
218 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
219 p.accept = parseParam(paramMap, "accept", false, null);
220 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
221 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
226 * Validates the given URL in the parameters.
228 * @param restapiUrl rest api URL
229 * @throws SvcLogicException when URL validation fails
231 private static void validateUrl(String restapiUrl) throws SvcLogicException {
232 if (restapiUrl.contains(",")) {
233 String[] urls = restapiUrl.split(",");
234 for (String url : urls) {
239 URI.create(restapiUrl);
240 } catch (IllegalArgumentException e) {
241 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
247 * Returns the list of list name.
249 * @param paramMap parameters map
250 * @return list of list name
252 private static Set<String> getListNameList(Map<String, String> paramMap) {
253 Set<String> ll = new HashSet<>();
254 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
255 if (entry.getKey().startsWith("listName")) {
256 ll.add(entry.getValue());
263 * Parses the parameter string map of property, validates if required, assigns default value if
264 * present and returns the value.
266 * @param paramMap string param map
267 * @param name name of the property
268 * @param required if value required
269 * @param def default value
270 * @return value of the property
271 * @throws SvcLogicException if required parameter value is empty
273 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
274 throws SvcLogicException {
275 String s = paramMap.get(name);
277 if (s == null || s.trim().length() == 0) {
281 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
285 StringBuilder value = new StringBuilder();
287 int i1 = s.indexOf('%');
289 int i2 = s.indexOf('%', i1 + 1);
294 String varName = s.substring(i1 + 1, i2);
295 String varValue = System.getenv(varName);
296 if (varValue == null) {
297 varValue = "%" + varName + "%";
300 value.append(s.substring(i, i1));
301 value.append(varValue);
304 i1 = s.indexOf('%', i);
306 value.append(s.substring(i));
308 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
310 return value.toString();
313 private static Object maskPassword(String name, Object value) {
314 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
315 for (String pwdName : pwdNames) {
316 if (name.contains(pwdName)) {
324 * Allows Directed Graphs the ability to interact with REST APIs.
326 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
330 * <th>Mandatory/Optional</th>
331 * <th>description</th>
332 * <th>example values</th></thead> <tbody>
334 * <td>templateFileName</td>
336 * <td>full path to template file that can be used to build a request</td>
337 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
340 * <td>restapiUrl</td>
342 * <td>url to send the request to</td>
343 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
346 * <td>restapiUser</td>
348 * <td>user name to use for http basic authentication</td>
352 * <td>restapiPassword</td>
354 * <td>unencrypted password to use for http basic authentication</td>
355 * <td>plain_password</td>
358 * <td>oAuthConsumerKey</td>
360 * <td>Consumer key to use for http oAuth authentication</td>
364 * <td>oAuthConsumerSecret</td>
366 * <td>Consumer secret to use for http oAuth authentication</td>
367 * <td>plain_secret</td>
370 * <td>oAuthSignatureMethod</td>
372 * <td>Consumer method to use for http oAuth authentication</td>
376 * <td>oAuthVersion</td>
378 * <td>Version http oAuth authentication</td>
382 * <td>contentType</td>
384 * <td>http content type to set in the http header</td>
385 * <td>usually application/json or application/xml</td>
390 * <td>should match request body format</td>
391 * <td>json or xml</td>
394 * <td>httpMethod</td>
396 * <td>http method to use when sending the request</td>
397 * <td>get post put delete patch</td>
400 * <td>responsePrefix</td>
402 * <td>location the response will be written to in context memory</td>
403 * <td>tmp.restapi.result</td>
406 * <td>listName[i]</td>
408 * <td>Used for processing XML responses with repeating
409 * elements.</td>vpn-information.vrf-details
413 * <td>skipSending</td>
416 * <td>true or false</td>
419 * <td>convertResponse</td>
421 * <td>whether the response should be converted</td>
422 * <td>true or false</td>
425 * <td>customHttpHeaders</td>
427 * <td>a list additional http headers to be passed in, follow the format in the example</td>
428 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
431 * <td>dumpHeaders</td>
433 * <td>when true writes http header content to context memory</td>
434 * <td>true or false</td>
439 * <td>used to retrieve username, password and url if partner store exists</td>
443 * <td>returnRequestPayload</td>
445 * <td>used to return payload built in the request</td>
446 * <td>true or false</td>
450 * @param ctx Reference to context memory
451 * @throws SvcLogicException
453 * @see String#split(String, int)
455 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
456 sendRequest(paramMap, ctx, null);
459 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
460 throws SvcLogicException {
462 HttpResponse r = new HttpResponse();
464 handlePartner(paramMap);
465 Parameters p = getParameters(paramMap, new Parameters());
466 if (p.restapiUrl.contains(",") && retryPolicy == null) {
467 String[] urls = p.restapiUrl.split(",");
468 retryPolicy = new RetryPolicy(urls, urls.length * 2);
469 p.restapiUrl = urls[0];
471 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
474 if (p.templateFileName != null) {
475 String reqTemplate = readFile(p.templateFileName);
476 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
477 } else if (p.requestBody != null) {
480 r = sendHttpRequest(req, p);
481 setResponseStatus(ctx, p.responsePrefix, r);
483 if (p.dumpHeaders && r.headers != null) {
484 for (Entry<String, List<String>> a : r.headers.entrySet()) {
485 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
489 if (p.returnRequestPayload && req != null) {
490 ctx.setAttribute(pp + "httpRequest", req);
493 if (r.body != null && r.body.trim().length() > 0) {
494 ctx.setAttribute(pp + "httpResponse", r.body);
496 if (p.convertResponse) {
497 Map<String, String> mm = null;
498 if (p.format == Format.XML) {
499 mm = XmlParser.convertToProperties(r.body, p.listNameList);
500 } else if (p.format == Format.JSON) {
501 mm = JsonParser.convertToProperties(r.body);
505 for (Map.Entry<String, String> entry : mm.entrySet()) {
506 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
511 } catch (SvcLogicException e) {
512 boolean shouldRetry = false;
513 if (e.getCause().getCause() instanceof SocketException) {
517 log.error("Error sending the request: " + e.getMessage(), e);
518 String prefix = parseParam(paramMap, responsePrefix, false, null);
519 if (retryPolicy == null || !shouldRetry) {
520 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
522 log.debug(retryPolicy.getRetryMessage());
524 // calling getNextHostName increments the retry count so it should be called before shouldRetry
525 String retryString = retryPolicy.getNextHostName();
526 if (retryPolicy.shouldRetry()) {
527 paramMap.put(restapiUrlString, retryString);
528 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
530 sendRequest(paramMap, ctx, retryPolicy);
532 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
533 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
535 } catch (Exception ex) {
536 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
537 + "has failed with error message " + ex.getMessage();
538 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
543 if (r != null && r.code >= 300) {
544 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
548 protected void handlePartner(Map<String, String> paramMap) {
549 String partner = paramMap.get("partner");
550 if (partner != null && partner.length() > 0) {
551 PartnerDetails details = partnerStore.get(partner);
552 paramMap.put(restapiUserKey, details.username);
553 paramMap.put(restapiPasswordKey, details.password);
554 if (paramMap.get(restapiUrlString) == null) {
555 paramMap.put(restapiUrlString, details.url);
560 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
561 log.info("Building {} started", format);
562 long t1 = System.currentTimeMillis();
563 String originalTemplate = template;
565 template = expandRepeats(ctx, template, 1);
567 Map<String, String> mm = new HashMap<>();
568 for (String s : ctx.getAttributeKeySet()) {
569 mm.put(s, ctx.getAttribute(s));
572 StringBuilder ss = new StringBuilder();
574 while (i < template.length()) {
575 int i1 = template.indexOf("${", i);
577 ss.append(template.substring(i));
581 int i2 = template.indexOf('}', i1 + 2);
583 throw new SvcLogicException("Template error: Matching } not found");
586 String var1 = template.substring(i1 + 2, i2);
587 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
588 if (value1 == null || value1.trim().length() == 0) {
589 // delete the whole element (line)
590 int i3 = template.lastIndexOf('\n', i1);
594 int i4 = template.indexOf('\n', i1);
596 i4 = template.length();
600 ss.append(template.substring(i, i3));
604 ss.append(template.substring(i, i1)).append(value1);
609 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
610 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
612 if (format == Format.JSON) {
613 req = XmlJsonUtil.removeLastCommaJson(req);
616 long t2 = System.currentTimeMillis();
617 log.info("Building {} completed. Time: {}", format, t2 - t1);
622 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
623 StringBuilder newTemplate = new StringBuilder();
625 while (k < template.length()) {
626 int i1 = template.indexOf("${repeat:", k);
628 newTemplate.append(template.substring(k));
632 int i2 = template.indexOf(':', i1 + 9);
634 throw new SvcLogicException(
635 "Template error: Context variable name followed by : is required after repeat");
638 // Find the closing }, store in i3
642 while (nn > 0 && i < template.length()) {
643 i3 = template.indexOf('}', i);
645 throw new SvcLogicException("Template error: Matching } not found");
647 int i32 = template.indexOf('{', i);
648 if (i32 >= 0 && i32 < i3) {
657 String var1 = template.substring(i1 + 9, i2);
658 String value1 = ctx.getAttribute(var1);
659 log.info(" {}:{}", var1, value1);
662 n = Integer.parseInt(value1);
663 } catch (NumberFormatException e) {
664 log.info("value1 not set or not a number, n will remain set at zero");
667 newTemplate.append(template.substring(k, i1));
669 String rpt = template.substring(i2 + 1, i3);
671 for (int ii = 0; ii < n; ii++) {
672 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
673 if (ii == n - 1 && ss.trim().endsWith(",")) {
674 int i4 = ss.lastIndexOf(',');
676 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
679 newTemplate.append(ss);
686 return newTemplate.toString();
689 return expandRepeats(ctx, newTemplate.toString(), level + 1);
692 protected String readFile(String fileName) throws SvcLogicException {
694 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
695 return new String(encoded, "UTF-8");
696 } catch (IOException | SecurityException e) {
697 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
701 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
702 Parameters p = new Parameters();
703 p.restapiUser = fp.user;
704 p.restapiPassword = fp.password;
705 p.oAuthConsumerKey = fp.oAuthConsumerKey;
706 p.oAuthVersion = fp.oAuthVersion;
707 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
708 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
709 p.authtype = fp.authtype;
710 return addAuthType(c, p);
713 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
714 if (p.authtype == AuthType.Unspecified) {
715 if (p.restapiUser != null && p.restapiPassword != null) {
716 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
717 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
718 Feature oAuth1Feature =
719 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
720 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
721 client.register(oAuth1Feature);
725 if (p.authtype == AuthType.DIGEST) {
726 if (p.restapiUser != null && p.restapiPassword != null) {
727 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
729 throw new SvcLogicException(
730 "oAUTH authentication type selected but all restapiUser and restapiPassword "
731 + "parameters doesn't exist",
734 } else if (p.authtype == AuthType.BASIC) {
735 if (p.restapiUser != null && p.restapiPassword != null) {
736 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
738 throw new SvcLogicException(
739 "oAUTH authentication type selected but all restapiUser and restapiPassword "
740 + "parameters doesn't exist",
743 } else if (p.authtype == AuthType.OAUTH) {
744 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
745 Feature oAuth1Feature = OAuth1ClientSupport
746 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
747 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
748 client.register(oAuth1Feature);
750 throw new SvcLogicException(
751 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
752 + "and oAuthSignatureMethod parameters doesn't exist",
761 * Receives the http response for the http request sent.
763 * @param request request msg
764 * @param p parameters
765 * @return HTTP response
766 * @throws SvcLogicException when sending http request fails
768 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
770 SSLContext ssl = null;
771 if (p.ssl && p.restapiUrl.startsWith("https")) {
772 ssl = createSSLContext(p);
777 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
778 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
780 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
782 setClientTimeouts(client);
783 // Needed to support additional HTTP methods such as PATCH
784 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
786 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
788 log.info("Sending request below to url " + p.restapiUrl);
790 long t1 = System.currentTimeMillis();
792 HttpResponse r = new HttpResponse();
794 String accept = p.accept;
795 if (accept == null) {
796 accept = p.format == Format.XML ? "application/xml" : "application/json";
799 String contentType = p.contentType;
800 if (contentType == null) {
801 contentType = accept + ";charset=UTF-8";
804 if (!p.skipSending && !p.multipartFormData) {
806 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
808 if (p.format == Format.NONE) {
809 invocationBuilder.header("", "");
812 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
813 String[] keyValuePairs = p.customHttpHeaders.split(",");
814 for (String singlePair : keyValuePairs) {
815 int equalPosition = singlePair.indexOf('=');
816 invocationBuilder.header(singlePair.substring(0, equalPosition),
817 singlePair.substring(equalPosition + 1, singlePair.length()));
821 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
823 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
828 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
829 } catch (ProcessingException | IllegalStateException e) {
830 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
833 r.code = response.getStatus();
834 r.headers = response.getStringHeaders();
835 EntityTag etag = response.getEntityTag();
837 r.message = etag.getValue();
839 if (response.hasEntity() && r.code != 204) {
840 r.body = response.readEntity(String.class);
842 } else if (!p.skipSending && p.multipartFormData) {
844 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
846 MultiPart multiPart = new MultiPart();
847 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
849 FileDataBodyPart fileDataBodyPart =
850 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
851 multiPart.bodyPart(fileDataBodyPart);
854 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
856 if (p.format == Format.NONE) {
857 invocationBuilder.header("", "");
860 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
861 String[] keyValuePairs = p.customHttpHeaders.split(",");
862 for (String singlePair : keyValuePairs) {
863 int equalPosition = singlePair.indexOf('=');
864 invocationBuilder.header(singlePair.substring(0, equalPosition),
865 singlePair.substring(equalPosition + 1, singlePair.length()));
869 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
875 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
876 } catch (ProcessingException | IllegalStateException e) {
877 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
880 r.code = response.getStatus();
881 r.headers = response.getStringHeaders();
882 EntityTag etag = response.getEntityTag();
884 r.message = etag.getValue();
886 if (response.hasEntity() && r.code != 204) {
887 r.body = response.readEntity(String.class);
892 long t2 = System.currentTimeMillis();
893 log.info(responseReceivedMessage, t2 - t1);
894 log.info(responseHttpCodeMessage, r.code);
895 log.info("HTTP response message: {}", r.message);
896 logHeaders(r.headers);
897 log.info("HTTP response: {}", r.body);
902 protected SSLContext createSSLContext(Parameters p) {
903 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
904 System.setProperty("jsse.enableSNIExtension", "false");
905 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
906 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
908 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
910 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
911 KeyStore ks = KeyStore.getInstance("PKCS12");
912 char[] pwd = p.keyStorePassword.toCharArray();
916 SSLContext ctx = SSLContext.getInstance("TLS");
917 ctx.init(kmf.getKeyManagers(), null, null);
919 } catch (Exception e) {
920 log.error("Error creating SSLContext: {}", e.getMessage(), e);
925 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
928 resp.message = errorMessage;
929 String pp = prefix != null ? prefix + '.' : "";
930 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
931 ctx.setAttribute(pp + "response-message", resp.message);
934 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
935 String pp = prefix != null ? prefix + '.' : "";
936 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
937 ctx.setAttribute(pp + "response-message", r.message);
940 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
941 HttpResponse r = null;
943 FileParam p = getFileParameters(paramMap);
944 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
946 r = sendHttpData(data, p);
947 setResponseStatus(ctx, p.responsePrefix, r);
949 } catch (SvcLogicException | IOException e) {
950 log.error("Error sending the request: {}", e.getMessage(), e);
952 r = new HttpResponse();
954 r.message = e.getMessage();
955 String prefix = parseParam(paramMap, responsePrefix, false, null);
956 setResponseStatus(ctx, prefix, r);
959 if (r != null && r.code >= 300) {
960 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
964 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
965 FileParam p = new FileParam();
966 p.fileName = parseParam(paramMap, "fileName", true, null);
967 p.url = parseParam(paramMap, "url", true, null);
968 p.user = parseParam(paramMap, "user", false, null);
969 p.password = parseParam(paramMap, "password", false, null);
970 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
971 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
972 String skipSendingStr = paramMap.get(skipSendingMessage);
973 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
974 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
975 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
976 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
977 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
978 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
982 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
985 UebParam p = getUebParameters(paramMap);
987 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
991 if (p.templateFileName == null) {
992 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
993 p.templateFileName = defaultUebTemplateFileName;
996 String reqTemplate = readFile(p.templateFileName);
997 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
998 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1000 r = postOnUeb(req, p);
1001 setResponseStatus(ctx, p.responsePrefix, r);
1002 if (r.body != null) {
1003 ctx.setAttribute(pp + "httpResponse", r.body);
1006 } catch (SvcLogicException e) {
1007 log.error("Error sending the request: {}", e.getMessage(), e);
1009 r = new HttpResponse();
1011 r.message = e.getMessage();
1012 String prefix = parseParam(paramMap, responsePrefix, false, null);
1013 setResponseStatus(ctx, prefix, r);
1016 if (r.code >= 300) {
1017 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1021 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
1023 Client client = ClientBuilder.newBuilder().build();
1024 setClientTimeouts(client);
1025 client.property(ClientProperties.FOLLOW_REDIRECTS, true);
1026 WebTarget webTarget = addAuthType(client, p).target(p.url);
1028 log.info("Sending file");
1029 long t1 = System.currentTimeMillis();
1031 HttpResponse r = new HttpResponse();
1034 if (!p.skipSending) {
1035 String tt = "application/octet-stream";
1036 Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
1041 if (p.httpMethod == HttpMethod.POST) {
1042 response = invocationBuilder.post(Entity.entity(data, tt));
1043 } else if (p.httpMethod == HttpMethod.PUT) {
1044 response = invocationBuilder.put(Entity.entity(data, tt));
1046 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1048 } catch (ProcessingException e) {
1049 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1052 r.code = response.getStatus();
1053 r.headers = response.getStringHeaders();
1054 EntityTag etag = response.getEntityTag();
1056 r.message = etag.getValue();
1058 if (response.hasEntity() && r.code != 204) {
1059 r.body = response.readEntity(String.class);
1062 if (r.code == 301) {
1063 String newUrl = response.getStringHeaders().getFirst("Location");
1065 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
1067 webTarget = client.target(newUrl);
1068 invocationBuilder = webTarget.request(tt).accept(tt);
1071 if (p.httpMethod == HttpMethod.POST) {
1072 response = invocationBuilder.post(Entity.entity(data, tt));
1073 } else if (p.httpMethod == HttpMethod.PUT) {
1074 response = invocationBuilder.put(Entity.entity(data, tt));
1076 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1078 } catch (ProcessingException e) {
1079 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1082 r.code = response.getStatus();
1083 etag = response.getEntityTag();
1085 r.message = etag.getValue();
1087 if (response.hasEntity() && r.code != 204) {
1088 r.body = response.readEntity(String.class);
1093 long t2 = System.currentTimeMillis();
1094 log.info(responseReceivedMessage, t2 - t1);
1095 log.info(responseHttpCodeMessage, r.code);
1096 log.info("HTTP response message: {}", r.message);
1097 logHeaders(r.headers);
1098 log.info("HTTP response: {}", r.body);
1103 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1104 UebParam p = new UebParam();
1105 p.topic = parseParam(paramMap, "topic", true, null);
1106 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1107 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1108 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1109 String skipSendingStr = paramMap.get(skipSendingMessage);
1110 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1114 protected void logProperties(Map<String, Object> mm) {
1115 List<String> ll = new ArrayList<>();
1116 for (Object o : mm.keySet()) {
1119 Collections.sort(ll);
1121 log.info("Properties:");
1122 for (String name : ll) {
1123 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1127 protected void logHeaders(MultivaluedMap<String, String> mm) {
1128 log.info("HTTP response headers:");
1134 List<String> ll = new ArrayList<>();
1135 for (Object o : mm.keySet()) {
1138 Collections.sort(ll);
1140 for (String name : ll) {
1141 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1145 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1146 String[] urls = uebServers.split(" ");
1147 for (int i = 0; i < urls.length; i++) {
1148 if (!urls[i].endsWith("/")) {
1151 urls[i] += "events/" + p.topic;
1154 Client client = ClientBuilder.newBuilder().build();
1155 setClientTimeouts(client);
1156 WebTarget webTarget = client.target(urls[0]);
1158 log.info("UEB URL: {}", urls[0]);
1159 log.info("Sending request:");
1161 long t1 = System.currentTimeMillis();
1163 HttpResponse r = new HttpResponse();
1166 if (!p.skipSending) {
1167 String tt = "application/json";
1168 String tt1 = tt + ";charset=UTF-8";
1171 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1174 response = invocationBuilder.post(Entity.entity(request, tt1));
1175 } catch (ProcessingException e) {
1176 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1178 r.code = response.getStatus();
1179 r.headers = response.getStringHeaders();
1180 if (response.hasEntity()) {
1181 r.body = response.readEntity(String.class);
1185 long t2 = System.currentTimeMillis();
1186 log.info(responseReceivedMessage, t2 - t1);
1187 log.info(responseHttpCodeMessage, r.code);
1188 logHeaders(r.headers);
1189 log.info("HTTP response:\n {}", r.body);
1194 public void setUebServers(String uebServers) {
1195 this.uebServers = uebServers;
1198 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1199 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1202 protected void setClientTimeouts(Client client) {
1203 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1204 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1207 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1208 String stringValue = System.getProperty(propertyName);
1209 if (stringValue != null && stringValue.length() > 0) {
1211 return Integer.valueOf(stringValue);
1212 } catch (NumberFormatException e) {
1213 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1216 return defaultValue;
1220 private static class FileParam {
1222 public String fileName;
1225 public String password;
1226 public HttpMethod httpMethod;
1227 public String responsePrefix;
1228 public boolean skipSending;
1229 public String oAuthConsumerKey;
1230 public String oAuthConsumerSecret;
1231 public String oAuthSignatureMethod;
1232 public String oAuthVersion;
1233 public AuthType authtype;
1236 private static class UebParam {
1238 public String topic;
1239 public String templateFileName;
1240 public String rootVarName;
1241 public String responsePrefix;
1242 public boolean skipSending;