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.List;
42 import java.util.Map.Entry;
43 import java.util.Properties;
45 import javax.net.ssl.HttpsURLConnection;
46 import javax.net.ssl.KeyManagerFactory;
47 import javax.net.ssl.SSLContext;
48 import javax.ws.rs.ProcessingException;
49 import javax.ws.rs.client.Client;
50 import javax.ws.rs.client.ClientBuilder;
51 import javax.ws.rs.client.Entity;
52 import javax.ws.rs.client.Invocation;
53 import javax.ws.rs.client.WebTarget;
54 import javax.ws.rs.core.EntityTag;
55 import javax.ws.rs.core.Feature;
56 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.MultivaluedMap;
58 import javax.ws.rs.core.Response;
59 import javax.ws.rs.core.UriBuilder;
60 import org.apache.commons.lang3.StringUtils;
61 import org.glassfish.jersey.client.ClientProperties;
62 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
63 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
64 import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
65 import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
66 import org.glassfish.jersey.media.multipart.MultiPart;
67 import org.glassfish.jersey.media.multipart.MultiPartFeature;
68 import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
69 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
70 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
71 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 public class RestapiCallNode implements SvcLogicJavaPlugin {
77 protected static final String DME2_PROPERTIES_FILE_NAME = "dme2.properties";
78 protected static final String UEB_PROPERTIES_FILE_NAME = "ueb.properties";
79 protected static final String DEFAULT_PROPERTIES_DIR = "/opt/onap/ccsdk/data/properties";
80 protected static final String PROPERTIES_DIR_KEY = "SDNC_CONFIG_DIR";
82 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
83 protected RetryPolicyStore retryPolicyStore;
84 private String uebServers;
85 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
87 private String responseReceivedMessage = "Response received. Time: {}";
88 private String responseHttpCodeMessage = "HTTP response code: {}";
89 private String requestPostingException = "Exception while posting http request to client ";
90 private static String skipSendingMessage = "skipSending";
91 private static String responsePrefix = "responsePrefix";
92 private static String restapiUrlString = "restapiUrl";
94 public RestapiCallNode() {
95 String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
97 try (FileInputStream in = new FileInputStream(configDir + "/" + DME2_PROPERTIES_FILE_NAME)) {
98 Properties props = new Properties();
100 retryPolicyStore = new RetryPolicyStore();
101 retryPolicyStore.setProxyServers(props.getProperty("proxyUrl"));
102 log.info("DME2 support enabled");
103 } catch (Exception e) {
104 log.warn("DME2 properties could not be read, DME2 support will not be enabled.", e);
107 try (FileInputStream in = new FileInputStream(configDir + "/" + UEB_PROPERTIES_FILE_NAME)) {
108 Properties props = new Properties();
110 uebServers = props.getProperty("servers");
111 log.info("UEB support enabled");
112 } catch (Exception e) {
113 log.warn("UEB properties could not be read, UEB support will not be enabled.", e);
118 * Returns parameters from the parameter map.
120 * @param paramMap parameter map
121 * @param p parameters instance
122 * @return parameters filed instance
123 * @throws SvcLogicException when svc logic exception occurs
125 public static Parameters getParameters(Map<String, String> paramMap,
127 throws SvcLogicException {
128 p.templateFileName = parseParam(paramMap, "templateFileName",
130 p.requestBody = parseParam(paramMap, "requestBody", false, null);
131 p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
132 validateUrl(p.restapiUrl);
133 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
134 p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
136 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey",
138 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret",
140 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod",
142 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
143 p.contentType = parseParam(paramMap, "contentType", false, null);
144 p.format = Format.fromString(parseParam(paramMap, "format", false,
146 p.authtype = fromString(parseParam(paramMap, "authType", false,
148 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
150 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
151 p.listNameList = getListNameList(paramMap);
152 String skipSendingStr = paramMap.get(skipSendingMessage);
153 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
154 p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
156 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName",
158 p.trustStorePassword = parseParam(paramMap, "trustStorePassword",
160 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName",
162 p.keyStorePassword = parseParam(paramMap, "keyStorePassword",
164 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null
165 && p.keyStoreFileName != null && p.keyStorePassword != null;
166 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders",
168 p.partner = parseParam(paramMap, "partner", false, null);
169 p.dumpHeaders = valueOf(parseParam(paramMap, "dumpHeaders",
171 p.returnRequestPayload = valueOf(parseParam(
172 paramMap, "returnRequestPayload", false, null));
173 p.accept = parseParam(paramMap, "accept",
175 p.multipartFormData = valueOf(parseParam(paramMap, "multipartFormData",
177 p.multipartFile = parseParam(paramMap, "multipartFile",
183 * Validates the given URL in the parameters.
185 * @param restapiUrl rest api URL
186 * @throws SvcLogicException when URL validation fails
188 private static void validateUrl(String restapiUrl)
189 throws SvcLogicException {
191 URI.create(restapiUrl);
192 } catch (IllegalArgumentException e) {
193 throw new SvcLogicException("Invalid input of url "
194 + e.getLocalizedMessage(), e);
199 * Returns the list of list name.
201 * @param paramMap parameters map
202 * @return list of list name
204 private static Set<String> getListNameList(Map<String, String> paramMap) {
205 Set<String> ll = new HashSet<>();
206 for (Map.Entry<String, String> entry : paramMap.entrySet()) {
207 if (entry.getKey().startsWith("listName")) {
208 ll.add(entry.getValue());
215 * Parses the parameter string map of property, validates if required,
216 * assigns default value if present and returns the value.
218 * @param paramMap string param map
219 * @param name name of the property
220 * @param required if value required
221 * @param def default value
222 * @return value of the property
223 * @throws SvcLogicException if required parameter value is empty
225 public static String parseParam(Map<String, String> paramMap, String name,
226 boolean required, String def)
227 throws SvcLogicException {
228 String s = paramMap.get(name);
230 if (s == null || s.trim().length() == 0) {
234 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
238 StringBuilder value = new StringBuilder();
240 int i1 = s.indexOf('%');
242 int i2 = s.indexOf('%', i1 + 1);
247 String varName = s.substring(i1 + 1, i2);
248 String varValue = System.getenv(varName);
249 if (varValue == null) {
250 varValue = "%" + varName + "%";
253 value.append(s.substring(i, i1));
254 value.append(varValue);
257 i1 = s.indexOf('%', i);
259 value.append(s.substring(i));
261 log.info("Parameter {}: [{}]", name, value);
262 return value.toString();
265 public RetryPolicyStore getRetryPolicyStore() {
266 return retryPolicyStore;
269 public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
270 this.retryPolicyStore = retryPolicyStore;
274 * Allows Directed Graphs the ability to interact with REST APIs.
275 * @param paramMap HashMap<String,String> of parameters passed by the DG to this function
277 * <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
279 * <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>
280 * <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>
281 * <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
282 * <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
283 * <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
284 * <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
285 * <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
286 * <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
287 * <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>
288 * <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
289 * <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>
290 * <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>
291 * <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>
292 * <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
293 * <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
294 * <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>
295 * <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
296 * <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
297 * <tr><td>returnRequestPayload</td><td>Optional</td><td>used to return payload built in the request</td><td>true or false</td></tr>
300 * @param ctx Reference to context memory
301 * @throws SvcLogicException
303 * @see String#split(String, int)
305 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
306 sendRequest(paramMap, ctx, null);
309 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
310 throws SvcLogicException {
312 RetryPolicy retryPolicy = null;
313 HttpResponse r = new HttpResponse();
315 Parameters p = getParameters(paramMap, new Parameters());
316 if (p.partner != null) {
317 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
319 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
322 if (p.templateFileName != null) {
323 String reqTemplate = readFile(p.templateFileName);
324 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
325 } else if (p.requestBody != null) {
328 r = sendHttpRequest(req, p);
329 setResponseStatus(ctx, p.responsePrefix, r);
331 if (p.dumpHeaders && r.headers != null) {
332 for (Entry<String, List<String>> a : r.headers.entrySet()) {
333 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
337 if (p.returnRequestPayload && req != null) {
338 ctx.setAttribute(pp + "httpRequest", req);
341 if (r.body != null && r.body.trim().length() > 0) {
342 ctx.setAttribute(pp + "httpResponse", r.body);
344 if (p.convertResponse) {
345 Map<String, String> mm = null;
346 if (p.format == Format.XML) {
347 mm = XmlParser.convertToProperties(r.body, p.listNameList);
348 } else if (p.format == Format.JSON) {
349 mm = JsonParser.convertToProperties(r.body);
353 for (Map.Entry<String, String> entry : mm.entrySet()) {
354 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
359 } catch (SvcLogicException e) {
360 boolean shouldRetry = false;
361 if (e.getCause().getCause() instanceof SocketException) {
365 log.error("Error sending the request: " + e.getMessage(), e);
366 String prefix = parseParam(paramMap, responsePrefix, false, null);
367 if (retryPolicy == null || !shouldRetry) {
368 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
370 if (retryCount == null) {
373 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
375 log.debug(retryMessage);
377 retryCount = retryCount + 1;
378 if (retryCount < retryPolicy.getMaximumRetries() + 1) {
379 URI uri = new URI(paramMap.get(restapiUrlString));
380 String hostname = uri.getHost();
381 String retryString = retryPolicy.getNextHostName(uri.toString());
382 URI uriTwo = new URI(retryString);
383 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
384 uriTwo.getScheme()).build();
385 paramMap.put(restapiUrlString, retryUri.toString());
386 log.debug("URL was set to {}", retryUri.toString());
387 log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
388 hostname, retryString);
389 log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
390 sendRequest(paramMap, ctx, retryCount);
392 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
393 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
395 } catch (Exception ex) {
396 log.error("Could not attempt retry.", ex);
397 String retryErrorMessage =
398 "Retry attempt has failed. No further retry shall be attempted, calling " +
399 "setFailureResponseStatus.";
400 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
405 if (r != null && r.code >= 300) {
406 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
410 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
411 throws SvcLogicException {
412 log.info("Building {} started", format);
413 long t1 = System.currentTimeMillis();
414 String originalTemplate = template;
416 template = expandRepeats(ctx, template, 1);
418 Map<String, String> mm = new HashMap<>();
419 for (String s : ctx.getAttributeKeySet()) {
420 mm.put(s, ctx.getAttribute(s));
423 StringBuilder ss = new StringBuilder();
425 while (i < template.length()) {
426 int i1 = template.indexOf("${", i);
428 ss.append(template.substring(i));
432 int i2 = template.indexOf('}', i1 + 2);
434 throw new SvcLogicException("Template error: Matching } not found");
437 String var1 = template.substring(i1 + 2, i2);
438 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
439 if (value1 == null || value1.trim().length() == 0) {
440 // delete the whole element (line)
441 int i3 = template.lastIndexOf('\n', i1);
445 int i4 = template.indexOf('\n', i1);
447 i4 = template.length();
451 ss.append(template.substring(i, i3));
455 ss.append(template.substring(i, i1)).append(value1);
460 String req = format == Format.XML
461 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(originalTemplate, ss.toString());
463 if (format == Format.JSON) {
464 req = XmlJsonUtil.removeLastCommaJson(req);
467 long t2 = System.currentTimeMillis();
468 log.info("Building {} completed. Time: {}", format, t2 - t1);
473 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
474 StringBuilder newTemplate = new StringBuilder();
476 while (k < template.length()) {
477 int i1 = template.indexOf("${repeat:", k);
479 newTemplate.append(template.substring(k));
483 int i2 = template.indexOf(':', i1 + 9);
485 throw new SvcLogicException(
486 "Template error: Context variable name followed by : is required after repeat");
489 // Find the closing }, store in i3
493 while (nn > 0 && i < template.length()) {
494 i3 = template.indexOf('}', i);
496 throw new SvcLogicException("Template error: Matching } not found");
498 int i32 = template.indexOf('{', i);
499 if (i32 >= 0 && i32 < i3) {
508 String var1 = template.substring(i1 + 9, i2);
509 String value1 = ctx.getAttribute(var1);
510 log.info(" {}:{}", var1, value1);
513 n = Integer.parseInt(value1);
514 } catch (NumberFormatException e) {
515 log.info("value1 not set or not a number, n will remain set at zero");
518 newTemplate.append(template.substring(k, i1));
520 String rpt = template.substring(i2 + 1, i3);
522 for (int ii = 0; ii < n; ii++) {
523 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
524 if (ii == n - 1 && ss.trim().endsWith(",")) {
525 int i4 = ss.lastIndexOf(',');
527 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
530 newTemplate.append(ss);
537 return newTemplate.toString();
540 return expandRepeats(ctx, newTemplate.toString(), level + 1);
543 protected String readFile(String fileName) throws SvcLogicException {
545 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
546 return new String(encoded, "UTF-8");
547 } catch (IOException | SecurityException e) {
548 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
552 protected Client addAuthType(Client c, FileParam fp) throws SvcLogicException {
553 Parameters p = new Parameters();
554 p.restapiUser = fp.user;
555 p.restapiPassword = fp.password;
556 p.oAuthConsumerKey = fp.oAuthConsumerKey;
557 p.oAuthVersion = fp.oAuthVersion;
558 p.oAuthConsumerSecret = fp.oAuthConsumerSecret;
559 p.oAuthSignatureMethod = fp.oAuthSignatureMethod;
560 p.authtype = fp.authtype;
561 return addAuthType(c, p);
564 public Client addAuthType(Client client, Parameters p) throws SvcLogicException {
565 if (p.authtype == AuthType.Unspecified) {
566 if (p.restapiUser != null && p.restapiPassword != null) {
567 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
568 } else if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null
569 && p.oAuthSignatureMethod != null) {
570 Feature oAuth1Feature = OAuth1ClientSupport
571 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
572 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
573 client.register(oAuth1Feature);
576 if (p.authtype == AuthType.DIGEST) {
577 if (p.restapiUser != null && p.restapiPassword != null) {
578 client.register(HttpAuthenticationFeature.digest(p.restapiUser, p.restapiPassword));
580 throw new SvcLogicException(
581 "oAUTH authentication type selected but all restapiUser and restapiPassword " +
582 "parameters doesn't exist", new Throwable());
584 } else if (p.authtype == AuthType.BASIC) {
585 if (p.restapiUser != null && p.restapiPassword != null) {
586 client.register(HttpAuthenticationFeature.basic(p.restapiUser, p.restapiPassword));
588 throw new SvcLogicException(
589 "oAUTH authentication type selected but all restapiUser and restapiPassword " +
590 "parameters doesn't exist", new Throwable());
592 } else if (p.authtype == AuthType.OAUTH) {
593 if (p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null) {
594 Feature oAuth1Feature = OAuth1ClientSupport
595 .builder(new ConsumerCredentials(p.oAuthConsumerKey, p.oAuthConsumerSecret))
596 .version(p.oAuthVersion).signatureMethod(p.oAuthSignatureMethod).feature().build();
597 client.register(oAuth1Feature);
599 throw new SvcLogicException(
600 "oAUTH authentication type selected but all oAuthConsumerKey, oAuthConsumerSecret " +
601 "and oAuthSignatureMethod parameters doesn't exist", new Throwable());
609 * Receives the http response for the http request sent.
611 * @param request request msg
612 * @param p parameters
613 * @return HTTP response
614 * @throws SvcLogicException when sending http request fails
616 public HttpResponse sendHttpRequest(String request, Parameters p)
617 throws SvcLogicException {
619 SSLContext ssl = null;
620 if (p.ssl && p.restapiUrl.startsWith("https")) {
621 ssl = createSSLContext(p);
626 HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
627 client = ClientBuilder.newBuilder().sslContext(ssl).hostnameVerifier((s, sslSession) -> true)
630 client = ClientBuilder.newBuilder().hostnameVerifier((s, sslSession) -> true)
633 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
634 // Needed to support additional HTTP methods such as PATCH
635 client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
637 WebTarget webTarget = addAuthType(client, p).target(p.restapiUrl);
639 log.info("Sending request:");
641 long t1 = System.currentTimeMillis();
643 HttpResponse r = new HttpResponse();
646 String accept = p.accept;
648 accept = p.format == Format.XML ? "application/xml" : "application/json";
651 String contentType = p.contentType;
652 if(contentType == null) {
653 contentType = accept + ";charset=UTF-8";
656 if (!p.skipSending && !p.multipartFormData) {
658 Invocation.Builder invocationBuilder = webTarget.request(contentType).accept(accept);
660 if (p.format == Format.NONE) {
661 invocationBuilder.header("", "");
664 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
665 String[] keyValuePairs = p.customHttpHeaders.split(",");
666 for (String singlePair : keyValuePairs) {
667 int equalPosition = singlePair.indexOf('=');
668 invocationBuilder.header(singlePair.substring(0, equalPosition),
669 singlePair.substring(equalPosition + 1, singlePair.length()));
673 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
675 invocationBuilder.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
680 response = invocationBuilder.method(p.httpMethod.toString(), entity(request, contentType));
681 } catch (ProcessingException | IllegalStateException e) {
682 throw new SvcLogicException(requestPostingException +
683 e.getLocalizedMessage(), e);
686 r.code = response.getStatus();
687 r.headers = response.getStringHeaders();
688 EntityTag etag = response.getEntityTag();
690 r.message = etag.getValue();
692 if (response.hasEntity() && r.code != 204) {
693 r.body = response.readEntity(String.class);
695 } else if (!p.skipSending && p.multipartFormData) {
697 WebTarget wt = client.register(MultiPartFeature.class).target(p.restapiUrl);
699 MultiPart multiPart = new MultiPart();
700 multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE);
702 FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
703 new File(p.multipartFile),
704 MediaType.APPLICATION_OCTET_STREAM_TYPE);
705 multiPart.bodyPart(fileDataBodyPart);
708 Invocation.Builder invocationBuilder = wt.request(contentType).accept(accept);
710 if (p.format == Format.NONE) {
711 invocationBuilder.header("", "");
714 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
715 String[] keyValuePairs = p.customHttpHeaders.split(",");
716 for (String singlePair : keyValuePairs) {
717 int equalPosition = singlePair.indexOf('=');
718 invocationBuilder.header(singlePair.substring(0, equalPosition),
719 singlePair.substring(equalPosition + 1, singlePair.length()));
723 invocationBuilder.header("X-ECOMP-RequestID", org.slf4j.MDC.get("X-ECOMP-RequestID"));
728 response = invocationBuilder.method(p.httpMethod.toString(), entity(multiPart, multiPart.getMediaType()));
729 } catch (ProcessingException | IllegalStateException e) {
730 throw new SvcLogicException(requestPostingException +
731 e.getLocalizedMessage(), e);
734 r.code = response.getStatus();
735 r.headers = response.getStringHeaders();
736 EntityTag etag = response.getEntityTag();
738 r.message = etag.getValue();
740 if (response.hasEntity() && r.code != 204) {
741 r.body = response.readEntity(String.class);
746 long t2 = System.currentTimeMillis();
747 log.info(responseReceivedMessage, t2 - t1);
748 log.info(responseHttpCodeMessage, r.code);
749 log.info("HTTP response message: {}", r.message);
750 logHeaders(r.headers);
751 log.info("HTTP response: {}", r.body);
756 protected SSLContext createSSLContext(Parameters p) {
757 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
758 System.setProperty("jsse.enableSNIExtension", "false");
759 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
760 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
762 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
764 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
765 KeyStore ks = KeyStore.getInstance("PKCS12");
766 char[] pwd = p.keyStorePassword.toCharArray();
770 SSLContext ctx = SSLContext.getInstance("TLS");
771 ctx.init(kmf.getKeyManagers(), null, null);
773 } catch (Exception e) {
774 log.error("Error creating SSLContext: {}", e.getMessage(), e);
779 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
782 resp.message = errorMessage;
783 String pp = prefix != null ? prefix + '.' : "";
784 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
785 ctx.setAttribute(pp + "response-message", resp.message);
788 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
789 String pp = prefix != null ? prefix + '.' : "";
790 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
791 ctx.setAttribute(pp + "response-message", r.message);
794 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
795 HttpResponse r = null;
797 FileParam p = getFileParameters(paramMap);
798 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
800 r = sendHttpData(data, p);
801 setResponseStatus(ctx, p.responsePrefix, r);
803 } catch (SvcLogicException | IOException e) {
804 log.error("Error sending the request: {}", e.getMessage(), e);
806 r = new HttpResponse();
808 r.message = e.getMessage();
809 String prefix = parseParam(paramMap, responsePrefix, false, null);
810 setResponseStatus(ctx, prefix, r);
813 if (r != null && r.code >= 300) {
814 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
818 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
819 FileParam p = new FileParam();
820 p.fileName = parseParam(paramMap, "fileName", true, null);
821 p.url = parseParam(paramMap, "url", true, null);
822 p.user = parseParam(paramMap, "user", false, null);
823 p.password = parseParam(paramMap, "password", false, null);
824 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
825 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
826 String skipSendingStr = paramMap.get(skipSendingMessage);
827 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
828 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
829 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
830 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
831 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
832 p.authtype = fromString(parseParam(paramMap, "authType", false, "unspecified"));
836 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
839 UebParam p = getUebParameters(paramMap);
841 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
845 if (p.templateFileName == null) {
846 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
847 p.templateFileName = defaultUebTemplateFileName;
850 String reqTemplate = readFile(p.templateFileName);
851 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
852 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
854 r = postOnUeb(req, p);
855 setResponseStatus(ctx, p.responsePrefix, r);
856 if (r.body != null) {
857 ctx.setAttribute(pp + "httpResponse", r.body);
860 } catch (SvcLogicException e) {
861 log.error("Error sending the request: {}", e.getMessage(), e);
863 r = new HttpResponse();
865 r.message = e.getMessage();
866 String prefix = parseParam(paramMap, responsePrefix, false, null);
867 setResponseStatus(ctx, prefix, r);
871 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
875 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
877 Client client = ClientBuilder.newBuilder().build();
878 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
879 client.property(ClientProperties.FOLLOW_REDIRECTS, true);
880 WebTarget webTarget = addAuthType(client, p).target(p.url);
882 log.info("Sending file");
883 long t1 = System.currentTimeMillis();
885 HttpResponse r = new HttpResponse();
888 if (!p.skipSending) {
889 String tt = "application/octet-stream";
890 Invocation.Builder invocationBuilder = webTarget.request(tt).accept(tt);
895 if (p.httpMethod == HttpMethod.POST) {
896 response = invocationBuilder.post(Entity.entity(data, tt));
897 } else if (p.httpMethod == HttpMethod.PUT) {
898 response = invocationBuilder.put(Entity.entity(data, tt));
900 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
902 } catch (ProcessingException e) {
903 throw new SvcLogicException(requestPostingException +
904 e.getLocalizedMessage(), e);
907 r.code = response.getStatus();
908 r.headers = response.getStringHeaders();
909 EntityTag etag = response.getEntityTag();
911 r.message = etag.getValue();
913 if (response.hasEntity() && r.code != 204) {
914 r.body = response.readEntity(String.class);
918 String newUrl = response.getStringHeaders().getFirst("Location");
920 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
922 webTarget = client.target(newUrl);
923 invocationBuilder = webTarget.request(tt).accept(tt);
926 if (p.httpMethod == HttpMethod.POST) {
927 response = invocationBuilder.post(Entity.entity(data, tt));
928 } else if (p.httpMethod == HttpMethod.PUT) {
929 response = invocationBuilder.put(Entity.entity(data, tt));
931 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
933 } catch (ProcessingException e) {
934 throw new SvcLogicException(requestPostingException +
935 e.getLocalizedMessage(), e);
938 r.code = response.getStatus();
939 etag = response.getEntityTag();
941 r.message = etag.getValue();
943 if (response.hasEntity() && r.code != 204) {
944 r.body = response.readEntity(String.class);
949 long t2 = System.currentTimeMillis();
950 log.info(responseReceivedMessage, t2 - t1);
951 log.info(responseHttpCodeMessage, r.code);
952 log.info("HTTP response message: {}", r.message);
953 logHeaders(r.headers);
954 log.info("HTTP response: {}", r.body);
959 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
960 UebParam p = new UebParam();
961 p.topic = parseParam(paramMap, "topic", true, null);
962 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
963 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
964 p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
965 String skipSendingStr = paramMap.get(skipSendingMessage);
966 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
970 protected void logProperties(Map<String, Object> mm) {
971 List<String> ll = new ArrayList<>();
972 for (Object o : mm.keySet()) {
975 Collections.sort(ll);
977 log.info("Properties:");
978 for (String name : ll) {
979 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
983 protected void logHeaders(MultivaluedMap<String, String> mm) {
984 log.info("HTTP response headers:");
990 List<String> ll = new ArrayList<>();
991 for (Object o : mm.keySet()) {
994 Collections.sort(ll);
996 for (String name : ll) {
997 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
1001 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
1002 String[] urls = uebServers.split(" ");
1003 for (int i = 0; i < urls.length; i++) {
1004 if (!urls[i].endsWith("/")) {
1007 urls[i] += "events/" + p.topic;
1010 Client client = ClientBuilder.newBuilder().build();
1011 client.property(ClientProperties.CONNECT_TIMEOUT, 5000);
1012 WebTarget webTarget = client.target(urls[0]);
1014 log.info("UEB URL: {}", urls[0]);
1015 log.info("Sending request:");
1017 long t1 = System.currentTimeMillis();
1019 HttpResponse r = new HttpResponse();
1022 if (!p.skipSending) {
1023 String tt = "application/json";
1024 String tt1 = tt + ";charset=UTF-8";
1027 Invocation.Builder invocationBuilder = webTarget.request(tt1).accept(tt);
1030 response = invocationBuilder.post(Entity.entity(request, tt1));
1031 } catch (ProcessingException e) {
1032 throw new SvcLogicException(requestPostingException +
1033 e.getLocalizedMessage(), e);
1035 r.code = response.getStatus();
1036 r.headers = response.getStringHeaders();
1037 if (response.hasEntity()) {
1038 r.body = response.readEntity(String.class);
1042 long t2 = System.currentTimeMillis();
1043 log.info(responseReceivedMessage, t2 - t1);
1044 log.info(responseHttpCodeMessage, r.code);
1045 logHeaders(r.headers);
1046 log.info("HTTP response:\n {}", r.body);
1051 public void setUebServers(String uebServers) {
1052 this.uebServers = uebServers;
1055 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
1056 this.defaultUebTemplateFileName = defaultUebTemplateFileName;
1059 private static class FileParam {
1061 public String fileName;
1064 public String password;
1065 public HttpMethod httpMethod;
1066 public String responsePrefix;
1067 public boolean skipSending;
1068 public String oAuthConsumerKey;
1069 public String oAuthConsumerSecret;
1070 public String oAuthSignatureMethod;
1071 public String oAuthVersion;
1072 public AuthType authtype;
1075 private static class UebParam {
1077 public String topic;
1078 public String templateFileName;
1079 public String rootVarName;
1080 public String responsePrefix;
1081 public boolean skipSending;