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 javax.ws.rs.core.UriBuilder;
61 import org.apache.commons.lang3.StringUtils;
62 import org.codehaus.jettison.json.JSONException;
63 import org.codehaus.jettison.json.JSONObject;
64 import org.glassfish.jersey.client.ClientProperties;
65 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
66 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
67 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
68 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
69 import org.glassfish.jersey.media.multipart.MultiPart;
70 import org.glassfish.jersey.media.multipart.MultiPartFeature;
71 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
72 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
73 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
74 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
78 public class RestapiCallNode implements SvcLogicJavaPlugin {
80 protected static final String PARTNERS_FILE_NAME = "partners.json";
81 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
82 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
83 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
84 protected static final int DEFAULT_HTTP_CONNECT_TIMEOUT_MS = 30000; // 30 seconds
85 protected static final int DEFAULT_HTTP_READ_TIMEOUT_MS = 600000; // 10 minutes
87 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
88 private String uebServers;
89 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
91 private String responseReceivedMessage = "Response received. Time: {}";
92 private String responseHttpCodeMessage = "HTTP response code: {}";
93 private String requestPostingException = "Exception while posting http request to client ";
94 protected static final String skipSendingMessage = "skipSending";
95 protected static final String responsePrefix = "responsePrefix";
96 protected static final String restapiUrlString = "restapiUrl";
97 protected static final String restapiUserKey = "restapiUser";
98 protected static final String restapiPasswordKey = "restapiPassword";
99 protected Integer httpConnectTimeout;
100 protected Integer httpReadTimeout;
102 protected HashMap<String, PartnerDetails> partnerStore;
104 public RestapiCallNode() {
105 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
107 String jsonString = readFile(configDir + "/" + PARTNERS_FILE_NAME);
108 JSONObject partners = new JSONObject(jsonString);
109 partnerStore = new HashMap<>();
110 loadPartners(partners);
111 log.info("Partners support enabled");
112 } catch (Exception e) {
113 log.warn("Partners file could not be read, Partner support will not be enabled.", e);
116 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
117 Properties props = new Properties();
119 uebServers = props.getProperty("servers");
120 log.info("UEB support enabled");
121 } catch (Exception e) {
122 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
124 httpConnectTimeout = readOptionalInteger("HTTP_CONNECT_TIMEOUT_MS",DEFAULT_HTTP_CONNECT_TIMEOUT_MS);
125 httpReadTimeout = readOptionalInteger("HTTP_READ_TIMEOUT_MS",DEFAULT_HTTP_READ_TIMEOUT_MS);
128 protected void loadPartners(JSONObject partners) {
129 Iterator<String> keys = partners.keys();
130 String partnerUserKey = "user";
131 String partnerPasswordKey = "password";
132 String partnerUrlKey = "url";
134 while (keys.hasNext()) {
135 String partnerKey = keys.next();
137 JSONObject partnerObject = (JSONObject) partners.get(partnerKey);
138 if (partnerObject.has(partnerUserKey) && partnerObject.has(partnerPasswordKey)) {
140 if (partnerObject.has(partnerUrlKey)) {
141 url = partnerObject.getString(partnerUrlKey);
143 String userName = partnerObject.getString(partnerUserKey);
144 String password = partnerObject.getString(partnerPasswordKey);
145 PartnerDetails details = new PartnerDetails(userName, getObfuscatedVal(password), url);
146 partnerStore.put(partnerKey, details);
147 log.info("mapped partner using partner key " + partnerKey);
149 log.info("Partner " + partnerKey + " is missing required keys, it won't be mapped");
151 } catch (JSONException e) {
152 log.info("Couldn't map the partner using partner key " + partnerKey, e);
157 /* Unobfuscate param value */
158 private static String getObfuscatedVal(String paramValue) {
159 String resValue = paramValue;
160 if (paramValue != null && paramValue.startsWith("${") && paramValue.endsWith("}"))
162 String paramStr = paramValue.substring(2, paramValue.length()-1);
163 if (paramStr != null && paramStr.length() > 0)
165 String val = System.getenv(paramStr);
166 if (val != null && val.length() > 0)
169 log.info("Obfuscated value RESET for param value:" + paramValue);
177 * Returns parameters from the parameter map.
179 * @param paramMap parameter map
180 * @param p parameters instance
181 * @return parameters filed instance
182 * @throws SvcLogicException when svc logic exception occurs
184 public static Parameters getParameters(Map<String, String> paramMap, Parameters p) throws SvcLogicException {
186 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
187 p.requestBody = parseParam(paramMap, "requestBody", false, null);
188 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
189 p.restapiUrlSuffix = parseParam(paramMap, "restapiUrlSuffix", false, null);
190 if (p.restapiUrlSuffix != null) {
191 p.restapiUrl = p.restapiUrl + p.restapiUrlSuffix;
194 p.restapiUrl = UriBuilder.fromUri(p.restapiUrl).toTemplate();
195 validateUrl(p.restapiUrl);
197 p.restapiUser = parseParam(paramMap, restapiUserKey, false, null);
198 p.restapiPassword = parseParam(paramMap, restapiPasswordKey, false, null);
199 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
200 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
201 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
202 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
203 p.contentType = parseParam(paramMap, "contentType", false, null);
204 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
205 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
206 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
207 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
208 p.listNameList = getListNameList(paramMap);
209 String skipSendingStr = paramMap.get(skipSendingMessage);
210 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
211 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse", false, "true"));
212 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
213 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
214 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
215 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
216 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null
217 && p.keyStorePassword != null;
218 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
219 p.partner = parseParam(paramMap, "partner", false, null);
220 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders", false, null));
221 p.returnRequestPayload = valueOf(parseParam(paramMap, "returnRequestPayload", false, null));
222 p.accept = parseParam(paramMap, "accept", false, null);
223 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData", false, "false"));
224 p.multipartFile = parseParam(paramMap, "multipartFile", false, null);
229 * Validates the given URL in the parameters.
231 * @param restapiUrl rest api URL
232 * @throws SvcLogicException when URL validation fails
234 private static void validateUrl(String restapiUrl) throws SvcLogicException {
235 if (restapiUrl.contains(",")) {
236 String[] urls = restapiUrl.split(",");
237 for (String url : urls) {
242 URI.create(restapiUrl);
243 } catch (IllegalArgumentException e) {
244 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
250 * Returns the list of list name.
252 * @param paramMap parameters map
253 * @return list of list name
255 private static Set<String> getListNameList(Map<String, String> paramMap) {
256 Set<String> ll = new HashSet<>();
257 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
258 if (entry.getKey().startsWith("listName")) {
259 ll.add(entry.getValue());
266 * Parses the parameter string map of property, validates if required, assigns default value if
267 * present and returns the value.
269 * @param paramMap string param map
270 * @param name name of the property
271 * @param required if value required
272 * @param def default value
273 * @return value of the property
274 * @throws SvcLogicException if required parameter value is empty
276 public static String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
277 throws SvcLogicException {
278 String s = paramMap.get(name);
280 if (s == null || s.trim().length() == 0) {
284 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
288 StringBuilder value = new StringBuilder();
290 int i1 = s.indexOf('%');
292 int i2 = s.indexOf('%', i1 + 1);
297 String varName = s.substring(i1 + 1, i2);
298 String varValue = System.getenv(varName);
299 if (varValue == null) {
300 varValue = "%" + varName + "%";
303 value.append(s.substring(i, i1));
304 value.append(varValue);
307 i1 = s.indexOf('%', i);
309 value.append(s.substring(i));
311 log.info("Parameter {}: [{}]", name, maskPassword(name, value));
313 return value.toString();
316 private static Object maskPassword(String name, Object value) {
317 String[] pwdNames = {"pwd", "passwd", "password", "Pwd", "Passwd", "Password"};
318 for (String pwdName : pwdNames) {
319 if (name.contains(pwdName)) {
327 * Allows Directed Graphs the ability to interact with REST APIs.
329 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
333 * <th>Mandatory/Optional</th>
334 * <th>description</th>
335 * <th>example values</th></thead> <tbody>
337 * <td>templateFileName</td>
339 * <td>full path to template file that can be used to build a request</td>
340 * <td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td>
343 * <td>restapiUrl</td>
345 * <td>url to send the request to</td>
346 * <td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td>
349 * <td>restapiUser</td>
351 * <td>user name to use for http basic authentication</td>
355 * <td>restapiPassword</td>
357 * <td>unencrypted password to use for http basic authentication</td>
358 * <td>plain_password</td>
361 * <td>oAuthConsumerKey</td>
363 * <td>Consumer key to use for http oAuth authentication</td>
367 * <td>oAuthConsumerSecret</td>
369 * <td>Consumer secret to use for http oAuth authentication</td>
370 * <td>plain_secret</td>
373 * <td>oAuthSignatureMethod</td>
375 * <td>Consumer method to use for http oAuth authentication</td>
379 * <td>oAuthVersion</td>
381 * <td>Version http oAuth authentication</td>
385 * <td>contentType</td>
387 * <td>http content type to set in the http header</td>
388 * <td>usually application/json or application/xml</td>
393 * <td>should match request body format</td>
394 * <td>json or xml</td>
397 * <td>httpMethod</td>
399 * <td>http method to use when sending the request</td>
400 * <td>get post put delete patch</td>
403 * <td>responsePrefix</td>
405 * <td>location the response will be written to in context memory</td>
406 * <td>tmp.restapi.result</td>
409 * <td>listName[i]</td>
411 * <td>Used for processing XML responses with repeating
412 * elements.</td>vpn-information.vrf-details
416 * <td>skipSending</td>
419 * <td>true or false</td>
422 * <td>convertResponse</td>
424 * <td>whether the response should be converted</td>
425 * <td>true or false</td>
428 * <td>customHttpHeaders</td>
430 * <td>a list additional http headers to be passed in, follow the format in the example</td>
431 * <td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td>
434 * <td>dumpHeaders</td>
436 * <td>when true writes http header content to context memory</td>
437 * <td>true or false</td>
442 * <td>used to retrieve username, password and url if partner store exists</td>
446 * <td>returnRequestPayload</td>
448 * <td>used to return payload built in the request</td>
449 * <td>true or false</td>
453 * @param ctx Reference to context memory
454 * @throws SvcLogicException
456 * @see String#split(String, int)
458 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
459 sendRequest(paramMap, ctx, null);
462 protected void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, RetryPolicy retryPolicy)
463 throws SvcLogicException {
465 HttpResponse r = new HttpResponse();
467 handlePartner(paramMap);
468 Parameters p = getParameters(paramMap, new Parameters());
469 if (p.restapiUrl.contains(",") && retryPolicy == null) {
470 String[] urls = p.restapiUrl.split(",");
471 retryPolicy = new RetryPolicy(urls, urls.length * 2);
472 p.restapiUrl = urls[0];
474 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
477 if (p.templateFileName != null) {
478 String reqTemplate = readFile(p.templateFileName);
479 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
480 } else if (p.requestBody != null) {
483 r = sendHttpRequest(req, p);
484 setResponseStatus(ctx, p.responsePrefix, r);
486 if (p.dumpHeaders && r.headers != null) {
487 for (Entry<String, List<String>> a : r.headers.entrySet()) {
488 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
492 if (p.returnRequestPayload && req != null) {
493 ctx.setAttribute(pp + "httpRequest", req);
496 if (r.body != null && r.body.trim().length() > 0) {
497 ctx.setAttribute(pp + "httpResponse", r.body);
499 if (p.convertResponse) {
500 Map<String, String> mm = null;
501 if (p.format == Format.XML) {
502 mm = XmlParser.convertToProperties(r.body, p.listNameList);
503 } else if (p.format == Format.JSON) {
504 mm = JsonParser.convertToProperties(r.body);
508 for (Map.Entry<String, String> entry : mm.entrySet()) {
509 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
514 } catch (SvcLogicException e) {
515 boolean shouldRetry = false;
516 if (e.getCause().getCause() instanceof SocketException) {
520 log.error("Error sending the request: " + e.getMessage(), e);
521 String prefix = parseParam(paramMap, responsePrefix, false, null);
522 if (retryPolicy == null || !shouldRetry) {
523 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
525 log.debug(retryPolicy.getRetryMessage());
527 // calling getNextHostName increments the retry count so it should be called before shouldRetry
528 String retryString = retryPolicy.getNextHostName();
529 if (retryPolicy.shouldRetry()) {
530 paramMap.put(restapiUrlString, retryString);
531 log.debug("retry attempt {} will use the retry url {}", retryPolicy.getRetryCount(),
533 sendRequest(paramMap, ctx, retryPolicy);
535 log.debug("Maximum retries reached, won't attempt to retry. Calling setFailureResponseStatus.");
536 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
538 } catch (Exception ex) {
539 String retryErrorMessage = "Retry attempt " + retryPolicy.getRetryCount()
540 + "has failed with error message " + ex.getMessage();
541 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
546 if (r != null && r.code >= 300) {
547 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
551 protected void handlePartner(Map<String, String> paramMap) {
552 String partner = paramMap.get("partner");
553 if (partner != null && partner.length() > 0) {
554 PartnerDetails details = partnerStore.get(partner);
555 paramMap.put(restapiUserKey, details.username);
556 paramMap.put(restapiPasswordKey, details.password);
557 if (paramMap.get(restapiUrlString) == null) {
558 paramMap.put(restapiUrlString, details.url);
563 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) throws SvcLogicException {
564 log.info("Building {} started", format);
565 long t1 = System.currentTimeMillis();
566 String originalTemplate = template;
568 template = expandRepeats(ctx, template, 1);
570 Map<String, String> mm = new HashMap<>();
571 for (String s : ctx.getAttributeKeySet()) {
572 mm.put(s, ctx.getAttribute(s));
575 StringBuilder ss = new StringBuilder();
577 while (i < template.length()) {
578 int i1 = template.indexOf("${", i);
580 ss.append(template.substring(i));
584 int i2 = template.indexOf('}', i1 + 2);
586 throw new SvcLogicException("Template error: Matching } not found");
589 String var1 = template.substring(i1 + 2, i2);
590 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
591 if (value1 == null || value1.trim().length() == 0) {
592 // delete the whole element (line)
593 int i3 = template.lastIndexOf('\n', i1);
597 int i4 = template.indexOf('\n', i1);
599 i4 = template.length();
603 ss.append(template.substring(i, i3));
607 ss.append(template.substring(i, i1)).append(value1);
612 String req = format == Format.XML ? XmlJsonUtil.removeEmptyStructXml(ss.toString())
613 : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
615 if (format == Format.JSON) {
616 req = XmlJsonUtil.removeLastCommaJson(req);
619 long t2 = System.currentTimeMillis();
620 log.info("Building {} completed. Time: {}", format, t2 - t1);
625 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
626 StringBuilder newTemplate = new StringBuilder();
628 while (k < template.length()) {
629 int i1 = template.indexOf("${repeat:", k);
631 newTemplate.append(template.substring(k));
635 int i2 = template.indexOf(':', i1 + 9);
637 throw new SvcLogicException(
638 "Template error: Context variable name followed by : is required after repeat");
641 // Find the closing }, store in i3
645 while (nn > 0 && i < template.length()) {
646 i3 = template.indexOf('}', i);
648 throw new SvcLogicException("Template error: Matching } not found");
650 int i32 = template.indexOf('{', i);
651 if (i32 >= 0 && i32 < i3) {
660 String var1 = template.substring(i1 + 9, i2);
661 String value1 = ctx.getAttribute(var1);
662 log.info(" {}:{}", var1, value1);
665 n = Integer.parseInt(value1);
666 } catch (NumberFormatException e) {
667 log.info("value1 not set or not a number, n will remain set at zero");
670 newTemplate.append(template.substring(k, i1));
672 String rpt = template.substring(i2 + 1, i3);
674 for (int ii = 0; ii < n; ii++) {
675 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
676 if (ii == n - 1 && ss.trim().endsWith(",")) {
677 int i4 = ss.lastIndexOf(',');
679 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
682 newTemplate.append(ss);
689 return newTemplate.toString();
692 return expandRepeats(ctx, newTemplate.toString(), level + 1);
695 protected String readFile(String fileName) throws SvcLogicException {
697 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
698 return new String(encoded, "UTF-8");
699 } catch (IOException | SecurityException e) {
700 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
704 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
705 Parameters p = new Parameters();
706 p.restapiUser = fp.user;
707 p.restapiPassword = fp.password;
708 p.oAuthConsumerKey = fp.oAuthConsumerKey;
709 p.oAuthVersion = fp.oAuthVersion;
710 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
711 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
712 p.authtype = fp.authtype;
713 return addAuthType(c, p);
716 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
717 if (p.authtype == AuthType.Unspecified) {
718 if (p.restapiUser != null && p.restapiPassword != null) {
719 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
720 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
721 Feature oAuth1Feature =
722 OAuth1ClientSupport.builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
723 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
724 client.register(oAuth1Feature);
728 if (p.authtype == AuthType.DIGEST) {
729 if (p.restapiUser != null && p.restapiPassword != null) {
730 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
732 throw new SvcLogicException(
733 "oAUTH authentication type selected but all restapiUser and restapiPassword "
734 + "parameters doesn't exist",
737 } else if (p.authtype == AuthType.BASIC) {
738 if (p.restapiUser != null && p.restapiPassword != null) {
739 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
741 throw new SvcLogicException(
742 "oAUTH authentication type selected but all restapiUser and restapiPassword "
743 + "parameters doesn't exist",
746 } else if (p.authtype == AuthType.OAUTH) {
747 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
748 Feature oAuth1Feature = OAuth1ClientSupport
749 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
750 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
751 client.register(oAuth1Feature);
753 throw new SvcLogicException(
754 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret "
755 + "and oAuthSignatureMethod parameters doesn't exist",
764 * Receives the http response for the http request sent.
766 * @param request request msg
767 * @param p parameters
768 * @return HTTP response
769 * @throws SvcLogicException when sending http request fails
771 public HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
773 SSLContext ssl = null;
774 if (p.ssl && p.restapiUrl.startsWith("https")) {
775 ssl = createSSLContext(p);
780 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
781 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true).build();
783 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true).build();
785 setClientTimeouts(client);
786 // Needed to support additional HTTP methods such as PATCH
787 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
789 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
791 log.info("Sending request below to url " + p.restapiUrl);
793 long t1 = System.currentTimeMillis();
795 HttpResponse r = new HttpResponse();
797 String accept = p.accept;
798 if (accept == null) {
799 accept = p.format == Format.XML ? "application/xml" : "application/json";
802 String contentType = p.contentType;
803 if (contentType == null) {
804 contentType = accept + ";charset=UTF-8";
807 if (!p.skipSending && !p.multipartFormData) {
809 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
811 if (p.format == Format.NONE) {
812 invocationBuilder.header("", "");
815 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
816 String[] keyValuePairs = p.customHttpHeaders.split(",");
817 for (String singlePair : keyValuePairs) {
818 int equalPosition = singlePair.indexOf('=');
819 invocationBuilder.header(singlePair.substring(0, equalPosition),
820 singlePair.substring(equalPosition + 1, singlePair.length()));
824 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
826 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
831 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
832 } catch (ProcessingException | IllegalStateException e) {
833 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
836 r.code = response.getStatus();
837 r.headers = response.getStringHeaders();
838 EntityTag etag = response.getEntityTag();
840 r.message = etag.getValue();
842 if (response.hasEntity() && r.code != 204) {
843 r.body = response.readEntity(String.class);
845 } else if (!p.skipSending && p.multipartFormData) {
847 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
849 MultiPart multiPart = new MultiPart();
850 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
852 FileDataBodyPart fileDataBodyPart =
853 new FileDataBodyPart("file", new File(p.multipartFile), MediaType.APPLICATION_OCTET_STREAM_TYPE);
854 multiPart.bodyPart(fileDataBodyPart);
857 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
859 if (p.format == Format.NONE) {
860 invocationBuilder.header("", "");
863 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
864 String[] keyValuePairs = p.customHttpHeaders.split(",");
865 for (String singlePair : keyValuePairs) {
866 int equalPosition = singlePair.indexOf('=');
867 invocationBuilder.header(singlePair.substring(0, equalPosition),
868 singlePair.substring(equalPosition + 1, singlePair.length()));
872 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
878 invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
879 } catch (ProcessingException | IllegalStateException e) {
880 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
883 r.code = response.getStatus();
884 r.headers = response.getStringHeaders();
885 EntityTag etag = response.getEntityTag();
887 r.message = etag.getValue();
889 if (response.hasEntity() && r.code != 204) {
890 r.body = response.readEntity(String.class);
895 long t2 = System.currentTimeMillis();
896 log.info(responseReceivedMessage, t2 - t1);
897 log.info(responseHttpCodeMessage, r.code);
898 log.info("HTTP response message: {}", r.message);
899 logHeaders(r.headers);
900 log.info("HTTP response: {}", r.body);
905 protected SSLContext createSSLContext(Parameters p) {
906 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
907 System.setProperty("jsse.enableSNIExtension", "false");
908 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
909 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
911 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
913 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
914 KeyStore ks = KeyStore.getInstance("PKCS12");
915 char[] pwd = p.keyStorePassword.toCharArray();
919 SSLContext ctx = SSLContext.getInstance("TLS");
920 ctx.init(kmf.getKeyManagers(), null, null);
922 } catch (Exception e) {
923 log.error("Error creating SSLContext: {}", e.getMessage(), e);
928 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
931 resp.message = errorMessage;
932 String pp = prefix != null ? prefix + '.' : "";
933 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
934 ctx.setAttribute(pp + "response-message", resp.message);
937 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
938 String pp = prefix != null ? prefix + '.' : "";
939 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
940 ctx.setAttribute(pp + "response-message", r.message);
943 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
944 HttpResponse r = null;
946 FileParam p = getFileParameters(paramMap);
947 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
949 r = sendHttpData(data, p);
950 setResponseStatus(ctx, p.responsePrefix, r);
952 } catch (SvcLogicException | IOException e) {
953 log.error("Error sending the request: {}", e.getMessage(), e);
955 r = new HttpResponse();
957 r.message = e.getMessage();
958 String prefix = parseParam(paramMap, responsePrefix, false, null);
959 setResponseStatus(ctx, prefix, r);
962 if (r != null && r.code >= 300) {
963 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
967 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
968 FileParam p = new FileParam();
969 p.fileName = parseParam(paramMap, "fileName", true, null);
970 p.url = parseParam(paramMap, "url", true, null);
971 p.user = parseParam(paramMap, "user", false, null);
972 p.password = parseParam(paramMap, "password", false, null);
973 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
974 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
975 String skipSendingStr = paramMap.get(skipSendingMessage);
976 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
977 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
978 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
979 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
980 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
981 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
985 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
988 UebParam p = getUebParameters(paramMap);
990 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
994 if (p.templateFileName == null) {
995 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
996 p.templateFileName = defaultUebTemplateFileName;
999 String reqTemplate = readFile(p.templateFileName);
1000 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
1001 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
1003 r = postOnUeb(req, p);
1004 setResponseStatus(ctx, p.responsePrefix, r);
1005 if (r.body != null) {
1006 ctx.setAttribute(pp + "httpResponse", r.body);
1009 } catch (SvcLogicException e) {
1010 log.error("Error sending the request: {}", e.getMessage(), e);
1012 r = new HttpResponse();
1014 r.message = e.getMessage();
1015 String prefix = parseParam(paramMap, responsePrefix, false, null);
1016 setResponseStatus(ctx, prefix, r);
1019 if (r.code >= 300) {
1020 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
1024 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
1026 Client client = ClientBuilder.newBuilder().build();
1027 setClientTimeouts(client);
1028 client.property(ClientProperties.FOLLOW_REDIRECTS, true);
1029 WebTarget webTarget = addAuthType(client, p).target(p.url);
1031 log.info("Sending file");
1032 long t1 = System.currentTimeMillis();
1034 HttpResponse r = new HttpResponse();
1037 if (!p.skipSending) {
1038 String tt = "application/octet-stream";
1039 Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
1044 if (p.httpMethod == HttpMethod.POST) {
1045 response = invocationBuilder.post(Entity.entity(data, tt));
1046 } else if (p.httpMethod == HttpMethod.PUT) {
1047 response = invocationBuilder.put(Entity.entity(data, tt));
1049 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1051 } catch (ProcessingException e) {
1052 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1055 r.code = response.getStatus();
1056 r.headers = response.getStringHeaders();
1057 EntityTag etag = response.getEntityTag();
1059 r.message = etag.getValue();
1061 if (response.hasEntity() && r.code != 204) {
1062 r.body = response.readEntity(String.class);
1065 if (r.code == 301) {
1066 String newUrl = response.getStringHeaders().getFirst("Location");
1068 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
1070 webTarget = client.target(newUrl);
1071 invocationBuilder = webTarget.request(tt).accept(tt);
1074 if (p.httpMethod == HttpMethod.POST) {
1075 response = invocationBuilder.post(Entity.entity(data, tt));
1076 } else if (p.httpMethod == HttpMethod.PUT) {
1077 response = invocationBuilder.put(Entity.entity(data, tt));
1079 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
1081 } catch (ProcessingException e) {
1082 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1085 r.code = response.getStatus();
1086 etag = response.getEntityTag();
1088 r.message = etag.getValue();
1090 if (response.hasEntity() && r.code != 204) {
1091 r.body = response.readEntity(String.class);
1096 long t2 = System.currentTimeMillis();
1097 log.info(responseReceivedMessage, t2 - t1);
1098 log.info(responseHttpCodeMessage, r.code);
1099 log.info("HTTP response message: {}", r.message);
1100 logHeaders(r.headers);
1101 log.info("HTTP response: {}", r.body);
1106 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
1107 UebParam p = new UebParam();
1108 p.topic = parseParam(paramMap, "topic", true, null);
1109 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
1110 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
1111 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
1112 String skipSendingStr = paramMap.get(skipSendingMessage);
1113 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
1117 protected void logProperties(Map<String, Object> mm) {
1118 List<String> ll = new ArrayList<>();
1119 for (Object o : mm.keySet()) {
1122 Collections.sort(ll);
1124 log.info("Properties:");
1125 for (String name : ll) {
1126 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1130 protected void logHeaders(MultivaluedMap<String, String> mm) {
1131 log.info("HTTP response headers:");
1137 List<String> ll = new ArrayList<>();
1138 for (Object o : mm.keySet()) {
1141 Collections.sort(ll);
1143 for (String name : ll) {
1144 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1148 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1149 String[] urls = uebServers.split(" ");
1150 for (int i = 0; i < urls.length; i++) {
1151 if (!urls[i].endsWith("/")) {
1154 urls[i] += "events/" + p.topic;
1157 Client client = ClientBuilder.newBuilder().build();
1158 setClientTimeouts(client);
1159 WebTarget webTarget = client.target(urls[0]);
1161 log.info("UEB URL: {}", urls[0]);
1162 log.info("Sending request:");
1164 long t1 = System.currentTimeMillis();
1166 HttpResponse r = new HttpResponse();
1169 if (!p.skipSending) {
1170 String tt = "application/json";
1171 String tt1 = tt + ";charset=UTF-8";
1174 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1177 response = invocationBuilder.post(Entity.entity(request, tt1));
1178 } catch (ProcessingException e) {
1179 throw new SvcLogicException(requestPostingException + e.getLocalizedMessage(), e);
1181 r.code = response.getStatus();
1182 r.headers = response.getStringHeaders();
1183 if (response.hasEntity()) {
1184 r.body = response.readEntity(String.class);
1188 long t2 = System.currentTimeMillis();
1189 log.info(responseReceivedMessage, t2 - t1);
1190 log.info(responseHttpCodeMessage, r.code);
1191 logHeaders(r.headers);
1192 log.info("HTTP response:\n {}", r.body);
1197 public void setUebServers(String uebServers) {
1198 this.uebServers = uebServers;
1201 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1202 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1205 protected void setClientTimeouts(Client client) {
1206 client.property(ClientProperties.CONNECT_TIMEOUT, httpConnectTimeout);
1207 client.property(ClientProperties.READ_TIMEOUT, httpReadTimeout);
1210 protected Integer readOptionalInteger(String propertyName, Integer defaultValue) {
1211 String stringValue = System.getProperty(propertyName);
1212 if (stringValue != null && stringValue.length() > 0) {
1214 return Integer.valueOf(stringValue);
1215 } catch (NumberFormatException e) {
1216 log.warn("property " + propertyName + " had the value " + stringValue + " that could not be converted to an Integer, default " + defaultValue + " will be used instead", e);
1219 return defaultValue;
1223 private static class FileParam {
1225 public String fileName;
1228 public String password;
1229 public HttpMethod httpMethod;
1230 public String responsePrefix;
1231 public boolean skipSending;
1232 public String oAuthConsumerKey;
1233 public String oAuthConsumerSecret;
1234 public String oAuthSignatureMethod;
1235 public String oAuthVersion;
1236 public AuthType authtype;
1239 private static class UebParam {
1241 public String topic;
1242 public String templateFileName;
1243 public String rootVarName;
1244 public String responsePrefix;
1245 public boolean skipSending;