2 package org.onap.ccsdk.sli.plugins.template;
4 import java.io.IOException;
7 import org.apache.velocity.context.InternalContextAdapter;
8 import org.apache.velocity.exception.MethodInvocationException;
9 import org.apache.velocity.exception.ParseErrorException;
10 import org.apache.velocity.exception.ResourceNotFoundException;
11 import org.apache.velocity.runtime.directive.Directive;
12 import org.apache.velocity.runtime.parser.node.Node;
14 // This directive can be used when handling optional json attributes in a template
15 // If an attribute value is null the entire name-value pair will not be rendered
16 // If an attribute value is not null the name-value pair will be rendered
17 // Additional optional parameters decide which values are quoted and if a comma and or newline should be appended
18 public class HideNullJson extends Directive {
20 public String getName() {
21 return "hideNullJson";
24 public int getType() {
28 // The first parameter is the json key
29 // The second parameter is the json value
30 // This directive handles placing the colon between the json key and json value
31 // The third parameter is a boolean, when true the json key is surrounded in double quotes by this directive
32 // The third parameter is true by default and is optional
33 // The fourth parameter is a boolean when true the json value is surrounded in double quotes by this directive
34 // The fourth parameter is true by default and is optional
35 // The fifth parameter is a boolean when true a comma is appended to the end
36 // The fifth parameter is true by default and is optional
37 // The sixth parameter is a boolean when true a newline is appended to the end
38 // The sixth parameter is true by default and is optional
39 public boolean render(InternalContextAdapter context, Writer writer, Node node)
40 throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
41 String tagValue = null;
42 Object tagValueObject = node.jjtGetChild(1).value(context);
43 if (tagValueObject == null) {
46 tagValue = String.valueOf(tagValueObject);
48 String tagName = String.valueOf(node.jjtGetChild(0).value(context));
50 Boolean quoteTagName = getBooleanParameter(true,node,2,context);
51 Boolean quoteTagValue = getBooleanParameter(true,node,3,context);
52 Boolean appendComma = getBooleanParameter(true,node,4,context);
53 Boolean appendNewLine = getBooleanParameter(true,node,5,context);
55 StringBuilder sb = new StringBuilder();
58 appendQuotedString(tagName,sb);
66 appendQuotedString(tagValue,sb);
78 writer.write(sb.toString());
82 private Boolean getBooleanParameter(Boolean defaultBool, Node node, int parameterPostion, InternalContextAdapter context) {
83 if (node.jjtGetNumChildren() > parameterPostion && node.jjtGetChild(parameterPostion) != null) {
84 Object val = node.jjtGetChild(parameterPostion).value(context);
92 private void appendQuotedString(String str, StringBuilder sb) {