- if (r.body != null && r.body.trim().length() > 0) {
- ctx.setAttribute(pp + "httpResponse", r.body);
-
- if (p.convertResponse) {
- Map<String, String> mm = null;
- if (p.format == Format.XML)
- mm = XmlParser.convertToProperties(r.body, p.listNameList);
- else if (p.format == Format.JSON)
- mm = JsonParser.convertToProperties(r.body);
-
- if (mm != null)
- for (String key : mm.keySet())
- ctx.setAttribute(pp + key, mm.get(key));
- }
- }
- } catch (Exception e) {
- boolean shouldRetry = false;
- if (e.getCause() instanceof java.net.SocketException) {
- shouldRetry = true;
- }
-
- log.error("Error sending the request: " + e.getMessage(), e);
- String prefix = parseParam(paramMap, "responsePrefix", false, null);
- if (retryPolicy == null || shouldRetry == false) {
- setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
- } else {
- if (retryCount == null) {
- retryCount = 0;
- }
- String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
- " maximum retries.";
- log.debug(retryMessage);
- try {
- retryCount = retryCount + 1;
- if (retryCount < retryPolicy.getMaximumRetries() + 1) {
- URI uri = new URI(paramMap.get("restapiUrl"));
- String hostname = uri.getHost();
- String retryString = retryPolicy.getNextHostName((uri.toString()));
- URI uriTwo = new URI(retryString);
- URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
- uriTwo.getScheme()).build();
- paramMap.put("restapiUrl", retryUri.toString());
- log.debug("URL was set to " + retryUri.toString());
- log.debug("Failed to communicate with host " + hostname +
- ". Request will be re-attempted using the host " + retryString + ".");
- log.debug("This is retry attempt " + retryCount + " out of " + retryPolicy.getMaximumRetries());
- sendRequest(paramMap, ctx, retryCount);
- } else {
- log.debug("Maximum retries reached, calling setFailureResponseStatus.");
- setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
- }
- } catch (Exception ex) {
- log.error("Could not attempt retry.", ex);
- String retryErrorMessage =
- "Retry attempt has failed. No further retry shall be attempted, calling setFailureResponseStatus.";
- setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
- }
- }
- }
-
- if (r != null && r.code >= 300)
- throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
- }
-
- protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
- Parameters p = new Parameters();
- p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
- p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
- p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
- p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
- p.contentType = parseParam(paramMap, "contentType", false, null);
- p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
- p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
- p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
- p.listNameList = getListNameList(paramMap);
- String skipSendingStr = paramMap.get("skipSending");
- p.skipSending = skipSendingStr != null && skipSendingStr.equalsIgnoreCase("true");
- p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
- p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
- p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
- p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
- p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
- p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
- p.keyStorePassword != null;
- p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
- p.partner = parseParam(paramMap, "partner", false, null);
- p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
- return p;
- }
-
- protected Set<String> getListNameList(Map<String, String> paramMap) {
- Set<String> ll = new HashSet<String>();
- for (String key : paramMap.keySet())
- if (key.startsWith("listName"))
- ll.add(paramMap.get(key));
- return ll;
- }
-
- protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
- throws SvcLogicException {
- String s = paramMap.get(name);
-
- if (s == null || s.trim().length() == 0) {
- if (!required)
- return def;
- throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
- }
-
- s = s.trim();
- String value = "";
- int i = 0;
- int i1 = s.indexOf('%');
- while (i1 >= 0) {
- int i2 = s.indexOf('%', i1 + 1);
- if (i2 < 0)
- break;
-
- String varName = s.substring(i1 + 1, i2);
- String varValue = System.getenv(varName);
- if (varValue == null)
- varValue = "%" + varName + "%";
-
- value += s.substring(i, i1);
- value += varValue;
-
- i = i2 + 1;
- i1 = s.indexOf('%', i);
- }
- value += s.substring(i);
-
- log.info("Parameter " + name + ": [" + value + "]");
- return value;
- }
-
- protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) {
- log.info("Building " + format + " started");
- long t1 = System.currentTimeMillis();
-
- template = expandRepeats(ctx, template, 1);
-
- Map<String, String> mm = new HashMap<>();
- for (String s : ctx.getAttributeKeySet())
- mm.put(s, ctx.getAttribute(s));
-
- StringBuilder ss = new StringBuilder();
- int i = 0;
- while (i < template.length()) {
- int i1 = template.indexOf("${", i);
- if (i1 < 0) {
- ss.append(template.substring(i));
- break;
- }
-
- int i2 = template.indexOf('}', i1 + 2);
- if (i2 < 0)
- throw new RuntimeException("Template error: Matching } not found");
-
- String var1 = template.substring(i1 + 2, i2);
- String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
- // log.info(" " + var1 + ": " + value1);
- if (value1 == null || value1.trim().length() == 0) {
- // delete the whole element (line)
- int i3 = template.lastIndexOf('\n', i1);
- if (i3 < 0)
- i3 = 0;
- int i4 = template.indexOf('\n', i1);
- if (i4 < 0)
- i4 = template.length();
-
- if (i < i3)
- ss.append(template.substring(i, i3));
- i = i4;
- } else {
- ss.append(template.substring(i, i1)).append(value1);
- i = i2 + 1;
- }
- }
-
- String req = format == Format.XML
- ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
-
- if (format == Format.JSON)
- req = XmlJsonUtil.removeLastCommaJson(req);
-
- long t2 = System.currentTimeMillis();
- log.info("Building " + format + " completed. Time: " + (t2 - t1));
-
- return req;
- }
-
- protected String expandRepeats(SvcLogicContext ctx, String template, int level) {
- StringBuilder newTemplate = new StringBuilder();
- int k = 0;
- while (k < template.length()) {
- int i1 = template.indexOf("${repeat:", k);
- if (i1 < 0) {
- newTemplate.append(template.substring(k));
- break;
- }
-
- int i2 = template.indexOf(':', i1 + 9);
- if (i2 < 0)
- throw new RuntimeException(
- "Template error: Context variable name followed by : is required after repeat");
-
- // Find the closing }, store in i3
- int nn = 1;
- int i3 = -1;
- int i = i2;
- while (nn > 0 && i < template.length()) {
- i3 = template.indexOf('}', i);
- if (i3 < 0)
- throw new RuntimeException("Template error: Matching } not found");
- int i32 = template.indexOf('{', i);
- if (i32 >= 0 && i32 < i3) {
- nn++;
- i = i32 + 1;
- } else {
- nn--;
- i = i3 + 1;
- }
- }
-
- String var1 = template.substring(i1 + 9, i2);
- String value1 = ctx.getAttribute(var1);
- log.info(" " + var1 + ": " + value1);
- int n = 0;
- try {
- n = Integer.parseInt(value1);
- } catch (Exception e) {
- n = 0;
- }
-
- newTemplate.append(template.substring(k, i1));
-
- String rpt = template.substring(i2 + 1, i3);
-
- for (int ii = 0; ii < n; ii++) {
- String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
- if (ii == n - 1 && ss.trim().endsWith(",")) {
- int i4 = ss.lastIndexOf(',');
- if (i4 > 0)
- ss = ss.substring(0, i4) + ss.substring(i4 + 1);
- }
- newTemplate.append(ss);
- }
-
- k = i3 + 1;
- }
-
- if (k == 0)
- return newTemplate.toString();
-
- return expandRepeats(ctx, newTemplate.toString(), level + 1);
- }
-
- protected String readFile(String fileName) throws Exception {
- byte[] encoded = Files.readAllBytes(Paths.get(fileName));
- return new String(encoded, "UTF-8");
- }
-
- protected HttpResponse sendHttpRequest(String request, Parameters p) throws Exception {
- ClientConfig config = new DefaultClientConfig();
- SSLContext ssl = null;
- if (p.ssl && p.restapiUrl.startsWith("https"))
- ssl = createSSLContext(p);
- if (ssl != null) {
- HostnameVerifier hostnameVerifier = new HostnameVerifier() {
-
- @Override
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- };
-
- config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
- new HTTPSProperties(hostnameVerifier, ssl));
- }
-
- logProperties(config.getProperties());
-
- Client client = Client.create(config);
- client.setConnectTimeout(5000);
- if (p.restapiUser != null)
- client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
- WebResource webResource = client.resource(p.restapiUrl);
-
- log.info("Sending request:");
- log.info(request);
- long t1 = System.currentTimeMillis();
-
- HttpResponse r = new HttpResponse();
- r.code = 200;
-
- if (!p.skipSending) {
- String tt = p.format == Format.XML ? "application/xml" : "application/json";
- String tt1 = tt + ";charset=UTF-8";
- if (p.contentType != null) {
- tt = p.contentType;
- tt1 = p.contentType;
- }
-
- WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);
+ if (r.body != null && r.body.trim().length() > 0) {
+ ctx.setAttribute(pp + "httpResponse", r.body);
+
+ if (p.convertResponse) {
+ Map<String, String> mm = null;
+ if (p.format == Format.XML)
+ mm = XmlParser.convertToProperties(r.body, p.listNameList);
+ else if (p.format == Format.JSON)
+ mm = JsonParser.convertToProperties(r.body);
+
+ if (mm != null)
+ for (String key : mm.keySet())
+ ctx.setAttribute(pp + key, mm.get(key));
+ }
+ }
+ } catch (Exception e) {
+ boolean shouldRetry = false;
+ if (e.getCause() instanceof java.net.SocketException) {
+ shouldRetry = true;
+ }
+
+ log.error("Error sending the request: " + e.getMessage(), e);
+ String prefix = parseParam(paramMap, "responsePrefix", false, null);
+ if (retryPolicy == null || shouldRetry == false) {
+ setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
+ } else {
+ if (retryCount == null) {
+ retryCount = 0;
+ }
+ String retryMessage = retryCount + " attempts were made out of " + retryPolicy.getMaximumRetries() +
+ " maximum retries.";
+ log.debug(retryMessage);
+ try {
+ retryCount = retryCount + 1;
+ if (retryCount < retryPolicy.getMaximumRetries() + 1) {
+ URI uri = new URI(paramMap.get("restapiUrl"));
+ String hostname = uri.getHost();
+ String retryString = retryPolicy.getNextHostName(uri.toString());
+ URI uriTwo = new URI(retryString);
+ URI retryUri = UriBuilder.fromUri(uri).host(uriTwo.getHost()).port(uriTwo.getPort()).scheme(
+ uriTwo.getScheme()).build();
+ paramMap.put("restapiUrl", retryUri.toString());
+ log.debug("URL was set to " + retryUri.toString());
+ log.debug("Failed to communicate with host " + hostname +
+ ". Request will be re-attempted using the host " + retryString + ".");
+ log.debug("This is retry attempt " + retryCount + " out of " + retryPolicy.getMaximumRetries());
+ sendRequest(paramMap, ctx, retryCount);
+ } else {
+ log.debug("Maximum retries reached, calling setFailureResponseStatus.");
+ setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
+ }
+ } catch (Exception ex) {
+ log.error("Could not attempt retry.", ex);
+ String retryErrorMessage =
+ "Retry attempt has failed. No further retry shall be attempted, calling setFailureResponseStatus.";
+ setFailureResponseStatus(ctx, prefix, retryErrorMessage, r);
+ }
+ }
+ }
+
+ if (r != null && r.code >= 300)
+ throw new SvcLogicException(String.valueOf(r.code) + ": " + r.message);
+ }
+
+ protected Parameters getParameters(Map<String, String> paramMap) throws SvcLogicException {
+ Parameters p = new Parameters();
+ p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
+ p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
+ p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
+ p.restapiPassword = parseParam(paramMap, "restapiPassword", false, null);
+ p.contentType = parseParam(paramMap, "contentType", false, null);
+ p.format = Format.fromString(parseParam(paramMap, "format", false, "json"));
+ p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
+ p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
+ p.listNameList = getListNameList(paramMap);
+ String skipSendingStr = paramMap.get("skipSending");
+ p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
+ p.convertResponse = Boolean.valueOf(parseParam(paramMap, "convertResponse", false, "true"));
+ p.trustStoreFileName = parseParam(paramMap, "trustStoreFileName", false, null);
+ p.trustStorePassword = parseParam(paramMap, "trustStorePassword", false, null);
+ p.keyStoreFileName = parseParam(paramMap, "keyStoreFileName", false, null);
+ p.keyStorePassword = parseParam(paramMap, "keyStorePassword", false, null);
+ p.ssl = p.trustStoreFileName != null && p.trustStorePassword != null && p.keyStoreFileName != null &&
+ p.keyStorePassword != null;
+ p.customHttpHeaders = parseParam(paramMap, "customHttpHeaders", false, null);
+ p.partner = parseParam(paramMap, "partner", false, null);
+ p.dumpHeaders = Boolean.valueOf(parseParam(paramMap, "dumpHeaders", false, null));
+ return p;
+ }
+
+ protected Set<String> getListNameList(Map<String, String> paramMap) {
+ Set<String> ll = new HashSet<String>();
+ for (Map.Entry<String,String> entry : paramMap.entrySet())
+ if (entry.getKey().startsWith("listName"))
+ ll.add(entry.getValue());
+ return ll;
+ }
+
+ protected String parseParam(Map<String, String> paramMap, String name, boolean required, String def)
+ throws SvcLogicException {
+ String s = paramMap.get(name);
+
+ if (s == null || s.trim().length() == 0) {
+ if (!required)
+ return def;
+ throw new SvcLogicException("Parameter " + name + " is required in RestapiCallNode");
+ }
+
+ s = s.trim();
+ String value = "";
+ int i = 0;
+ int i1 = s.indexOf('%');
+ while (i1 >= 0) {
+ int i2 = s.indexOf('%', i1 + 1);
+ if (i2 < 0)
+ break;
+
+ String varName = s.substring(i1 + 1, i2);
+ String varValue = System.getenv(varName);
+ if (varValue == null)
+ varValue = "%" + varName + "%";
+
+ value += s.substring(i, i1);
+ value += varValue;
+
+ i = i2 + 1;
+ i1 = s.indexOf('%', i);
+ }
+ value += s.substring(i);
+
+ log.info("Parameter " + name + ": [" + value + "]");
+ return value;
+ }
+
+ protected String buildXmlJsonRequest(SvcLogicContext ctx, String template, Format format) {
+ log.info("Building " + format + " started");
+ long t1 = System.currentTimeMillis();
+
+ template = expandRepeats(ctx, template, 1);
+
+ Map<String, String> mm = new HashMap<>();
+ for (String s : ctx.getAttributeKeySet())
+ mm.put(s, ctx.getAttribute(s));
+
+ StringBuilder ss = new StringBuilder();
+ int i = 0;
+ while (i < template.length()) {
+ int i1 = template.indexOf("${", i);
+ if (i1 < 0) {
+ ss.append(template.substring(i));
+ break;
+ }
+
+ int i2 = template.indexOf('}', i1 + 2);
+ if (i2 < 0)
+ throw new RuntimeException("Template error: Matching } not found");
+
+ String var1 = template.substring(i1 + 2, i2);
+ String value1 = format == Format.XML ? XmlJsonUtil.getXml(mm, var1) : XmlJsonUtil.getJson(mm, var1);
+ // log.info(" " + var1 + ": " + value1);
+ if (value1 == null || value1.trim().length() == 0) {
+ // delete the whole element (line)
+ int i3 = template.lastIndexOf('\n', i1);
+ if (i3 < 0)
+ i3 = 0;
+ int i4 = template.indexOf('\n', i1);
+ if (i4 < 0)
+ i4 = template.length();
+
+ if (i < i3)
+ ss.append(template.substring(i, i3));
+ i = i4;
+ } else {
+ ss.append(template.substring(i, i1)).append(value1);
+ i = i2 + 1;
+ }
+ }
+
+ String req = format == Format.XML
+ ? XmlJsonUtil.removeEmptyStructXml(ss.toString()) : XmlJsonUtil.removeEmptyStructJson(ss.toString());
+
+ if (format == Format.JSON)
+ req = XmlJsonUtil.removeLastCommaJson(req);
+
+ long t2 = System.currentTimeMillis();
+ log.info("Building " + format + " completed. Time: " + (t2 - t1));
+
+ return req;
+ }
+
+ protected String expandRepeats(SvcLogicContext ctx, String template, int level) {
+ StringBuilder newTemplate = new StringBuilder();
+ int k = 0;
+ while (k < template.length()) {
+ int i1 = template.indexOf("${repeat:", k);
+ if (i1 < 0) {
+ newTemplate.append(template.substring(k));
+ break;
+ }
+
+ int i2 = template.indexOf(':', i1 + 9);
+ if (i2 < 0)
+ throw new RuntimeException(
+ "Template error: Context variable name followed by : is required after repeat");
+
+ // Find the closing }, store in i3
+ int nn = 1;
+ int i3 = -1;
+ int i = i2;
+ while (nn > 0 && i < template.length()) {
+ i3 = template.indexOf('}', i);
+ if (i3 < 0)
+ throw new RuntimeException("Template error: Matching } not found");
+ int i32 = template.indexOf('{', i);
+ if (i32 >= 0 && i32 < i3) {
+ nn++;
+ i = i32 + 1;
+ } else {
+ nn--;
+ i = i3 + 1;
+ }
+ }
+
+ String var1 = template.substring(i1 + 9, i2);
+ String value1 = ctx.getAttribute(var1);
+ log.info(" " + var1 + ": " + value1);
+ int n = 0;
+ try {
+ n = Integer.parseInt(value1);
+ } catch (Exception e) {
+ n = 0;
+ }
+
+ newTemplate.append(template.substring(k, i1));
+
+ String rpt = template.substring(i2 + 1, i3);
+
+ for (int ii = 0; ii < n; ii++) {
+ String ss = rpt.replaceAll("\\[\\$\\{" + level + "\\}\\]", "[" + ii + "]");
+ if (ii == n - 1 && ss.trim().endsWith(",")) {
+ int i4 = ss.lastIndexOf(',');
+ if (i4 > 0)
+ ss = ss.substring(0, i4) + ss.substring(i4 + 1);
+ }
+ newTemplate.append(ss);
+ }
+
+ k = i3 + 1;
+ }
+
+ if (k == 0)
+ return newTemplate.toString();
+
+ return expandRepeats(ctx, newTemplate.toString(), level + 1);
+ }
+
+ protected String readFile(String fileName) throws Exception {
+ byte[] encoded = Files.readAllBytes(Paths.get(fileName));
+ return new String(encoded, "UTF-8");
+ }
+
+ protected HttpResponse sendHttpRequest(String request, Parameters p) throws Exception {
+ ClientConfig config = new DefaultClientConfig();
+ SSLContext ssl = null;
+ if (p.ssl && p.restapiUrl.startsWith("https"))
+ ssl = createSSLContext(p);
+ if (ssl != null) {
+ HostnameVerifier hostnameVerifier = new HostnameVerifier() {
+
+ @Override
+ public boolean verify(String hostname, SSLSession session) {
+ return true;
+ }
+ };
+
+ config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
+ new HTTPSProperties(hostnameVerifier, ssl));
+ }
+
+ logProperties(config.getProperties());
+
+ Client client = Client.create(config);
+ client.setConnectTimeout(5000);
+ if (p.restapiUser != null)
+ client.addFilter(new HTTPBasicAuthFilter(p.restapiUser, p.restapiPassword));
+ WebResource webResource = client.resource(p.restapiUrl);
+
+ log.info("Sending request:");
+ log.info(request);
+ long t1 = System.currentTimeMillis();
+
+ HttpResponse r = new HttpResponse();
+ r.code = 200;
+
+ if (!p.skipSending) {
+ String tt = p.format == Format.XML ? "application/xml" : "application/json";
+ String tt1 = tt + ";charset=UTF-8";
+ if (p.contentType != null) {
+ tt = p.contentType;
+ tt1 = p.contentType;
+ }
+
+ WebResource.Builder webResourceBuilder = webResource.accept(tt).type(tt1);