2 * Copyright © 2017-2018 AT&T Intellectual Property.
4 * Modifications Copyright © 2019 IBM, Bell Canada.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
19 package org.onap.ccsdk.cds.controllerblueprints.core.service
21 import com.fasterxml.jackson.databind.JsonNode
22 import com.fasterxml.jackson.databind.ObjectMapper
23 import org.apache.commons.lang3.BooleanUtils
24 import org.apache.commons.lang3.StringUtils
25 import org.apache.velocity.VelocityContext
26 import org.apache.velocity.app.VelocityEngine
27 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
28 import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintJsonNodeFactory
29 import org.onap.ccsdk.cds.controllerblueprints.core.removeNullNode
30 import java.io.StringWriter
32 object BluePrintVelocityTemplateService {
35 * Generate Content from Velocity Template and JSON Content with injected API
40 ignoreJsonNull: Boolean = false,
41 additionalContext: MutableMap<String, Any> = mutableMapOf()
44 // Customized Object Mapper to remove String double quotes
45 val mapper = ObjectMapper()
46 val nodeFactory = BluePrintJsonNodeFactory()
47 mapper.nodeFactory = nodeFactory
49 val jsonNode: JsonNode? = if (json.isNotEmpty()) {
50 mapper.readValue(json, JsonNode::class.java)
51 ?: throw BluePrintProcessorException("couldn't get json node from json")
55 return generateContent(template, jsonNode, ignoreJsonNull, additionalContext)
59 * Generate Content from Velocity Template and JSON Node with injected API
64 ignoreJsonNull: Boolean = false,
65 additionalContext: MutableMap<String, Any> = mutableMapOf()
69 * create a new instance of the velocity engine
71 val velocity = VelocityEngine()
74 * initialize the engine
78 val velocityContext = VelocityContext()
79 velocityContext.put("StringUtils", StringUtils::class.java)
80 velocityContext.put("BooleanUtils", BooleanUtils::class.java)
82 // Add the Custom Velocity Context API
83 additionalContext.forEach { (name, value) -> velocityContext.put(name, value) }
85 // Add the JSON Data to the context
86 if (jsonNode != null) {
88 jsonNode.removeNullNode()
89 jsonNode.fields().forEach { entry ->
90 velocityContext.put(entry.key, entry.value)
94 val stringWriter = StringWriter()
95 velocity.evaluate(velocityContext, stringWriter, "TemplateData", template)
97 return stringWriter.toString()