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.Velocity
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
37 fun generateContent(template: String, json: String, ignoreJsonNull: Boolean = false,
38 additionalContext: MutableMap<String, Any> = mutableMapOf()): String {
40 // Customized Object Mapper to remove String double quotes
41 val mapper = ObjectMapper()
42 val nodeFactory = BluePrintJsonNodeFactory()
43 mapper.nodeFactory = nodeFactory
45 val jsonNode: JsonNode? = if (json.isNotEmpty()) {
46 mapper.readValue(json, JsonNode::class.java)
47 ?: throw BluePrintProcessorException("couldn't get json node from json")
51 return generateContent(template, jsonNode, ignoreJsonNull, additionalContext)
55 * Generate Content from Velocity Template and JSON Node with injected API
57 fun generateContent(template: String, jsonNode: JsonNode?, ignoreJsonNull: Boolean = false,
58 additionalContext: MutableMap<String, Any> = mutableMapOf()): String {
62 val velocityContext = VelocityContext()
63 velocityContext.put("StringUtils", StringUtils::class.java)
64 velocityContext.put("BooleanUtils", BooleanUtils::class.java)
66 // Add the Custom Velocity Context API
67 additionalContext.forEach { (name, value) -> velocityContext.put(name, value) }
69 // Add the JSON Data to the context
70 if (jsonNode != null) {
72 jsonNode.removeNullNode()
73 jsonNode.fields().forEach { entry ->
74 velocityContext.put(entry.key, entry.value)
78 val stringWriter = StringWriter()
79 Velocity.evaluate(velocityContext, stringWriter, "TemplateData", template)
81 return stringWriter.toString()