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);
135 r = sendHttpRequest(req, p);
136 setResponseStatus(ctx, p.responsePrefix, r);
138 if (p.dumpHeaders && r.headers != null) {
139 for (Entry<String, List<String>> a : r.headers.entrySet()) {
140 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
144 if (r.body != null && r.body.trim().length() > 0) {
145 ctx.setAttribute(pp + "httpResponse", r.body);
147 if (p.convertResponse) {
148 Map<String, String> mm = null;
149 if (p.format == Format.XML)
150 mm = XmlParser.convertToProperties(r.body, p.listNameList);
151 else if (p.format == Format.JSON)
152 mm = JsonParser.convertToProperties(r.body);
155 for (Map.Entry<String,String> entry : mm.entrySet())
156 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
159 } catch (SvcLogicException | JSONException e) {
160 boolean shouldRetry = false;
161 if (e.getCause().getCause() instanceof SocketException) {
165 log.error("Error sending the request: " + e.getMessage(), e);
166 String prefix = parseParam(paramMap, "responsePrefix", false, null);
167 if (retryPolicy == null || shouldRetry == false) {
168 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
170 if (retryCount == null) {
173 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
175 log.debug(retryMessage);
177 retryCount = retryCount + 1;
178 if (retryCount < retryPolicy.getMaximumRetries() + 1) {
179 URI uri = new URI(paramMap.get("restapiUrl"));
180 String hostname = uri.getHost();
181 String retryString = retryPolicy.getNextHostName(uri.toString());
182 URI uriTwo = new URI(retryString);
183 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
184 uriTwo.getScheme()).build();
185 paramMap.put("restapiUrl", retryUri.toString());
186 log.debug("URL was set to " + retryUri.toString());
187 log.debug("Failed to communicate with host " + hostname +
188 ". Request will be re-attempted using the host " + retryString + ".");
189 log.debug("This is retry attempt " + retryCount + " out of " + retryPolicy.getMaximumRetries());
190 sendRequest(paramMap, ctx, retryCount);
192 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
193 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
195 } catch (Exception ex) {
196 log.error("Could not attempt retry.", ex);
197 String retryErrorMessage =
198 "Retry attempt has failed. No further retry shall be attempted, calling " +
199 "setFailureResponseStatus.";
200 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
205 if (r != null && r.code >= 300)
206 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
209 protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
210 Parameters p = new Parameters();
211 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
212 p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
213 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
214 p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
215 p.contentType = parseParam(paramMap, "contentType", false, null);
216 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
217 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
218 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
219 p.listNameList = getListNameList(paramMap);
220 String skipSendingStr = paramMap.get("skipSending");
221 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
222 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
223 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
224 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
225 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
226 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
227 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
228 p.keyStorePassword != null;
229 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
230 p.partner = parseParam(paramMap, "partner", false, null);
231 p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
235 protected Set<String> getListNameList(Map<String, String> paramMap) {
236 Set<String> ll = new HashSet<>();
237 for (Map.Entry<String,String> entry : paramMap.entrySet())
238 if (entry.getKey().startsWith("listName"))
239 ll.add(entry.getValue());
243 protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
244 throws SvcLogicException {
245 String s = paramMap.get(name);
247 if (s == null || s.trim().length() == 0) {
250 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
256 int i1 = s.indexOf('%');
258 int i2 = s.indexOf('%', i1 + 1);
262 String varName = s.substring(i1 + 1, i2);
263 String varValue = System.getenv(varName);
264 if (varValue == null)
265 varValue = "%" + varName + "%";
267 value += s.substring(i, i1);
271 i1 = s.indexOf('%', i);
273 value += s.substring(i);
275 log.info("Parameter " + name + ": [" + value + "]");
279 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
280 throws SvcLogicException {
281 log.info("Building " + format + " started");
282 long t1 = System.currentTimeMillis();
284 template = expandRepeats(ctx, template, 1);
286 Map<String, String> mm = new HashMap<>();
287 for (String s : ctx.getAttributeKeySet())
288 mm.put(s, ctx.getAttribute(s));
290 StringBuilder ss = new StringBuilder();
292 while (i < template.length()) {
293 int i1 = template.indexOf("${", i);
295 ss.append(template.substring(i));
299 int i2 = template.indexOf('}', i1 + 2);
301 throw new SvcLogicException("Template error: Matching } not found");
303 String var1 = template.substring(i1 + 2, i2);
304 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
305 // log.info(" " + var1 + ": " + value1);
306 if (value1 == null || value1.trim().length() == 0) {
307 // delete the whole element (line)
308 int i3 = template.lastIndexOf('\n', i1);
311 int i4 = template.indexOf('\n', i1);
313 i4 = template.length();
316 ss.append(template.substring(i, i3));
319 ss.append(template.substring(i, i1)).append(value1);
324 String req = format == Format.XML
325 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
327 if (format == Format.JSON)
328 req = XmlJsonUtil.removeLastCommaJson(req);
330 long t2 = System.currentTimeMillis();
331 log.info("Building " + format + " completed. Time: " + (t2 - t1));
336 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
337 StringBuilder newTemplate = new StringBuilder();
339 while (k < template.length()) {
340 int i1 = template.indexOf("${repeat:", k);
342 newTemplate.append(template.substring(k));
346 int i2 = template.indexOf(':', i1 + 9);
348 throw new SvcLogicException(
349 "Template error: Context variable name followed by : is required after repeat");
351 // Find the closing }, store in i3
355 while (nn > 0 && i < template.length()) {
356 i3 = template.indexOf('}', i);
358 throw new SvcLogicException("Template error: Matching } not found");
359 int i32 = template.indexOf('{', i);
360 if (i32 >= 0 && i32 < i3) {
369 String var1 = template.substring(i1 + 9, i2);
370 String value1 = ctx.getAttribute(var1);
371 log.info(" " + var1 + ": " + value1);
374 n = Integer.parseInt(value1);
375 } catch (NumberFormatException e) {
376 throw new SvcLogicException("Invalid input of repeat interval, should be an integer value " +
377 e.getLocalizedMessage(), e);
380 newTemplate.append(template.substring(k, i1));
382 String rpt = template.substring(i2 + 1, i3);
384 for (int ii = 0; ii < n; ii++) {
385 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
386 if (ii == n - 1 && ss.trim().endsWith(",")) {
387 int i4 = ss.lastIndexOf(',');
389 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
391 newTemplate.append(ss);
398 return newTemplate.toString();
400 return expandRepeats(ctx, newTemplate.toString(), level + 1);
403 protected String readFile(String fileName) throws SvcLogicException {
405 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
406 return new String(encoded, "UTF-8");
407 } catch (IOException | SecurityException e) {
408 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
412 protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
414 ClientConfig config = new DefaultClientConfig();
415 SSLContext ssl = null;
416 if (p.ssl && p.restapiUrl.startsWith("https"))
417 ssl = createSSLContext(p);
419 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
422 public boolean verify(String hostname, SSLSession session) {
427 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
428 new HTTPSProperties(hostnameVerifier, ssl));
431 logProperties(config.getProperties());
433 Client client = Client.create(config);
434 client.setConnectTimeout(5000);
435 if (p.restapiUser != null)
436 client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
437 WebResource webResource = client.resource(p.restapiUrl);
439 log.info("Sending request:");
441 long t1 = System.currentTimeMillis();
443 HttpResponse r = new HttpResponse();
446 if (!p.skipSending) {
447 String tt = p.format == Format.XML ? "application/xml" : "application/json";
448 String tt1 = tt + ";charset=UTF-8";
449 if (p.contentType != null) {
454 WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
456 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
457 String[] keyValuePairs = p.customHttpHeaders.split(",");
458 for (String singlePair : keyValuePairs) {
459 int equalPosition = singlePair.indexOf('=');
460 webResourceBuilder.header(singlePair.substring(0, equalPosition),
461 singlePair.substring(equalPosition + 1, singlePair.length()));
465 webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
467 ClientResponse response;
470 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
471 } catch (UniformInterfaceException | ClientHandlerException e) {
472 throw new SvcLogicException("Exception while sending http request to client "
473 + e.getLocalizedMessage(), e);
476 r.code = response.getStatus();
477 r.headers = response.getHeaders();
478 EntityTag etag = response.getEntityTag();
480 r.message = etag.getValue();
481 if (response.hasEntity() && r.code != 204)
482 r.body = response.getEntity(String.class);
485 long t2 = System.currentTimeMillis();
486 log.info("Response received. Time: " + (t2 - t1));
487 log.info("HTTP response code: " + r.code);
488 log.info("HTTP response message: " + r.message);
489 logHeaders(r.headers);
490 log.info("HTTP response: " + r.body);
495 protected SSLContext createSSLContext(Parameters p) {
496 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
497 System.setProperty("jsse.enableSNIExtension", "false");
498 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
499 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
501 HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
504 public boolean verify(String string, SSLSession ssls) {
509 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
510 KeyStore ks = KeyStore.getInstance("PKCS12");
511 char[] pwd = p.keyStorePassword.toCharArray();
515 SSLContext ctx = SSLContext.getInstance("TLS");
516 ctx.init(kmf.getKeyManagers(), null, null);
518 } catch (Exception e) {
519 log.error("Error creating SSLContext: " + e.getMessage(), e);
524 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
527 resp.message = errorMessage;
528 String pp = prefix != null ? prefix + '.' : "";
529 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
530 ctx.setAttribute(pp + "response-message", resp.message);
533 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
534 String pp = prefix != null ? prefix + '.' : "";
535 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
536 ctx.setAttribute(pp + "response-message", r.message);
539 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
540 HttpResponse r = null;
542 FileParam p = getFileParameters(paramMap);
543 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
545 r = sendHttpData(data, p);
546 setResponseStatus(ctx, p.responsePrefix, r);
548 } catch (SvcLogicException | IOException e) {
549 log.error("Error sending the request: " + e.getMessage(), e);
551 r = new HttpResponse();
553 r.message = e.getMessage();
554 String prefix = parseParam(paramMap, "responsePrefix", false, null);
555 setResponseStatus(ctx, prefix, r);
558 if (r != null && r.code >= 300)
559 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
562 private static class FileParam {
564 public String fileName;
567 public String password;
568 public HttpMethod httpMethod;
569 public String responsePrefix;
570 public boolean skipSending;
573 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
574 FileParam p = new FileParam();
575 p.fileName = parseParam(paramMap, "fileName", true, null);
576 p.url = parseParam(paramMap, "url", true, null);
577 p.user = parseParam(paramMap, "user", false, null);
578 p.password = parseParam(paramMap, "password", false, null);
579 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
580 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
581 String skipSendingStr = paramMap.get("skipSending");
582 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
586 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
587 Client client = Client.create();
588 client.setConnectTimeout(5000);
589 client.setFollowRedirects(true);
591 client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
592 WebResource webResource = client.resource(p.url);
594 log.info("Sending file");
595 long t1 = System.currentTimeMillis();
597 HttpResponse r = new HttpResponse();
600 if (!p.skipSending) {
601 String tt = "application/octet-stream";
603 ClientResponse response;
605 if (p.httpMethod == HttpMethod.POST)
606 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
607 else if (p.httpMethod == HttpMethod.PUT)
608 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
610 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
611 } catch (UniformInterfaceException | ClientHandlerException e) {
612 throw new SvcLogicException("Exception while sending http request to client " +
613 e.getLocalizedMessage(), e);
616 r.code = response.getStatus();
617 r.headers = response.getHeaders();
618 EntityTag etag = response.getEntityTag();
620 r.message = etag.getValue();
621 if (response.hasEntity() && r.code != 204)
622 r.body = response.getEntity(String.class);
625 String newUrl = response.getHeaders().getFirst("Location");
627 log.info("Got response code 301. Sending same request to URL: " + newUrl);
629 webResource = client.resource(newUrl);
632 if (p.httpMethod == HttpMethod.POST)
633 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
634 else if (p.httpMethod == HttpMethod.PUT)
635 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
637 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
638 } catch (UniformInterfaceException | ClientHandlerException e) {
639 throw new SvcLogicException("Exception while sending http request to client " +
640 e.getLocalizedMessage(), e);
643 r.code = response.getStatus();
644 etag = response.getEntityTag();
646 r.message = etag.getValue();
647 if (response.hasEntity() && r.code != 204)
648 r.body = response.getEntity(String.class);
652 long t2 = System.currentTimeMillis();
653 log.info("Response received. Time: " + (t2 - t1));
654 log.info("HTTP response code: " + r.code);
655 log.info("HTTP response message: " + r.message);
656 logHeaders(r.headers);
657 log.info("HTTP response: " + r.body);
662 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
665 UebParam p = getUebParameters(paramMap);
667 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
671 if (p.templateFileName == null) {
672 log.info("No template file name specified. Using default UEB template: " + defaultUebTemplateFileName);
673 p.templateFileName = defaultUebTemplateFileName;
676 String reqTemplate = readFile(p.templateFileName);
677 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
678 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
680 r = postOnUeb(req, p);
681 setResponseStatus(ctx, p.responsePrefix, r);
683 ctx.setAttribute(pp + "httpResponse", r.body);
685 } catch (SvcLogicException e) {
686 log.error("Error sending the request: " + e.getMessage(), e);
688 r = new HttpResponse();
690 r.message = e.getMessage();
691 String prefix = parseParam(paramMap, "responsePrefix", false, null);
692 setResponseStatus(ctx, prefix, r);
696 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
699 private static class UebParam {
702 public String templateFileName;
703 public String rootVarName;
704 public String responsePrefix;
705 public boolean skipSending;
708 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
709 UebParam p = new UebParam();
710 p.topic = parseParam(paramMap, "topic", true, null);
711 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
712 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
713 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
714 String skipSendingStr = paramMap.get("skipSending");
715 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
719 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
720 String[] urls = uebServers.split(" ");
721 for (int i = 0; i < urls.length; i++) {
722 if (!urls[i].endsWith("/"))
724 urls[i] += "events/" + p.topic;
727 Client client = Client.create();
728 client.setConnectTimeout(5000);
729 WebResource webResource = client.resource(urls[0]);
731 log.info("UEB URL: " + urls[0]);
732 log.info("Sending request:");
734 long t1 = System.currentTimeMillis();
736 HttpResponse r = new HttpResponse();
739 if (!p.skipSending) {
740 String tt = "application/json";
741 String tt1 = tt + ";charset=UTF-8";
743 ClientResponse response;
746 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
747 } catch (UniformInterfaceException | ClientHandlerException e) {
748 throw new SvcLogicException("Exception while posting http request to client " +
749 e.getLocalizedMessage(), e);
752 r.code = response.getStatus();
753 r.headers = response.getHeaders();
754 if (response.hasEntity())
755 r.body = response.getEntity(String.class);
758 long t2 = System.currentTimeMillis();
759 log.info("Response received. Time: " + (t2 - t1));
760 log.info("HTTP response code: " + r.code);
761 logHeaders(r.headers);
762 log.info("HTTP response:\n" + r.body);
767 protected void logProperties(Map<String, Object> mm) {
768 List<String> ll = new ArrayList<>();
769 for (Object o : mm.keySet())
771 Collections.sort(ll);
773 log.info("Properties:");
774 for (String name : ll)
775 log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
778 protected void logHeaders(MultivaluedMap<String, String> mm) {
779 log.info("HTTP response headers:");
784 List<String> ll = new ArrayList<>();
785 for (Object o : mm.keySet())
787 Collections.sort(ll);
789 for (String name : ll)
790 log.info("--- " + name + ": " + String.valueOf(mm.get(name)));
793 public void setUebServers(String uebServers) {
794 this.uebServers = uebServers;
797 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
798 this.defaultUebTemplateFileName = defaultUebTemplateFileName;