2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.plugins.restapicall;
24 import static java.lang.Boolean.valueOf;
25 import static javax.ws.rs.client.Entity.entity;
26 import static org.onap.ccsdk.sli.plugins.restapicall.AuthType.fromString;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.net.SocketException;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.security.KeyStore;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.List;
41 import java.util.Map.Entry;
42 import java.util.Properties;
44 import javax.net.ssl.HttpsURLConnection;
45 import javax.net.ssl.KeyManagerFactory;
46 import javax.net.ssl.SSLContext;
47 import javax.ws.rs.ProcessingException;
48 import javax.ws.rs.client.Client;
49 import javax.ws.rs.client.ClientBuilder;
50 import javax.ws.rs.client.Entity;
51 import javax.ws.rs.client.Invocation;
52 import javax.ws.rs.client.WebTarget;
53 import javax.ws.rs.core.EntityTag;
54 import javax.ws.rs.core.Feature;
55 import javax.ws.rs.core.MultivaluedMap;
56 import javax.ws.rs.core.Response;
57 import javax.ws.rs.core.UriBuilder;
58 import org.apache.commons.lang3.StringUtils;
59 import org.glassfish.jersey.client.ClientProperties;
60 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
61 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
62 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
63 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
64 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
65 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class RestapiCallNode implements SvcLogicJavaPlugin {
71 protected static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties";
72 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
73 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
74 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
76 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
77 protected RetryPolicyStore retryPolicyStore;
78 private String uebServers;
79 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
81 public RestapiCallNode() {
82 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
84 try (FileInputStream in = new FileInputStream(configDir + "/" + DME2_PROPERTIES_FILE_NAME)) {
85 Properties props = new Properties();
87 this.retryPolicyStore = new RetryPolicyStore();
88 this.retryPolicyStore.setProxyServers(props.getProperty("proxyUrl"));
89 log.info("DME2 support enabled");
90 } catch (Exception e) {
91 log.warn("DME2 properties could not be read, DME2 support will not be enabled.", e);
94 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
95 Properties props = new Properties();
97 this.uebServers = props.getProperty("servers");
98 log.info("UEB support enabled");
99 } catch (Exception e) {
100 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
105 * Returns parameters from the parameter map.
107 * @param paramMap parameter map
108 * @param p parameters instance
109 * @return parameters filed instance
110 * @throws SvcLogicException when svc logic exception occurs
112 public static Parameters getParameters(Map<String, String> paramMap,
114 throws SvcLogicException {
115 p.templateFileName = parseParam(paramMap, "templateFileName",
117 p.requestBody = parseParam(paramMap, "requestBody", false, null);
118 p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
119 validateUrl(p.restapiUrl);
120 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
121 p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
123 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey",
125 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret",
127 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod",
129 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
130 p.contentType = parseParam(paramMap, "contentType", false, null);
131 p.format = Format.fromString(parseParam(paramMap, "format", false,
133 p.authtype = fromString(parseParam(paramMap, "authType", false,
135 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
137 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
138 p.listNameList = getListNameList(paramMap);
139 String skipSendingStr = paramMap.get("skipSending");
140 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
141 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
143 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName",
145 p.trustStorePassword = parseParam(paramMap, "trustStorePassword",
147 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName",
149 p.keyStorePassword = parseParam(paramMap, "keyStorePassword",
151 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null
152 && p.keyStoreFileName != null && p.keyStorePassword != null;
153 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders",
155 p.partner = parseParam(paramMap, "partner", false, null);
156 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders",
158 p.returnRequestPayload = valueOf(parseParam(
159 paramMap, "returnRequestPayload", false, null));
164 * Validates the given URL in the parameters.
166 * @param restapiUrl rest api URL
167 * @throws SvcLogicException when URL validation fails
169 private static void validateUrl(String restapiUrl)
170 throws SvcLogicException {
172 URI.create(restapiUrl);
173 } catch (IllegalArgumentException e) {
174 throw new SvcLogicException("Invalid input of url "
175 + e.getLocalizedMessage(), e);
180 * Returns the list of list name.
182 * @param paramMap parameters map
183 * @return list of list name
185 private static Set<String> getListNameList(Map<String, String> paramMap) {
186 Set<String> ll = new HashSet<>();
187 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
188 if (entry.getKey().startsWith("listName")) {
189 ll.add(entry.getValue());
196 * Parses the parameter string map of property, validates if required,
197 * assigns default value if present and returns the value.
199 * @param paramMap string param map
200 * @param name name of the property
201 * @param required if value required
202 * @param def default value
203 * @return value of the property
204 * @throws SvcLogicException if required parameter value is empty
206 public static String parseParam(Map<String, String> paramMap, String name,
207 boolean required, String def)
208 throws SvcLogicException {
209 String s = paramMap.get(name);
211 if (s == null || s.trim().length() == 0) {
215 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
219 StringBuilder value = new StringBuilder();
221 int i1 = s.indexOf('%');
223 int i2 = s.indexOf('%', i1 + 1);
228 String varName = s.substring(i1 + 1, i2);
229 String varValue = System.getenv(varName);
230 if (varValue == null) {
231 varValue = "%" + varName + "%";
234 value.append(s.substring(i, i1));
235 value.append(varValue);
238 i1 = s.indexOf('%', i);
240 value.append(s.substring(i));
242 log.info("Parameter {}: [{}]", name, value);
243 return value.toString();
246 public RetryPolicyStore getRetryPolicyStore() {
247 return retryPolicyStore;
250 public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
251 this.retryPolicyStore = retryPolicyStore;
255 * Allows Directed Graphs the ability to interact with REST APIs.
256 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
258 * <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
260 * <tr><td>templateFileName</td><td>Optional</td><td>full path to template file that can be used to build a request</td><td>/sdncopt/bvc/restapi/templates/vnf_service-configuration-operation_minimal.json</td></tr>
261 * <tr><td>restapiUrl</td><td>Mandatory</td><td>url to send the request to</td><td>https://sdncodl:8543/restconf/operations/L3VNF-API:create-update-vnf-request</td></tr>
262 * <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
263 * <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
264 * <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
265 * <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
266 * <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
267 * <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
268 * <tr><td>contentType</td><td>Optional</td><td>http content type to set in the http header</td><td>usually application/json or application/xml</td></tr>
269 * <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
270 * <tr><td>httpMethod</td><td>Optional</td><td>http method to use when sending the request</td><td>get post put delete patch</td></tr>
271 * <tr><td>responsePrefix</td><td>Optional</td><td>location the response will be written to in context memory</td><td>tmp.restapi.result</td></tr>
272 * <tr><td>listName[i]</td><td>Optional</td><td>Used for processing XML responses with repeating elements.</td>vpn-information.vrf-details<td></td></tr>
273 * <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
274 * <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
275 * <tr><td>customHttpHeaders</td><td>Optional</td><td>a list additional http headers to be passed in, follow the format in the example</td><td>X-CSI-MessageId=messageId,headerFieldName=headerFieldValue</td></tr>
276 * <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
277 * <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
278 * <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
281 * @param ctx Reference to context memory
282 * @throws SvcLogicException
284 * @see String#split(String, int)
286 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
287 sendRequest(paramMap, ctx, null);
290 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
291 throws SvcLogicException {
293 RetryPolicy retryPolicy = null;
294 HttpResponse r = new HttpResponse();
296 Parameters p = getParameters(paramMap, new Parameters());
297 if (p.partner != null) {
298 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
300 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
303 if (p.templateFileName != null) {
304 String reqTemplate = readFile(p.templateFileName);
305 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
306 } else if (p.requestBody != null) {
309 r = sendHttpRequest(req, p);
310 setResponseStatus(ctx, p.responsePrefix, r);
312 if (p.dumpHeaders && r.headers != null) {
313 for (Entry<String, List<String>> a : r.headers.entrySet()) {
314 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
318 if (p.returnRequestPayload && req != null) {
319 ctx.setAttribute(pp + "httpRequest", req);
322 if (r.body != null && r.body.trim().length() > 0) {
323 ctx.setAttribute(pp + "httpResponse", r.body);
325 if (p.convertResponse) {
326 Map<String, String> mm = null;
327 if (p.format == Format.XML) {
328 mm = XmlParser.convertToProperties(r.body, p.listNameList);
329 } else if (p.format == Format.JSON) {
330 mm = JsonParser.convertToProperties(r.body);
334 for (Map.Entry<String, String> entry : mm.entrySet()) {
335 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
340 } catch (SvcLogicException e) {
341 boolean shouldRetry = false;
342 if (e.getCause().getCause() instanceof SocketException) {
346 log.error("Error sending the request: " + e.getMessage(), e);
347 String prefix = parseParam(paramMap, "responsePrefix", false, null);
348 if (retryPolicy == null || shouldRetry == false) {
349 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
351 if (retryCount == null) {
354 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
356 log.debug(retryMessage);
358 retryCount = retryCount + 1;
359 if (retryCount < retryPolicy.getMaximumRetries() + 1) {
360 URI uri = new URI(paramMap.get("restapiUrl"));
361 String hostname = uri.getHost();
362 String retryString = retryPolicy.getNextHostName(uri.toString());
363 URI uriTwo = new URI(retryString);
364 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
365 uriTwo.getScheme()).build();
366 paramMap.put("restapiUrl", retryUri.toString());
367 log.debug("URL was set to {}", retryUri.toString());
368 log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
369 hostname, retryString);
370 log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
371 sendRequest(paramMap, ctx, retryCount);
373 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
374 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
376 } catch (Exception ex) {
377 log.error("Could not attempt retry.", ex);
378 String retryErrorMessage =
379 "Retry attempt has failed. No further retry shall be attempted, calling " +
380 "setFailureResponseStatus.";
381 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
386 if (r != null && r.code >= 300) {
387 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
391 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
392 throws SvcLogicException {
393 log.info("Building {} started", format);
394 long t1 = System.currentTimeMillis();
395 String originalTemplate = template;
397 template = expandRepeats(ctx, template, 1);
399 Map<String, String> mm = new HashMap<>();
400 for (String s : ctx.getAttributeKeySet()) {
401 mm.put(s, ctx.getAttribute(s));
404 StringBuilder ss = new StringBuilder();
406 while (i < template.length()) {
407 int i1 = template.indexOf("${", i);
409 ss.append(template.substring(i));
413 int i2 = template.indexOf('}', i1 + 2);
415 throw new SvcLogicException("Template error: Matching } not found");
418 String var1 = template.substring(i1 + 2, i2);
419 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
420 // log.info(" " + var1 + ": " + value1);
421 if (value1 == null || value1.trim().length() == 0) {
422 // delete the whole element (line)
423 int i3 = template.lastIndexOf('\n', i1);
427 int i4 = template.indexOf('\n', i1);
429 i4 = template.length();
433 ss.append(template.substring(i, i3));
437 ss.append(template.substring(i, i1)).append(value1);
442 String req = format == Format.XML
443 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
445 if (format == Format.JSON) {
446 req = XmlJsonUtil.removeLastCommaJson(req);
449 long t2 = System.currentTimeMillis();
450 log.info("Building {} completed. Time: {}", format, (t2 - t1));
455 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
456 StringBuilder newTemplate = new StringBuilder();
458 while (k < template.length()) {
459 int i1 = template.indexOf("${repeat:", k);
461 newTemplate.append(template.substring(k));
465 int i2 = template.indexOf(':', i1 + 9);
467 throw new SvcLogicException(
468 "Template error: Context variable name followed by : is required after repeat");
471 // Find the closing }, store in i3
475 while (nn > 0 && i < template.length()) {
476 i3 = template.indexOf('}', i);
478 throw new SvcLogicException("Template error: Matching } not found");
480 int i32 = template.indexOf('{', i);
481 if (i32 >= 0 && i32 < i3) {
490 String var1 = template.substring(i1 + 9, i2);
491 String value1 = ctx.getAttribute(var1);
492 log.info(" {}:{}", var1, value1);
495 n = Integer.parseInt(value1);
496 } catch (NumberFormatException e) {
497 log.info("value1 not set or not a number, n will remain set at zero");
500 newTemplate.append(template.substring(k, i1));
502 String rpt = template.substring(i2 + 1, i3);
504 for (int ii = 0; ii < n; ii++) {
505 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
506 if (ii == n - 1 && ss.trim().endsWith(",")) {
507 int i4 = ss.lastIndexOf(',');
509 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
512 newTemplate.append(ss);
519 return newTemplate.toString();
522 return expandRepeats(ctx, newTemplate.toString(), level + 1);
525 protected String readFile(String fileName) throws SvcLogicException {
527 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
528 return new String(encoded, "UTF-8");
529 } catch (IOException | SecurityException e) {
530 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
534 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
535 Parameters p = new Parameters();
536 p.restapiUser = fp.user;
537 p.restapiPassword = fp.password;
538 p.oAuthConsumerKey = fp.oAuthConsumerKey;
539 p.oAuthVersion = fp.oAuthVersion;
540 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
541 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
542 p.authtype = fp.authtype;
543 return addAuthType(c, p);
546 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
547 if (p.authtype == AuthType.Unspecified) {
548 if (p.restapiUser != null && p.restapiPassword != null) {
549 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
550 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
551 && p.oAuthSignatureMethod != null) {
552 Feature oAuth1Feature = OAuth1ClientSupport
553 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
554 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
555 client.register(oAuth1Feature);
558 if (p.authtype == AuthType.DIGEST) {
559 if (p.restapiUser != null && p.restapiPassword != null) {
560 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
562 throw new SvcLogicException(
563 "oAUTH authentication type selected but all restapiUser and restapiPassword " +
564 "parameters doesn't exist", new Throwable());
566 } else if (p.authtype == AuthType.BASIC) {
567 if (p.restapiUser != null && p.restapiPassword != null) {
568 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
570 throw new SvcLogicException(
571 "oAUTH authentication type selected but all restapiUser and restapiPassword " +
572 "parameters doesn't exist", new Throwable());
574 } else if (p.authtype == AuthType.OAUTH) {
575 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
576 Feature oAuth1Feature = OAuth1ClientSupport
577 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
578 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
579 client.register(oAuth1Feature);
581 throw new SvcLogicException(
582 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
583 "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
591 * Receives the http response for the http request sent.
593 * @param request request msg
594 * @param p parameters
595 * @return HTTP response
596 * @throws SvcLogicException when sending http request fails
598 public HttpResponse sendHttpRequest(String request, Parameters p)
599 throws SvcLogicException {
601 SSLContext ssl = null;
602 if (p.ssl && p.restapiUrl.startsWith("https")) {
603 ssl = createSSLContext(p);
608 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
609 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
612 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
615 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
617 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
619 log.info("Sending request:");
621 long t1 = System.currentTimeMillis();
623 HttpResponse r = new HttpResponse();
626 if (!p.skipSending) {
627 String tt = p.format == Format.XML ? "application/xml" : "application/json";
628 String tt1 = tt + ";charset=UTF-8";
629 if (p.contentType != null) {
634 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
636 if (p.format == Format.NONE) {
637 invocationBuilder.header("", "");
640 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
641 String[] keyValuePairs = p.customHttpHeaders.split(",");
642 for (String singlePair : keyValuePairs) {
643 int equalPosition = singlePair.indexOf('=');
644 invocationBuilder.header(singlePair.substring(0, equalPosition),
645 singlePair.substring(equalPosition + 1, singlePair.length()));
649 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
654 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
655 } catch (ProcessingException | IllegalStateException e) {
656 throw new SvcLogicException("Exception while posting http request to client " +
657 e.getLocalizedMessage(), e);
660 r.code = response.getStatus();
661 r.headers = response.getStringHeaders();
662 EntityTag etag = response.getEntityTag();
664 r.message = etag.getValue();
666 if (response.hasEntity() && r.code != 204) {
667 r.body = response.readEntity(String.class);
671 long t2 = System.currentTimeMillis();
672 log.info("Response received. Time: {}", (t2 - t1));
673 log.info("HTTP response code: {}", r.code);
674 log.info("HTTP response message: {}", r.message);
675 logHeaders(r.headers);
676 log.info("HTTP response: {}", r.body);
681 protected SSLContext createSSLContext(Parameters p) {
682 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
683 System.setProperty("jsse.enableSNIExtension", "false");
684 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
685 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
687 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
689 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
690 KeyStore ks = KeyStore.getInstance("PKCS12");
691 char[] pwd = p.keyStorePassword.toCharArray();
695 SSLContext ctx = SSLContext.getInstance("TLS");
696 ctx.init(kmf.getKeyManagers(), null, null);
698 } catch (Exception e) {
699 log.error("Error creating SSLContext: {}", e.getMessage(), e);
704 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
707 resp.message = errorMessage;
708 String pp = prefix != null ? prefix + '.' : "";
709 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
710 ctx.setAttribute(pp + "response-message", resp.message);
713 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
714 String pp = prefix != null ? prefix + '.' : "";
715 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
716 ctx.setAttribute(pp + "response-message", r.message);
719 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
720 HttpResponse r = null;
722 FileParam p = getFileParameters(paramMap);
723 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
725 r = sendHttpData(data, p);
726 setResponseStatus(ctx, p.responsePrefix, r);
728 } catch (SvcLogicException | IOException e) {
729 log.error("Error sending the request: {}", e.getMessage(), e);
731 r = new HttpResponse();
733 r.message = e.getMessage();
734 String prefix = parseParam(paramMap, "responsePrefix", false, null);
735 setResponseStatus(ctx, prefix, r);
738 if (r != null && r.code >= 300) {
739 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
743 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
744 FileParam p = new FileParam();
745 p.fileName = parseParam(paramMap, "fileName", true, null);
746 p.url = parseParam(paramMap, "url", true, null);
747 p.user = parseParam(paramMap, "user", false, null);
748 p.password = parseParam(paramMap, "password", false, null);
749 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
750 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
751 String skipSendingStr = paramMap.get("skipSending");
752 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
753 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
754 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
755 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
756 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
757 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
761 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
764 UebParam p = getUebParameters(paramMap);
766 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
770 if (p.templateFileName == null) {
771 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
772 p.templateFileName = defaultUebTemplateFileName;
775 String reqTemplate = readFile(p.templateFileName);
776 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
777 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
779 r = postOnUeb(req, p);
780 setResponseStatus(ctx, p.responsePrefix, r);
781 if (r.body != null) {
782 ctx.setAttribute(pp + "httpResponse", r.body);
785 } catch (SvcLogicException e) {
786 log.error("Error sending the request: {}", e.getMessage(), e);
788 r = new HttpResponse();
790 r.message = e.getMessage();
791 String prefix = parseParam(paramMap, "responsePrefix", false, null);
792 setResponseStatus(ctx, prefix, r);
796 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
800 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
802 Client client = ClientBuilder.newBuilder().build();
803 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
804 client.property(ClientProperties.FOLLOW_REDIRECTS, true);
805 WebTarget webTarget = addAuthType(client, p).target(p.url);
807 log.info("Sending file");
808 long t1 = System.currentTimeMillis();
810 HttpResponse r = new HttpResponse();
813 if (!p.skipSending) {
814 String tt = "application/octet-stream";
815 Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
820 if (p.httpMethod == HttpMethod.POST) {
821 response = invocationBuilder.post(Entity.entity(data, tt));
822 } else if (p.httpMethod == HttpMethod.PUT) {
823 response = invocationBuilder.put(Entity.entity(data, tt));
825 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
827 } catch (ProcessingException e) {
828 throw new SvcLogicException("Exception while posting http request to client " +
829 e.getLocalizedMessage(), e);
832 r.code = response.getStatus();
833 r.headers = response.getStringHeaders();
834 EntityTag etag = response.getEntityTag();
836 r.message = etag.getValue();
838 if (response.hasEntity() && r.code != 204) {
839 r.body = response.readEntity(String.class);
843 String newUrl = response.getStringHeaders().getFirst("Location");
845 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
847 webTarget = client.target(newUrl);
848 invocationBuilder = webTarget.request(tt).accept(tt);
851 if (p.httpMethod == HttpMethod.POST) {
852 response = invocationBuilder.post(Entity.entity(data, tt));
853 } else if (p.httpMethod == HttpMethod.PUT) {
854 response = invocationBuilder.put(Entity.entity(data, tt));
856 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
858 } catch (ProcessingException e) {
859 throw new SvcLogicException("Exception while posting http request to client " +
860 e.getLocalizedMessage(), e);
863 r.code = response.getStatus();
864 etag = response.getEntityTag();
866 r.message = etag.getValue();
868 if (response.hasEntity() && r.code != 204) {
869 r.body = response.readEntity(String.class);
874 long t2 = System.currentTimeMillis();
875 log.info("Response received. Time: {}", (t2 - t1));
876 log.info("HTTP response code: {}", r.code);
877 log.info("HTTP response message: {}", r.message);
878 logHeaders(r.headers);
879 log.info("HTTP response: {}", r.body);
884 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
885 UebParam p = new UebParam();
886 p.topic = parseParam(paramMap, "topic", true, null);
887 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
888 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
889 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
890 String skipSendingStr = paramMap.get("skipSending");
891 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
895 protected void logProperties(Map<String, Object> mm) {
896 List<String> ll = new ArrayList<>();
897 for (Object o : mm.keySet()) {
900 Collections.sort(ll);
902 log.info("Properties:");
903 for (String name : ll) {
904 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
908 protected void logHeaders(MultivaluedMap<String, String> mm) {
909 log.info("HTTP response headers:");
915 List<String> ll = new ArrayList<>();
916 for (Object o : mm.keySet()) {
919 Collections.sort(ll);
921 for (String name : ll) {
922 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
926 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
927 String[] urls = uebServers.split(" ");
928 for (int i = 0; i < urls.length; i++) {
929 if (!urls[i].endsWith("/")) {
932 urls[i] += "events/" + p.topic;
935 Client client = ClientBuilder.newBuilder().build();
936 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
937 WebTarget webTarget = client.target(urls[0]);
939 log.info("UEB URL: {}", urls[0]);
940 log.info("Sending request:");
942 long t1 = System.currentTimeMillis();
944 HttpResponse r = new HttpResponse();
947 if (!p.skipSending) {
948 String tt = "application/json";
949 String tt1 = tt + ";charset=UTF-8";
952 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
955 response = invocationBuilder.post(Entity.entity(request, tt1));
956 } catch (ProcessingException e) {
957 throw new SvcLogicException("Exception while posting http request to client " +
958 e.getLocalizedMessage(), e);
960 r.code = response.getStatus();
961 r.headers = response.getStringHeaders();
962 if (response.hasEntity()) {
963 r.body = response.readEntity(String.class);
967 long t2 = System.currentTimeMillis();
968 log.info("Response received. Time: {}", (t2 - t1));
969 log.info("HTTP response code: {}", r.code);
970 logHeaders(r.headers);
971 log.info("HTTP response:\n {}", r.body);
976 public void setUebServers(String uebServers) {
977 this.uebServers = uebServers;
980 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
981 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
984 private static class FileParam {
986 public String fileName;
989 public String password;
990 public HttpMethod httpMethod;
991 public String responsePrefix;
992 public boolean skipSending;
993 public String oAuthConsumerKey;
994 public String oAuthConsumerSecret;
995 public String oAuthSignatureMethod;
996 public String oAuthVersion;
997 public AuthType authtype;
1000 private static class UebParam {
1002 public String topic;
1003 public String templateFileName;
1004 public String rootVarName;
1005 public String responsePrefix;
1006 public boolean skipSending;