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 com.sun.jersey.api.client.ClientHandlerException;
25 import com.sun.jersey.api.client.UniformInterfaceException;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.net.SocketException;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.security.KeyStore;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
39 import java.util.Map.Entry;
42 import javax.net.ssl.HostnameVerifier;
43 import javax.net.ssl.HttpsURLConnection;
44 import javax.net.ssl.KeyManagerFactory;
45 import javax.net.ssl.SSLContext;
46 import javax.net.ssl.SSLSession;
47 import javax.ws.rs.core.EntityTag;
48 import javax.ws.rs.core.MultivaluedMap;
49 import javax.ws.rs.core.UriBuilder;
51 import org.apache.commons.lang3.StringUtils;
52 import org.codehaus.jettison.json.JSONException;
53 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
54 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import com.sun.jersey.api.client.Client;
60 import com.sun.jersey.api.client.ClientResponse;
61 import com.sun.jersey.api.client.WebResource;
62 import com.sun.jersey.api.client.config.ClientConfig;
63 import com.sun.jersey.api.client.config.DefaultClientConfig;
64 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
65 import com.sun.jersey.client.urlconnection.HTTPSProperties;
67 public class RestapiCallNode implements SvcLogicJavaPlugin {
69 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
71 private String uebServers;
72 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
73 protected RetryPolicyStore retryPolicyStore;
75 protected RetryPolicyStore getRetryPolicyStore() {
76 return retryPolicyStore;
79 public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
80 this.retryPolicyStore = retryPolicyStore;
83 public RestapiCallNode() {
88 * Allows Directed Graphs the ability to interact with REST APIs.
89 * @param parameters HashMap<String,String> of parameters passed by the DG to this function
91 * <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
93 * <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>
94 * <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>
95 * <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
96 * <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
97 * <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>
98 * <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
99 * <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>
100 * <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>
101 * <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>
102 * <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
103 * <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
104 * <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>
105 * <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
106 * <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
109 * @param ctx Reference to context memory
110 * @throws SvcLogicException
112 * @see String#split(String, int)
114 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
115 sendRequest(paramMap, ctx, null);
118 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
119 throws SvcLogicException {
121 RetryPolicy retryPolicy = null;
122 HttpResponse r = new HttpResponse();
124 Parameters p = getParameters(paramMap);
125 if (p.partner != null) {
126 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
128 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
131 if (p.templateFileName != null) {
132 String reqTemplate = readFile(p.templateFileName);
133 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
134 } else if (p.requestBody != null) {
137 r = sendHttpRequest(req, p);
138 setResponseStatus(ctx, p.responsePrefix, r);
140 if (p.dumpHeaders && r.headers != null) {
141 for (Entry<String, List<String>> a : r.headers.entrySet()) {
142 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
146 if (r.body != null && r.body.trim().length() > 0) {
147 ctx.setAttribute(pp + "httpResponse", r.body);
149 if (p.convertResponse) {
150 Map<String, String> mm = null;
151 if (p.format == Format.XML)
152 mm = XmlParser.convertToProperties(r.body, p.listNameList);
153 else if (p.format == Format.JSON)
154 mm = JsonParser.convertToProperties(r.body);
157 for (Map.Entry<String,String> entry : mm.entrySet())
158 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
161 } catch (SvcLogicException e) {
162 boolean shouldRetry = false;
163 if (e.getCause().getCause() instanceof SocketException) {
167 log.error("Error sending the request: " + e.getMessage(), e);
168 String prefix = parseParam(paramMap, "responsePrefix", false, null);
169 if (retryPolicy == null || shouldRetry == false) {
170 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
172 if (retryCount == null) {
175 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
177 log.debug(retryMessage);
179 retryCount = retryCount + 1;
180 if (retryCount < retryPolicy.getMaximumRetries() + 1) {
181 URI uri = new URI(paramMap.get("restapiUrl"));
182 String hostname = uri.getHost();
183 String retryString = retryPolicy.getNextHostName(uri.toString());
184 URI uriTwo = new URI(retryString);
185 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
186 uriTwo.getScheme()).build();
187 paramMap.put("restapiUrl", retryUri.toString());
188 log.debug("URL was set to {}", retryUri.toString());
189 log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
190 hostname, retryString);
191 log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
192 sendRequest(paramMap, ctx, retryCount);
194 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
195 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
197 } catch (Exception ex) {
198 log.error("Could not attempt retry.", ex);
199 String retryErrorMessage =
200 "Retry attempt has failed. No further retry shall be attempted, calling " +
201 "setFailureResponseStatus.";
202 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
207 if (r != null && r.code >= 300)
208 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
211 protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
212 Parameters p = new Parameters();
213 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
214 p.requestBody = parseParam(paramMap, "requestBody", false, null);
215 p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
216 validateUrl(p.restapiUrl);
217 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
218 p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
219 p.contentType = parseParam(paramMap, "contentType", false, null);
220 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
221 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
222 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
223 p.listNameList = getListNameList(paramMap);
224 String skipSendingStr = paramMap.get("skipSending");
225 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
226 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
227 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
228 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
229 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
230 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
231 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
232 p.keyStorePassword != null;
233 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
234 p.partner = parseParam(paramMap, "partner", false, null);
235 p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
239 private void validateUrl(String restapiUrl) throws SvcLogicException {
241 URI.create(restapiUrl);
242 } catch (IllegalArgumentException e) {
243 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
247 protected Set<String> getListNameList(Map<String, String> paramMap) {
248 Set<String> ll = new HashSet<>();
249 for (Map.Entry<String,String> entry : paramMap.entrySet())
250 if (entry.getKey().startsWith("listName"))
251 ll.add(entry.getValue());
255 protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
256 throws SvcLogicException {
257 String s = paramMap.get(name);
259 if (s == null || s.trim().length() == 0) {
262 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
266 StringBuilder value = new StringBuilder();
268 int i1 = s.indexOf('%');
270 int i2 = s.indexOf('%', i1 + 1);
274 String varName = s.substring(i1 + 1, i2);
275 String varValue = System.getenv(varName);
276 if (varValue == null)
277 varValue = "%" + varName + "%";
279 value.append(s.substring(i, i1));
280 value.append(varValue);
283 i1 = s.indexOf('%', i);
285 value.append(s.substring(i));
287 log.info("Parameter {}: [{}]", name, value);
288 return value.toString();
291 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
292 throws SvcLogicException {
293 log.info("Building {} started", format);
294 long t1 = System.currentTimeMillis();
296 template = expandRepeats(ctx, template, 1);
298 Map<String, String> mm = new HashMap<>();
299 for (String s : ctx.getAttributeKeySet())
300 mm.put(s, ctx.getAttribute(s));
302 StringBuilder ss = new StringBuilder();
304 while (i < template.length()) {
305 int i1 = template.indexOf("${", i);
307 ss.append(template.substring(i));
311 int i2 = template.indexOf('}', i1 + 2);
313 throw new SvcLogicException("Template error: Matching } not found");
315 String var1 = template.substring(i1 + 2, i2);
316 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
317 // log.info(" " + var1 + ": " + value1);
318 if (value1 == null || value1.trim().length() == 0) {
319 // delete the whole element (line)
320 int i3 = template.lastIndexOf('\n', i1);
323 int i4 = template.indexOf('\n', i1);
325 i4 = template.length();
328 ss.append(template.substring(i, i3));
331 ss.append(template.substring(i, i1)).append(value1);
336 String req = format == Format.XML
337 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
339 if (format == Format.JSON)
340 req = XmlJsonUtil.removeLastCommaJson(req);
342 long t2 = System.currentTimeMillis();
343 log.info("Building {} completed. Time: {}", format, (t2 - t1));
348 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
349 StringBuilder newTemplate = new StringBuilder();
351 while (k < template.length()) {
352 int i1 = template.indexOf("${repeat:", k);
354 newTemplate.append(template.substring(k));
358 int i2 = template.indexOf(':', i1 + 9);
360 throw new SvcLogicException(
361 "Template error: Context variable name followed by : is required after repeat");
363 // Find the closing }, store in i3
367 while (nn > 0 && i < template.length()) {
368 i3 = template.indexOf('}', i);
370 throw new SvcLogicException("Template error: Matching } not found");
371 int i32 = template.indexOf('{', i);
372 if (i32 >= 0 && i32 < i3) {
381 String var1 = template.substring(i1 + 9, i2);
382 String value1 = ctx.getAttribute(var1);
383 log.info(" {}:{}", var1, value1);
386 n = Integer.parseInt(value1);
387 } catch (NumberFormatException e) {
388 log.info("value1 not set or not a number, n will remain set at zero");
391 newTemplate.append(template.substring(k, i1));
393 String rpt = template.substring(i2 + 1, i3);
395 for (int ii = 0; ii < n; ii++) {
396 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
397 if (ii == n - 1 && ss.trim().endsWith(",")) {
398 int i4 = ss.lastIndexOf(',');
400 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
402 newTemplate.append(ss);
409 return newTemplate.toString();
411 return expandRepeats(ctx, newTemplate.toString(), level + 1);
414 protected String readFile(String fileName) throws SvcLogicException {
416 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
417 return new String(encoded, "UTF-8");
418 } catch (IOException | SecurityException e) {
419 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
423 protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
425 ClientConfig config = new DefaultClientConfig();
426 SSLContext ssl = null;
427 if (p.ssl && p.restapiUrl.startsWith("https"))
428 ssl = createSSLContext(p);
430 HostnameVerifier hostnameVerifier = (hostname, session) -> true;
432 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
433 new HTTPSProperties(hostnameVerifier, ssl));
436 logProperties(config.getProperties());
438 Client client = Client.create(config);
439 client.setConnectTimeout(5000);
440 if (p.restapiUser != null)
441 client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
442 WebResource webResource = client.resource(p.restapiUrl);
444 log.info("Sending request:");
446 long t1 = System.currentTimeMillis();
448 HttpResponse r = new HttpResponse();
451 if (!p.skipSending) {
452 String tt = p.format == Format.XML ? "application/xml" : "application/json";
453 String tt1 = tt + ";charset=UTF-8";
454 if (p.contentType != null) {
459 WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
461 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
462 String[] keyValuePairs = p.customHttpHeaders.split(",");
463 for (String singlePair : keyValuePairs) {
464 int equalPosition = singlePair.indexOf('=');
465 webResourceBuilder.header(singlePair.substring(0, equalPosition),
466 singlePair.substring(equalPosition + 1, singlePair.length()));
470 webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
472 ClientResponse response;
475 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
476 } catch (UniformInterfaceException | ClientHandlerException e) {
477 throw new SvcLogicException("Exception while sending http request to client "
478 + e.getLocalizedMessage(), e);
481 r.code = response.getStatus();
482 r.headers = response.getHeaders();
483 EntityTag etag = response.getEntityTag();
485 r.message = etag.getValue();
486 if (response.hasEntity() && r.code != 204)
487 r.body = response.getEntity(String.class);
490 long t2 = System.currentTimeMillis();
491 log.info("Response received. Time: {}", (t2 - t1));
492 log.info("HTTP response code: {}", r.code);
493 log.info("HTTP response message: {}", r.message);
494 logHeaders(r.headers);
495 log.info("HTTP response: {}", r.body);
500 protected SSLContext createSSLContext(Parameters p) {
501 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
502 System.setProperty("jsse.enableSNIExtension", "false");
503 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
504 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
506 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
508 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
509 KeyStore ks = KeyStore.getInstance("PKCS12");
510 char[] pwd = p.keyStorePassword.toCharArray();
514 SSLContext ctx = SSLContext.getInstance("TLS");
515 ctx.init(kmf.getKeyManagers(), null, null);
517 } catch (Exception e) {
518 log.error("Error creating SSLContext: {}", e.getMessage(), e);
523 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
526 resp.message = errorMessage;
527 String pp = prefix != null ? prefix + '.' : "";
528 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
529 ctx.setAttribute(pp + "response-message", resp.message);
532 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
533 String pp = prefix != null ? prefix + '.' : "";
534 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
535 ctx.setAttribute(pp + "response-message", r.message);
538 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
539 HttpResponse r = null;
541 FileParam p = getFileParameters(paramMap);
542 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
544 r = sendHttpData(data, p);
545 setResponseStatus(ctx, p.responsePrefix, r);
547 } catch (SvcLogicException | IOException e) {
548 log.error("Error sending the request: {}", e.getMessage(), e);
550 r = new HttpResponse();
552 r.message = e.getMessage();
553 String prefix = parseParam(paramMap, "responsePrefix", false, null);
554 setResponseStatus(ctx, prefix, r);
557 if (r != null && r.code >= 300)
558 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
561 private static class FileParam {
563 public String fileName;
566 public String password;
567 public HttpMethod httpMethod;
568 public String responsePrefix;
569 public boolean skipSending;
572 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
573 FileParam p = new FileParam();
574 p.fileName = parseParam(paramMap, "fileName", true, null);
575 p.url = parseParam(paramMap, "url", true, null);
576 p.user = parseParam(paramMap, "user", false, null);
577 p.password = parseParam(paramMap, "password", false, null);
578 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
579 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
580 String skipSendingStr = paramMap.get("skipSending");
581 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
585 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
586 Client client = Client.create();
587 client.setConnectTimeout(5000);
588 client.setFollowRedirects(true);
590 client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
591 WebResource webResource = client.resource(p.url);
593 log.info("Sending file");
594 long t1 = System.currentTimeMillis();
596 HttpResponse r = new HttpResponse();
599 if (!p.skipSending) {
600 String tt = "application/octet-stream";
602 ClientResponse response;
604 if (p.httpMethod == HttpMethod.POST)
605 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
606 else if (p.httpMethod == HttpMethod.PUT)
607 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
609 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
610 } catch (UniformInterfaceException | ClientHandlerException e) {
611 throw new SvcLogicException("Exception while sending http request to client " +
612 e.getLocalizedMessage(), e);
615 r.code = response.getStatus();
616 r.headers = response.getHeaders();
617 EntityTag etag = response.getEntityTag();
619 r.message = etag.getValue();
620 if (response.hasEntity() && r.code != 204)
621 r.body = response.getEntity(String.class);
624 String newUrl = response.getHeaders().getFirst("Location");
626 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
628 webResource = client.resource(newUrl);
631 if (p.httpMethod == HttpMethod.POST)
632 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
633 else if (p.httpMethod == HttpMethod.PUT)
634 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
636 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
637 } catch (UniformInterfaceException | ClientHandlerException e) {
638 throw new SvcLogicException("Exception while sending http request to client " +
639 e.getLocalizedMessage(), e);
642 r.code = response.getStatus();
643 etag = response.getEntityTag();
645 r.message = etag.getValue();
646 if (response.hasEntity() && r.code != 204)
647 r.body = response.getEntity(String.class);
651 long t2 = System.currentTimeMillis();
652 log.info("Response received. Time: {}", (t2 - t1));
653 log.info("HTTP response code: {}", r.code);
654 log.info("HTTP response message: {}", r.message);
655 logHeaders(r.headers);
656 log.info("HTTP response: {}", r.body);
661 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
664 UebParam p = getUebParameters(paramMap);
666 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
670 if (p.templateFileName == null) {
671 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
672 p.templateFileName = defaultUebTemplateFileName;
675 String reqTemplate = readFile(p.templateFileName);
676 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
677 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
679 r = postOnUeb(req, p);
680 setResponseStatus(ctx, p.responsePrefix, r);
682 ctx.setAttribute(pp + "httpResponse", r.body);
684 } catch (SvcLogicException e) {
685 log.error("Error sending the request: {}", e.getMessage(), e);
687 r = new HttpResponse();
689 r.message = e.getMessage();
690 String prefix = parseParam(paramMap, "responsePrefix", false, null);
691 setResponseStatus(ctx, prefix, r);
695 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
698 private static class UebParam {
701 public String templateFileName;
702 public String rootVarName;
703 public String responsePrefix;
704 public boolean skipSending;
707 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
708 UebParam p = new UebParam();
709 p.topic = parseParam(paramMap, "topic", true, null);
710 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
711 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
712 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
713 String skipSendingStr = paramMap.get("skipSending");
714 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
718 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
719 String[] urls = uebServers.split(" ");
720 for (int i = 0; i < urls.length; i++) {
721 if (!urls[i].endsWith("/"))
723 urls[i] += "events/" + p.topic;
726 Client client = Client.create();
727 client.setConnectTimeout(5000);
728 WebResource webResource = client.resource(urls[0]);
730 log.info("UEB URL: {}", urls[0]);
731 log.info("Sending request:");
733 long t1 = System.currentTimeMillis();
735 HttpResponse r = new HttpResponse();
738 if (!p.skipSending) {
739 String tt = "application/json";
740 String tt1 = tt + ";charset=UTF-8";
742 ClientResponse response;
745 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
746 } catch (UniformInterfaceException | ClientHandlerException e) {
747 throw new SvcLogicException("Exception while posting http request to client " +
748 e.getLocalizedMessage(), e);
751 r.code = response.getStatus();
752 r.headers = response.getHeaders();
753 if (response.hasEntity())
754 r.body = response.getEntity(String.class);
757 long t2 = System.currentTimeMillis();
758 log.info("Response received. Time: {}", (t2 - t1));
759 log.info("HTTP response code: {}", r.code);
760 logHeaders(r.headers);
761 log.info("HTTP response:\n {}", r.body);
766 protected void logProperties(Map<String, Object> mm) {
767 List<String> ll = new ArrayList<>();
768 for (Object o : mm.keySet())
770 Collections.sort(ll);
772 log.info("Properties:");
773 for (String name : ll)
774 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
777 protected void logHeaders(MultivaluedMap<String, String> mm) {
778 log.info("HTTP response headers:");
783 List<String> ll = new ArrayList<>();
784 for (Object o : mm.keySet())
786 Collections.sort(ll);
788 for (String name : ll)
789 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
792 public void setUebServers(String uebServers) {
793 this.uebServers = uebServers;
796 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
797 this.defaultUebTemplateFileName = defaultUebTemplateFileName;