2 * Copyright © 2017-2018 AT&T Intellectual Property.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.onap.ccsdk.cds.controllerblueprints.core.service
19 import com.fasterxml.jackson.core.io.CharTypes
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.fasterxml.jackson.databind.ObjectMapper
22 import com.fasterxml.jackson.databind.node.JsonNodeFactory
23 import com.fasterxml.jackson.databind.node.TextNode
24 import org.apache.commons.lang3.BooleanUtils
25 import org.apache.commons.lang3.StringUtils
26 import org.apache.velocity.VelocityContext
27 import org.apache.velocity.app.Velocity
28 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
30 import java.io.StringWriter
32 open class BluePrintTemplateService {
37 * Generate Content from Velocity Template and JSON Content or property map.
39 fun generateContent(template: String, json: String = "",
40 ignoreJsonNull: Boolean = false,
41 additionalContext: Map<String, Any> = hashMapOf()): String {
43 val mapper = ObjectMapper()
44 val nodeFactory = BluePrintJsonNodeFactory()
45 mapper.nodeFactory = nodeFactory
47 val velocityContext = VelocityContext()
48 velocityContext.put("StringUtils", StringUtils::class.java)
49 velocityContext.put("BooleanUtils", BooleanUtils::class.java)
51 // Add the Custom Velocity Context API
52 additionalContext.forEach { name, value -> velocityContext.put(name, value) }
54 // Add the JSON Data to the context
55 if (json.isNotEmpty()) {
56 val jsonNode = mapper.readValue<JsonNode>(json, JsonNode::class.java)
57 ?: throw BluePrintProcessorException("couldn't get json node from json")
59 JacksonUtils.removeJsonNullNode(jsonNode)
60 jsonNode.fields().forEach { entry ->
61 velocityContext.put(entry.key, entry.value)
65 val stringWriter = StringWriter()
66 Velocity.evaluate(velocityContext, stringWriter, "TemplateData", template)
68 return stringWriter.toString()
74 * Customise JsonNodeFactory adn TextNode, Since it introduces quotes for string data.
76 open class BluePrintJsonNodeFactory : JsonNodeFactory() {
77 override fun textNode(text: String): TextNode {
78 return BluePrintTextNode(text)
82 open class BluePrintTextNode(v: String) : TextNode(v) {
83 override fun toString(): String {
84 var len = this._value.length
85 len = len + 2 + (len shr 4)
86 val sb = StringBuilder(len)
87 CharTypes.appendQuoted(sb, this._value)