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.apps.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.apps.controllerblueprints.core.BluePrintProcessorException
29 import org.onap.ccsdk.apps.controllerblueprints.core.utils.JacksonUtils
30 import java.io.StringWriter
32 open class BluePrintTemplateService {
37 * Generate Content from Velocity Template and JSON Content.
39 fun generateContent(template: String, json: String,
40 ignoreJsonNull: Boolean = false,
41 additionalContext: MutableMap<String, Any> = hashMapOf()): String {
43 val mapper = ObjectMapper()
44 val nodeFactory = BluePrintJsonNodeFactory()
45 mapper.setNodeFactory(nodeFactory)
47 val jsonNode = mapper.readValue<JsonNode>(json, JsonNode::class.java)
48 ?: throw BluePrintProcessorException("couldn't get json node from json")
51 JacksonUtils.removeJsonNullNode(jsonNode)
53 val velocityContext = VelocityContext()
54 velocityContext.put("StringUtils", StringUtils::class.java)
55 velocityContext.put("BooleanUtils", BooleanUtils::class.java)
57 * Add the Custom Velocity Context API
59 additionalContext.forEach { name, value -> velocityContext.put(name, value) }
61 * Add the JSON Data to the context
63 jsonNode.fields().forEach { entry ->
64 velocityContext.put(entry.key, entry.value)
67 val stringWriter = StringWriter()
68 Velocity.evaluate(velocityContext, stringWriter, "TemplateData", template)
70 return stringWriter.toString()
76 * Customise JsonNodeFactory adn TextNode, Since it introduces quotes for string data.
78 open class BluePrintJsonNodeFactory : JsonNodeFactory() {
79 override fun textNode(text: String): TextNode {
80 return BluePrintTextNode(text)
84 open class BluePrintTextNode(v: String) : TextNode(v) {
85 override fun toString(): String {
86 var len = this._value.length
87 len = len + 2 + (len shr 4)
88 val sb = StringBuilder(len)
89 CharTypes.appendQuoted(sb, this._value)