* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights
* reserved.
+ * Modifications Copyright © 2018 IBM.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private String uebServers;
private String defaultUebTemplateFileName = "/opt/bvc/restapi/templates/default-ueb-message.json";
+ private String responseReceivedMessage = "Response received. Time: {}";
+ private String responseHttpCodeMessage = "HTTP response code: {}";
+ private String requestPostingException = "Exception while posting http request to client ";
+ private static String skipSendingMessage = "skipSending";
+ private static String responsePrefix = "responsePrefix";
+ private static String restapiUrlString = "restapiUrl";
+
public RestapiCallNode() {
String configDir = System.getProperty(PROPERTIES_DIR_KEY, DEFAULT_PROPERTIES_DIR);
p.templateFileName = parseParam(paramMap, "templateFileName",
false, null);
p.requestBody = parseParam(paramMap, "requestBody", false, null);
- p.restapiUrl = parseParam(paramMap, "restapiUrl", true, null);
+ p.restapiUrl = parseParam(paramMap, restapiUrlString, true, null);
validateUrl(p.restapiUrl);
p.restapiUser = parseParam(paramMap, "restapiUser", false, null);
p.restapiPassword = parseParam(paramMap, "restapiPassword", false,
"unspecified"));
p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod",
false, "post"));
- p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
+ p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
p.listNameList = getListNameList(paramMap);
- String skipSendingStr = paramMap.get("skipSending");
+ String skipSendingStr = paramMap.get(skipSendingMessage);
p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
p.convertResponse = valueOf(parseParam(paramMap, "convertResponse",
false, "true"));
}
log.error("Error sending the request: " + e.getMessage(), e);
- String prefix = parseParam(paramMap, "responsePrefix", false, null);
- if (retryPolicy == null || shouldRetry == false) {
+ String prefix = parseParam(paramMap, responsePrefix, false, null);
+ if (retryPolicy == null || !shouldRetry) {
setFailureResponseStatus(ctx, prefix, e.getMessage(), r);
} else {
if (retryCount == null) {
try {
retryCount = retryCount + 1;
if (retryCount < retryPolicy.getMaximumRetries() + 1) {
- URI uri = new URI(paramMap.get("restapiUrl"));
+ URI uri = new URI(paramMap.get(restapiUrlString));
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());
+ paramMap.put(restapiUrlString, retryUri.toString());
log.debug("URL was set to {}", retryUri.toString());
log.debug("Failed to communicate with host {}. Request will be re-attempted using the host {}.",
hostname, retryString);
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);
try {
response = invocationBuilder.method(p.httpMethod.toString(), entity(request, tt1));
} catch (ProcessingException | IllegalStateException e) {
- throw new SvcLogicException("Exception while posting http request to client " +
+ throw new SvcLogicException(requestPostingException +
e.getLocalizedMessage(), e);
}
}
long t2 = System.currentTimeMillis();
- log.info("Response received. Time: {}", (t2 - t1));
- log.info("HTTP response code: {}", r.code);
+ log.info(responseReceivedMessage, (t2 - t1));
+ log.info(responseHttpCodeMessage, r.code);
log.info("HTTP response message: {}", r.message);
logHeaders(r.headers);
log.info("HTTP response: {}", r.body);
r = new HttpResponse();
r.code = 500;
r.message = e.getMessage();
- String prefix = parseParam(paramMap, "responsePrefix", false, null);
+ String prefix = parseParam(paramMap, responsePrefix, false, null);
setResponseStatus(ctx, prefix, r);
}
p.user = parseParam(paramMap, "user", false, null);
p.password = parseParam(paramMap, "password", false, null);
p.httpMethod = HttpMethod.fromString(parseParam(paramMap, "httpMethod", false, "post"));
- p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
- String skipSendingStr = paramMap.get("skipSending");
+ p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
+ String skipSendingStr = paramMap.get(skipSendingMessage);
p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
p.oAuthConsumerKey = parseParam(paramMap, "oAuthConsumerKey", false, null);
p.oAuthVersion = parseParam(paramMap, "oAuthVersion", false, null);
r = new HttpResponse();
r.code = 500;
r.message = e.getMessage();
- String prefix = parseParam(paramMap, "responsePrefix", false, null);
+ String prefix = parseParam(paramMap, responsePrefix, false, null);
setResponseStatus(ctx, prefix, r);
}
throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
}
} catch (ProcessingException e) {
- throw new SvcLogicException("Exception while posting http request to client " +
+ throw new SvcLogicException(requestPostingException +
e.getLocalizedMessage(), e);
}
throw new SvcLogicException("Http operation" + p.httpMethod + "not supported");
}
} catch (ProcessingException e) {
- throw new SvcLogicException("Exception while posting http request to client " +
+ throw new SvcLogicException(requestPostingException +
e.getLocalizedMessage(), e);
}
}
long t2 = System.currentTimeMillis();
- log.info("Response received. Time: {}", (t2 - t1));
- log.info("HTTP response code: {}", r.code);
+ log.info(responseReceivedMessage, (t2 - t1));
+ log.info(responseHttpCodeMessage, r.code);
log.info("HTTP response message: {}", r.message);
logHeaders(r.headers);
log.info("HTTP response: {}", r.body);
p.topic = parseParam(paramMap, "topic", true, null);
p.templateFileName = parseParam(paramMap, "templateFileName", false, null);
p.rootVarName = parseParam(paramMap, "rootVarName", false, null);
- p.responsePrefix = parseParam(paramMap, "responsePrefix", false, null);
- String skipSendingStr = paramMap.get("skipSending");
+ p.responsePrefix = parseParam(paramMap, responsePrefix, false, null);
+ String skipSendingStr = paramMap.get(skipSendingMessage);
p.skipSending = "true".equalsIgnoreCase(skipSendingStr);
return p;
}
try {
response = invocationBuilder.post(Entity.entity(request, tt1));
} catch (ProcessingException e) {
- throw new SvcLogicException("Exception while posting http request to client " +
+ throw new SvcLogicException(requestPostingException +
e.getLocalizedMessage(), e);
}
r.code = response.getStatus();
}
long t2 = System.currentTimeMillis();
- log.info("Response received. Time: {}", (t2 - t1));
- log.info("HTTP response code: {}", r.code);
+ log.info(responseReceivedMessage, (t2 - t1));
+ log.info(responseHttpCodeMessage, r.code);
logHeaders(r.headers);
log.info("HTTP response:\n {}", r.body);
* ONAP - CCSDK
* ================================================================================
* Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
+ *
+ * Modifications Copyright © 2018 IBM
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.util.Map;
* ================================================================================
* Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
* ================================================================================
+ * Modifications Copyright © 2018 IBM
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* Representation of the YANG parameters for the restconf api call node.
*/
public class YangParameters extends Parameters {
+ /**
+ * Directory path of the YANG file.
+ */
+ public String dirPath;
/**
* Creates an instance of the YANG parameters.
public YangParameters() {
super();
}
-
- /**
- * Directory path of the YANG file.
- */
- public String dirPath;
}
* ONAP - CCSDK
* ================================================================================
* Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
+ *
+ * Modifications Copyright © 2018 IBM
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private String value;
private Namespace valueNs;
+ private static final String svcLogicException = "Leaf cannot hold child nodes";
/**
* Creates an instance of leaf node.
public PropertiesNode addChild(String name, Namespace namespace,
NodeType type,
Object appInfo) throws SvcLogicException {
- throw new SvcLogicException("Leaf cannot hold child nodes");
+ throw new SvcLogicException(svcLogicException);
}
@Override
NodeType type, String value,
Namespace valueNs,
Object appInfo) throws SvcLogicException {
- throw new SvcLogicException("Leaf cannot hold child nodes");
+ throw new SvcLogicException(svcLogicException);
}
@Override
Namespace namespace,
NodeType type,
Object appInfo) throws SvcLogicException {
- throw new SvcLogicException("Leaf cannot hold child nodes");
+ throw new SvcLogicException(svcLogicException);
}
@Override
* =============================================================================
* Copyright (C) 2018 Samsung Electronics. All rights
reserved.
-* * ================================================================================
+ * ================================================================================
+ * Modifications Copyright © 2018 IBM
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
package org.onap.ccsdk.sli.plugins.sshapicall;
-//import com.fasterxml.jackson.databind.ObjectMapper;
-
import java.io.ByteArrayOutputStream;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Map;
-import java.util.Set;
-import com.google.common.base.Strings;
-import org.json.JSONObject;
import org.onap.appc.adapter.ssh.SshAdapter;
import org.onap.appc.adapter.ssh.SshConnection;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
*/
private int DEF_SUCCESS_STATUS = 0;
+
+
+ private SshAdapter sshAdapter;
+
/**
* Used for jUnit test and testing interface
*/
PARAM_TEST_MODE = false;
}
- private SshAdapter sshAdapter;
-
public void setSshAdapter(SshAdapter sshAdapter) {
this.sshAdapter = sshAdapter;
}
int status = -1;
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
- String stdoutRes = "", stderrRes = "";
+ String stdoutRes = "";
+ String stderrRes = "";
try {
if (!PARAM_TEST_MODE) {
sshConnection = getSshConnection(p);
stderrRes = stderr.toString();
} else {
- if (params.get("TestFail").equalsIgnoreCase("true"))
+ if (("true").equalsIgnoreCase(params.get("TestFail")))
status = 202;
else
status = DEF_SUCCESS_STATUS;
return sshAdapter.getConnection(p.sshapiUrl, p.sshapiPort, p.sshapiUser, p.sshapiPassword);
// This is not supported yet in the API, patch has already been added to APPC
else if (p.authtype == AuthType.KEY){
- //return sshAdapter.getConnection(p.sshapiUrl, p.sshapiPort, p.sshKey);
throw new SvcLogicException("SSH Key based Auth method not supported");
}
else if (p.authtype == AuthType.NONE){
- //return sshAdapter.getConnection(p.sshapiUrl, p.sshapiPort, p.sshKey);
throw new SvcLogicException("SSH Auth type required, BASIC auth in support");
}
else if (p.authtype == AuthType.UNSPECIFIED){
* Copyright (C) 2018 Samsung Electronics. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright © 2018 IBM
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* Copyright (C) 2018 Samsung Electronics. All rights
* reserved.
* ================================================================================
+ * Modifications Copyright © 2018 IBM
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
private Map<String, String> properties = new HashMap<>();
- public Map<String, String> getProperties() {
- return properties;
- }
-
StringBuilder currentName = new StringBuilder();
StringBuilder currentValue = new StringBuilder();
this.listNameList = new HashSet<>();
}
+ public Map<String, String> getProperties() {
+ return properties;
+ }
+
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
--- /dev/null
+
+package org.onap.ccsdk.sli.plugins.template;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import org.apache.velocity.context.InternalContextAdapter;
+import org.apache.velocity.exception.MethodInvocationException;
+import org.apache.velocity.exception.ParseErrorException;
+import org.apache.velocity.exception.ResourceNotFoundException;
+import org.apache.velocity.runtime.directive.Directive;
+import org.apache.velocity.runtime.parser.node.Node;
+
+// This directive can be used when handling optional json attributes in a template
+// If an attribute value is null the entire name-value pair will not be rendered
+// If an attribute value is not null the name-value pair will be rendered
+// Additional optional parameters decide which values are quoted and if a comma and or newline should be appended
+public class HideNullJson extends Directive {
+
+ public String getName() {
+ return "hideNullJson";
+ }
+
+ public int getType() {
+ return BLOCK;
+ }
+
+ // The first parameter is the json key
+ // The second parameter is the json value
+ // This directive handles placing the colon between the json key and json value
+ // The third parameter is a boolean, when true the json key is surrounded in double quotes by this directive
+ // The third parameter is true by default and is optional
+ // The fourth parameter is a boolean when true the json value is surrounded in double quotes by this directive
+ // The fourth parameter is true by default and is optional
+ // The fifth parameter is a boolean when true a comma is appended to the end
+ // The fifth parameter is true by default and is optional
+ // The sixth parameter is a boolean when true a newline is appended to the end
+ // The sixth parameter is true by default and is optional
+ public boolean render(InternalContextAdapter context, Writer writer, Node node)
+ throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
+ String tagValue = null;
+ Object tagValueObject = node.jjtGetChild(1).value(context);
+ if (tagValueObject == null) {
+ return true;
+ }
+ tagValue = String.valueOf(tagValueObject);
+
+ String tagName = String.valueOf(node.jjtGetChild(0).value(context));
+
+ Boolean quoteTagName = getBooleanParameter(true,node,2,context);
+ Boolean quoteTagValue = getBooleanParameter(true,node,3,context);
+ Boolean appendComma = getBooleanParameter(true,node,4,context);
+ Boolean appendNewLine = getBooleanParameter(true,node,5,context);
+
+ StringBuilder sb = new StringBuilder();
+
+ if (quoteTagName) {
+ appendQuotedString(tagName,sb);
+ }else {
+ sb.append(tagName);
+ }
+
+ sb.append(":");
+
+ if (quoteTagValue) {
+ appendQuotedString(tagValue,sb);
+ }else {
+ sb.append(tagValue);
+ }
+
+ if(appendComma) {
+ sb.append(",");
+ }
+
+ if(appendNewLine) {
+ sb.append("\n");
+ }
+ writer.write(sb.toString());
+ return true;
+ }
+
+ private Boolean getBooleanParameter(Boolean defaultBool, Node node, int parameterPostion, InternalContextAdapter context) {
+ if (node.jjtGetNumChildren() > parameterPostion && node.jjtGetChild(parameterPostion) != null) {
+ Object val = node.jjtGetChild(parameterPostion).value(context);
+ if (val != null) {
+ return (Boolean) val;
+ }
+ }
+ return defaultBool;
+ }
+
+ private void appendQuotedString(String str, StringBuilder sb) {
+ sb.append("\"");
+ sb.append(str);
+ sb.append("\"");
+ }
+
+}
\ No newline at end of file
import java.io.FileInputStream;
import java.io.StringWriter;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
ve = new VelocityEngine();
setProperties();
ve.init();
+ ve.loadDirective("org.onap.ccsdk.sli.plugins.template.HideNullJson");
}
protected void setProperties() {
VelocityContext context = new VelocityContext();
context.put("ctx", ctx);
context.put("params", params);
+ //Adding these values directly to context makes working with the values cleaner
+ for (Entry<String, String> entry : params.entrySet()) {
+ context.put(entry.getKey(), entry.getValue());
+ }
StringWriter sw = new StringWriter();
template.merge(context, sw);
ctx.setAttribute(outputPath, sw.toString());
}
}
-}
\ No newline at end of file
+}
--- /dev/null
+package org.onap.ccsdk.sli.plugins.template;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
+
+public class HideNullJsonTest {
+
+ @Test
+ public void testSampleTemplate() throws Exception {
+ TemplateNode t = new MockTemplateNode();
+
+ Map<String, String> params = new HashMap<String, String>();
+ params.put(TemplateNode.PREFIX_KEY, "output");
+ params.put(TemplateNode.OUTPUT_PATH_KEY, "mycontainer");
+ params.put(TemplateNode.TEMPLATE_PATH, "src/test/resources/HideNullJson.vtl");
+
+ //Setup sample data to feed into the directive
+ params.put("service-type", "\"VPN\""); //the value is quoted to test an override
+ params.put("svc-request-id", "REQ001");
+ params.put("svc-action", "CREATE");
+ params.put("service-instance-id", "SVC001");
+ params.put("customerNameTag", "customer-name");
+ params.put("customer-name", "TestCust");
+ params.put("siidTag", "\"service-instance-id\""); //the value is quoted to test an override
+
+ SvcLogicContext ctx = new SvcLogicContext();
+ t.evaluateTemplate(params, ctx);
+ String result = ctx.getAttribute("output.mycontainer");
+ assertTrue(result.contains("\"svc-request-id\":\"REQ001\","));
+ assertTrue(result.contains("\"svc-action\":\"CREATE\""));
+ assertFalse(result.contains("\"svc-action\":\"CREATE\",")); // there should be no trailing comma
+ assertTrue(result.contains("\"service-type\":\"VPN\","));
+ assertTrue(result.contains("\"customer-name\":\"TestCust\","));
+ assertTrue(result.contains("\"service-instance-id\":\"SVC001\""));
+ assertFalse(result.contains("\"service-instance-id\":\"SVC001\",")); // there should be no trailing comma
+ //This should be hidden by the directive because the parameter was never populated
+ assertFalse(result.contains("customer-phone-number"));
+ }
+
+}
\ No newline at end of file
--- /dev/null
+## This is an example comment
+## This velocity template is used to test the hideNullJson directive
+{
+ "input": {
+ "request-header": {
+## by default the values parameters provided are surrounded in double quotes and separated by a colon
+ #hideNullJson("svc-request-id",$svc-request-id)#end
+## override default settings so the comma isn't written
+ #hideNullJson("svc-action",$svc-action, true, true, false)#end
+ },
+ "service-information": {
+## if we look at the values in parameters we see service-type is already surrounded by quotes
+## we override the default so the string isn't surrounded by excess quotes
+ #hideNullJson("service-type",$service-type,true,false,true)#end
+## the first parameter doesn't need to be a literal
+ #hideNullJson($customerNameTag,$customer-name)#end
+## if the first parameter already has already been quoted we can override the default
+ #hideNullJson($siidTag,$service-instance-id,false,true,false)#end
+ #hideNullJson("customer-phone-number",$customer-phone-number)#end
+ }
+ }
+}
\ No newline at end of file