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.oauth.client.OAuthClientFilter;
66 import com.sun.jersey.oauth.signature.OAuthParameters;
67 import com.sun.jersey.oauth.signature.OAuthSecrets;
68 import com.sun.jersey.client.urlconnection.HTTPSProperties;
70 public class RestapiCallNode implements SvcLogicJavaPlugin {
72 private static final Logger log = LoggerFactory.getLogger(RestapiCallNode.class);
74 private String uebServers;
75 private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
76 protected RetryPolicyStore retryPolicyStore;
78 protected RetryPolicyStore getRetryPolicyStore() {
79 return retryPolicyStore;
82 public void setRetryPolicyStore(RetryPolicyStore retryPolicyStore) {
83 this.retryPolicyStore = retryPolicyStore;
86 public RestapiCallNode() {
91 * Allows Directed Graphs the ability to interact with REST APIs.
92 * @param parameters HashMap<String,String> of parameters passed by the DG to this function
94 * <thead><th>parameter</th><th>Mandatory/Optional</th><th>description</th><th>example values</th></thead>
96 * <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>
97 * <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>
98 * <tr><td>restapiUser</td><td>Optional</td><td>user name to use for http basic authentication</td><td>sdnc_ws</td></tr>
99 * <tr><td>restapiPassword</td><td>Optional</td><td>unencrypted password to use for http basic authentication</td><td>plain_password</td></tr>
100 * <tr><td>oAuthConsumerKey</td><td>Optional</td><td>Consumer key to use for http oAuth authentication</td><td>plain_key</td></tr>
101 * <tr><td>oAuthConsumerSecret</td><td>Optional</td><td>Consumer secret to use for http oAuth authentication</td><td>plain_secret</td></tr>
102 * <tr><td>oAuthSignatureMethod</td><td>Optional</td><td>Consumer method to use for http oAuth authentication</td><td>method</td></tr>
103 * <tr><td>oAuthVersion</td><td>Optional</td><td>Version http oAuth authentication</td><td>version</td></tr>
104 * <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>
105 * <tr><td>format</td><td>Optional</td><td>should match request body format</td><td>json or xml</td></tr>
106 * <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>
107 * <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>
108 * <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>
109 * <tr><td>skipSending</td><td>Optional</td><td></td><td>true or false</td></tr>
110 * <tr><td>convertResponse </td><td>Optional</td><td>whether the response should be converted</td><td>true or false</td></tr>
111 * <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>
112 * <tr><td>dumpHeaders</td><td>Optional</td><td>when true writes http header content to context memory</td><td>true or false</td></tr>
113 * <tr><td>partner</td><td>Optional</td><td>needed for DME2 calls</td><td>dme2proxy</td></tr>
116 * @param ctx Reference to context memory
117 * @throws SvcLogicException
119 * @see String#split(String, int)
121 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
122 sendRequest(paramMap, ctx, null);
125 public void sendRequest(Map<String, String> paramMap, SvcLogicContext ctx, Integer retryCount)
126 throws SvcLogicException {
128 RetryPolicy retryPolicy = null;
129 HttpResponse r = new HttpResponse();
131 Parameters p = getParameters(paramMap);
132 if (p.partner != null) {
133 retryPolicy = retryPolicyStore.getRetryPolicy(p.partner);
135 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
138 if (p.templateFileName != null) {
139 String reqTemplate = readFile(p.templateFileName);
140 req = buildXmlJsonRequest(ctx, reqTemplate, p.format);
141 } else if (p.requestBody != null) {
144 r = sendHttpRequest(req, p);
145 setResponseStatus(ctx, p.responsePrefix, r);
147 if (p.dumpHeaders && r.headers != null) {
148 for (Entry<String, List<String>> a : r.headers.entrySet()) {
149 ctx.setAttribute(pp + "header." + a.getKey(), StringUtils.join(a.getValue(), ","));
153 if (r.body != null && r.body.trim().length() > 0) {
154 ctx.setAttribute(pp + "httpResponse", r.body);
156 if (p.convertResponse) {
157 Map<String, String> mm = null;
158 if (p.format == Format.XML)
159 mm = XmlParser.convertToProperties(r.body, p.listNameList);
160 else if (p.format == Format.JSON)
161 mm = JsonParser.convertToProperties(r.body);
164 for (Map.Entry<String,String> entry : mm.entrySet())
165 ctx.setAttribute(pp + entry.getKey(), entry.getValue());
168 } catch (SvcLogicException e) {
169 boolean shouldRetry = false;
170 if (e.getCause().getCause() instanceof SocketException) {
174 log.error("Error sending the request: " + e.getMessage(), e);
175 String prefix = parseParam(paramMap, "responsePrefix", false, null);
176 if (retryPolicy == null || shouldRetry == false) {
177 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
179 if (retryCount == null) {
182 String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
184 log.debug(retryMessage);
186 retryCount = retryCount + 1;
187 if (retryCount < retryPolicy.getMaximumRetries() + 1) {
188 URI uri = new URI(paramMap.get("restapiUrl"));
189 String hostname = uri.getHost();
190 String retryString = retryPolicy.getNextHostName(uri.toString());
191 URI uriTwo = new URI(retryString);
192 URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
193 uriTwo.getScheme()).build();
194 paramMap.put("restapiUrl", retryUri.toString());
195 log.debug("URL was set to {}", retryUri.toString());
196 log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
197 hostname, retryString);
198 log.debug("This is retry attempt {} out of {}", retryCount, retryPolicy.getMaximumRetries());
199 sendRequest(paramMap, ctx, retryCount);
201 log.debug("Maximum retries reached, calling setFailureResponseStatus.");
202 setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
204 } catch (Exception ex) {
205 log.error("Could not attempt retry.", ex);
206 String retryErrorMessage =
207 "Retry attempt has failed. No further retry shall be attempted, calling " +
208 "setFailureResponseStatus.";
209 setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
214 if (r != null && r.code >= 300)
215 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
218 protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
219 Parameters p = new Parameters();
220 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
221 p.requestBody = parseParam(paramMap, "requestBody", false, null);
222 p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
223 validateUrl(p.restapiUrl);
224 p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
225 p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
226 p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
227 p.oAuthConsumerSecret = parseParam(paramMap, "oAuthConsumerSecret", false, null);
228 p.oAuthSignatureMethod = parseParam(paramMap, "oAuthSignatureMethod", false, null);
229 p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
230 p.contentType = parseParam(paramMap, "contentType", false, null);
231 p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
232 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
233 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
234 p.listNameList = getListNameList(paramMap);
235 String skipSendingStr = paramMap.get("skipSending");
236 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
237 p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
238 p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
239 p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
240 p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
241 p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
242 p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
243 p.keyStorePassword != null;
244 p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
245 p.partner = parseParam(paramMap, "partner", false, null);
246 p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
250 private void validateUrl(String restapiUrl) throws SvcLogicException {
252 URI.create(restapiUrl);
253 } catch (IllegalArgumentException e) {
254 throw new SvcLogicException("Invalid input of url " + e.getLocalizedMessage(), e);
258 protected Set<String> getListNameList(Map<String, String> paramMap) {
259 Set<String> ll = new HashSet<>();
260 for (Map.Entry<String,String> entry : paramMap.entrySet())
261 if (entry.getKey().startsWith("listName"))
262 ll.add(entry.getValue());
266 protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
267 throws SvcLogicException {
268 String s = paramMap.get(name);
270 if (s == null || s.trim().length() == 0) {
273 throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
277 StringBuilder value = new StringBuilder();
279 int i1 = s.indexOf('%');
281 int i2 = s.indexOf('%', i1 + 1);
285 String varName = s.substring(i1 + 1, i2);
286 String varValue = System.getenv(varName);
287 if (varValue == null)
288 varValue = "%" + varName + "%";
290 value.append(s.substring(i, i1));
291 value.append(varValue);
294 i1 = s.indexOf('%', i);
296 value.append(s.substring(i));
298 log.info("Parameter {}: [{}]", name, value);
299 return value.toString();
302 protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format)
303 throws SvcLogicException {
304 log.info("Building {} started", format);
305 long t1 = System.currentTimeMillis();
307 template = expandRepeats(ctx, template, 1);
309 Map<String, String> mm = new HashMap<>();
310 for (String s : ctx.getAttributeKeySet())
311 mm.put(s, ctx.getAttribute(s));
313 StringBuilder ss = new StringBuilder();
315 while (i < template.length()) {
316 int i1 = template.indexOf("${", i);
318 ss.append(template.substring(i));
322 int i2 = template.indexOf('}', i1 + 2);
324 throw new SvcLogicException("Template error: Matching } not found");
326 String var1 = template.substring(i1 + 2, i2);
327 String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
328 // log.info(" " + var1 + ": " + value1);
329 if (value1 == null || value1.trim().length() == 0) {
330 // delete the whole element (line)
331 int i3 = template.lastIndexOf('\n', i1);
334 int i4 = template.indexOf('\n', i1);
336 i4 = template.length();
339 ss.append(template.substring(i, i3));
342 ss.append(template.substring(i, i1)).append(value1);
347 String req = format == Format.XML
348 ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
350 if (format == Format.JSON)
351 req = XmlJsonUtil.removeLastCommaJson(req);
353 long t2 = System.currentTimeMillis();
354 log.info("Building {} completed. Time: {}", format, (t2 - t1));
359 protected String expandRepeats(SvcLogicContext ctx, String template, int level) throws SvcLogicException {
360 StringBuilder newTemplate = new StringBuilder();
362 while (k < template.length()) {
363 int i1 = template.indexOf("${repeat:", k);
365 newTemplate.append(template.substring(k));
369 int i2 = template.indexOf(':', i1 + 9);
371 throw new SvcLogicException(
372 "Template error: Context variable name followed by : is required after repeat");
374 // Find the closing }, store in i3
378 while (nn > 0 && i < template.length()) {
379 i3 = template.indexOf('}', i);
381 throw new SvcLogicException("Template error: Matching } not found");
382 int i32 = template.indexOf('{', i);
383 if (i32 >= 0 && i32 < i3) {
392 String var1 = template.substring(i1 + 9, i2);
393 String value1 = ctx.getAttribute(var1);
394 log.info(" {}:{}", var1, value1);
397 n = Integer.parseInt(value1);
398 } catch (NumberFormatException e) {
399 log.info("value1 not set or not a number, n will remain set at zero");
402 newTemplate.append(template.substring(k, i1));
404 String rpt = template.substring(i2 + 1, i3);
406 for (int ii = 0; ii < n; ii++) {
407 String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
408 if (ii == n - 1 && ss.trim().endsWith(",")) {
409 int i4 = ss.lastIndexOf(',');
411 ss = ss.substring(0, i4) + ss.substring(i4 + 1);
413 newTemplate.append(ss);
420 return newTemplate.toString();
422 return expandRepeats(ctx, newTemplate.toString(), level + 1);
425 protected String readFile(String fileName) throws SvcLogicException {
427 byte[] encoded = Files.readAllBytes(Paths.get(fileName));
428 return new String(encoded, "UTF-8");
429 } catch (IOException | SecurityException e) {
430 throw new SvcLogicException("Unable to read file " + fileName + e.getLocalizedMessage(), e);
434 protected HttpResponse sendHttpRequest(String request, Parameters p) throws SvcLogicException {
436 ClientConfig config = new DefaultClientConfig();
437 SSLContext ssl = null;
438 if (p.ssl && p.restapiUrl.startsWith("https"))
439 ssl = createSSLContext(p);
441 HostnameVerifier hostnameVerifier = (hostname, session) -> true;
443 config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
444 new HTTPSProperties(hostnameVerifier, ssl));
447 logProperties(config.getProperties());
449 Client client = Client.create(config);
450 client.setConnectTimeout(5000);
451 if (p.restapiUser != null && p.restapiPassword != null)
452 client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
453 else if(p.oAuthConsumerKey != null && p.oAuthConsumerSecret != null && p.oAuthSignatureMethod != null && p.oAuthVersion != null)
455 OAuthParameters params = new OAuthParameters()
456 .signatureMethod(p.oAuthSignatureMethod)
457 .consumerKey(p.oAuthConsumerKey)
458 .version(p.oAuthVersion);
460 OAuthSecrets secrets = new OAuthSecrets()
461 .consumerSecret(p.oAuthConsumerSecret);
462 client.addFilter(new OAuthClientFilter(client.getProviders(), params, secrets));
464 WebResource webResource = client.resource(p.restapiUrl);
466 log.info("Sending request:");
468 long t1 = System.currentTimeMillis();
470 HttpResponse r = new HttpResponse();
473 if (!p.skipSending) {
474 String tt = p.format == Format.XML ? "application/xml" : "application/json";
475 String tt1 = tt + ";charset=UTF-8";
476 if (p.contentType != null) {
481 WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
482 if(p.format == Format.NONE){
483 webResourceBuilder = webResource.header("","");
486 if (p.customHttpHeaders != null && p.customHttpHeaders.length() > 0) {
487 String[] keyValuePairs = p.customHttpHeaders.split(",");
488 for (String singlePair : keyValuePairs) {
489 int equalPosition = singlePair.indexOf('=');
490 webResourceBuilder.header(singlePair.substring(0, equalPosition),
491 singlePair.substring(equalPosition + 1, singlePair.length()));
495 webResourceBuilder.header("X-ECOMP-RequestID",org.slf4j.MDC.get("X-ECOMP-RequestID"));
497 ClientResponse response;
500 response = webResourceBuilder.method(p.httpMethod.toString(), ClientResponse.class, request);
501 } catch (UniformInterfaceException | ClientHandlerException e) {
502 throw new SvcLogicException("Exception while sending http request to client "
503 + e.getLocalizedMessage(), e);
506 r.code = response.getStatus();
507 r.headers = response.getHeaders();
508 EntityTag etag = response.getEntityTag();
510 r.message = etag.getValue();
511 if (response.hasEntity() && r.code != 204)
512 r.body = response.getEntity(String.class);
515 long t2 = System.currentTimeMillis();
516 log.info("Response received. Time: {}", (t2 - t1));
517 log.info("HTTP response code: {}", r.code);
518 log.info("HTTP response message: {}", r.message);
519 logHeaders(r.headers);
520 log.info("HTTP response: {}", r.body);
525 protected SSLContext createSSLContext(Parameters p) {
526 try (FileInputStream in = new FileInputStream(p.keyStoreFileName)) {
527 System.setProperty("jsse.enableSNIExtension", "false");
528 System.setProperty("javax.net.ssl.trustStore", p.trustStoreFileName);
529 System.setProperty("javax.net.ssl.trustStorePassword", p.trustStorePassword);
531 HttpsURLConnection.setDefaultHostnameVerifier((string, ssls) -> true);
533 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
534 KeyStore ks = KeyStore.getInstance("PKCS12");
535 char[] pwd = p.keyStorePassword.toCharArray();
539 SSLContext ctx = SSLContext.getInstance("TLS");
540 ctx.init(kmf.getKeyManagers(), null, null);
542 } catch (Exception e) {
543 log.error("Error creating SSLContext: {}", e.getMessage(), e);
548 protected void setFailureResponseStatus(SvcLogicContext ctx, String prefix, String errorMessage,
551 resp.message = errorMessage;
552 String pp = prefix != null ? prefix + '.' : "";
553 ctx.setAttribute(pp + "response-code", String.valueOf(resp.code));
554 ctx.setAttribute(pp + "response-message", resp.message);
557 protected void setResponseStatus(SvcLogicContext ctx, String prefix, HttpResponse r) {
558 String pp = prefix != null ? prefix + '.' : "";
559 ctx.setAttribute(pp + "response-code", String.valueOf(r.code));
560 ctx.setAttribute(pp + "response-message", r.message);
563 public void sendFile(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
564 HttpResponse r = null;
566 FileParam p = getFileParameters(paramMap);
567 byte[] data = Files.readAllBytes(Paths.get(p.fileName));
569 r = sendHttpData(data, p);
570 setResponseStatus(ctx, p.responsePrefix, r);
572 } catch (SvcLogicException | IOException e) {
573 log.error("Error sending the request: {}", e.getMessage(), e);
575 r = new HttpResponse();
577 r.message = e.getMessage();
578 String prefix = parseParam(paramMap, "responsePrefix", false, null);
579 setResponseStatus(ctx, prefix, r);
582 if (r != null && r.code >= 300)
583 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
586 private static class FileParam {
588 public String fileName;
591 public String password;
592 public HttpMethod httpMethod;
593 public String responsePrefix;
594 public boolean skipSending;
597 private FileParam getFileParameters(Map<String, String> paramMap) throws SvcLogicException {
598 FileParam p = new FileParam();
599 p.fileName = parseParam(paramMap, "fileName", true, null);
600 p.url = parseParam(paramMap, "url", true, null);
601 p.user = parseParam(paramMap, "user", false, null);
602 p.password = parseParam(paramMap, "password", false, null);
603 p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
604 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
605 String skipSendingStr = paramMap.get("skipSending");
606 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
610 protected HttpResponse sendHttpData(byte[] data, FileParam p) throws SvcLogicException {
611 Client client = Client.create();
612 client.setConnectTimeout(5000);
613 client.setFollowRedirects(true);
615 client.addFilter(new HTTPBasicAuthFilter(p.user, p.password));
616 WebResource webResource = client.resource(p.url);
618 log.info("Sending file");
619 long t1 = System.currentTimeMillis();
621 HttpResponse r = new HttpResponse();
624 if (!p.skipSending) {
625 String tt = "application/octet-stream";
627 ClientResponse response;
629 if (p.httpMethod == HttpMethod.POST)
630 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
631 else if (p.httpMethod == HttpMethod.PUT)
632 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
634 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
635 } catch (UniformInterfaceException | ClientHandlerException e) {
636 throw new SvcLogicException("Exception while sending http request to client " +
637 e.getLocalizedMessage(), e);
640 r.code = response.getStatus();
641 r.headers = response.getHeaders();
642 EntityTag etag = response.getEntityTag();
644 r.message = etag.getValue();
645 if (response.hasEntity() && r.code != 204)
646 r.body = response.getEntity(String.class);
649 String newUrl = response.getHeaders().getFirst("Location");
651 log.info("Got response code 301. Sending same request to URL: {}", newUrl);
653 webResource = client.resource(newUrl);
656 if (p.httpMethod == HttpMethod.POST)
657 response = webResource.accept(tt).type(tt).post(ClientResponse.class, data);
658 else if (p.httpMethod == HttpMethod.PUT)
659 response = webResource.accept(tt).type(tt).put(ClientResponse.class, data);
661 throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
662 } catch (UniformInterfaceException | ClientHandlerException e) {
663 throw new SvcLogicException("Exception while sending http request to client " +
664 e.getLocalizedMessage(), e);
667 r.code = response.getStatus();
668 etag = response.getEntityTag();
670 r.message = etag.getValue();
671 if (response.hasEntity() && r.code != 204)
672 r.body = response.getEntity(String.class);
676 long t2 = System.currentTimeMillis();
677 log.info("Response received. Time: {}", (t2 - t1));
678 log.info("HTTP response code: {}", r.code);
679 log.info("HTTP response message: {}", r.message);
680 logHeaders(r.headers);
681 log.info("HTTP response: {}", r.body);
686 public void postMessageOnUeb(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException {
689 UebParam p = getUebParameters(paramMap);
691 String pp = p.responsePrefix != null ? p.responsePrefix + '.' : "";
695 if (p.templateFileName == null) {
696 log.info("No template file name specified. Using default UEB template: {}", defaultUebTemplateFileName);
697 p.templateFileName = defaultUebTemplateFileName;
700 String reqTemplate = readFile(p.templateFileName);
701 reqTemplate = reqTemplate.replaceAll("rootVarName", p.rootVarName);
702 req = buildXmlJsonRequest(ctx, reqTemplate, Format.JSON);
704 r = postOnUeb(req, p);
705 setResponseStatus(ctx, p.responsePrefix, r);
707 ctx.setAttribute(pp + "httpResponse", r.body);
709 } catch (SvcLogicException e) {
710 log.error("Error sending the request: {}", e.getMessage(), e);
712 r = new HttpResponse();
714 r.message = e.getMessage();
715 String prefix = parseParam(paramMap, "responsePrefix", false, null);
716 setResponseStatus(ctx, prefix, r);
720 throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
723 private static class UebParam {
726 public String templateFileName;
727 public String rootVarName;
728 public String responsePrefix;
729 public boolean skipSending;
732 private UebParam getUebParameters(Map<String, String> paramMap) throws SvcLogicException {
733 UebParam p = new UebParam();
734 p.topic = parseParam(paramMap, "topic", true, null);
735 p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
736 p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
737 p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
738 String skipSendingStr = paramMap.get("skipSending");
739 p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
743 protected HttpResponse postOnUeb(String request, UebParam p) throws SvcLogicException {
744 String[] urls = uebServers.split(" ");
745 for (int i = 0; i < urls.length; i++) {
746 if (!urls[i].endsWith("/"))
748 urls[i] += "events/" + p.topic;
751 Client client = Client.create();
752 client.setConnectTimeout(5000);
753 WebResource webResource = client.resource(urls[0]);
755 log.info("UEB URL: {}", urls[0]);
756 log.info("Sending request:");
758 long t1 = System.currentTimeMillis();
760 HttpResponse r = new HttpResponse();
763 if (!p.skipSending) {
764 String tt = "application/json";
765 String tt1 = tt + ";charset=UTF-8";
767 ClientResponse response;
770 response = webResource.accept(tt).type(tt1).post(ClientResponse.class, request);
771 } catch (UniformInterfaceException | ClientHandlerException e) {
772 throw new SvcLogicException("Exception while posting http request to client " +
773 e.getLocalizedMessage(), e);
776 r.code = response.getStatus();
777 r.headers = response.getHeaders();
778 if (response.hasEntity())
779 r.body = response.getEntity(String.class);
782 long t2 = System.currentTimeMillis();
783 log.info("Response received. Time: {}", (t2 - t1));
784 log.info("HTTP response code: {}", r.code);
785 logHeaders(r.headers);
786 log.info("HTTP response:\n {}", r.body);
791 protected void logProperties(Map<String, Object> mm) {
792 List<String> ll = new ArrayList<>();
793 for (Object o : mm.keySet())
795 Collections.sort(ll);
797 log.info("Properties:");
798 for (String name : ll)
799 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
802 protected void logHeaders(MultivaluedMap<String, String> mm) {
803 log.info("HTTP response headers:");
808 List<String> ll = new ArrayList<>();
809 for (Object o : mm.keySet())
811 Collections.sort(ll);
813 for (String name : ll)
814 log.info("--- {}:{}", name, String.valueOf(mm.get(name)));
817 public void setUebServers(String uebServers) {
818 this.uebServers = uebServers;
821 public void setDefaultUebTemplateFileName(String defaultUebTemplateFileName) {
822 this.defaultUebTemplateFileName = defaultUebTemplateFileName;