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.interfaces.BlueprintTemplateService
30 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
31 import java.io.StringWriter
33 object BluePrintVelocityTemplateService: BlueprintTemplateService {
36 * Generate Content from Velocity Template and JSON Content or property map.
38 override suspend fun generateContent(template: String, json: String, ignoreJsonNull: Boolean, additionalContext:
39 MutableMap<String, Any>): String {
41 val mapper = ObjectMapper()
42 val nodeFactory = BluePrintJsonNodeFactory()
43 mapper.nodeFactory = nodeFactory
45 val velocityContext = VelocityContext()
46 velocityContext.put("StringUtils", StringUtils::class.java)
47 velocityContext.put("BooleanUtils", BooleanUtils::class.java)
49 // Add the Custom Velocity Context API
50 additionalContext.forEach { name, value -> velocityContext.put(name, value) }
52 // Add the JSON Data to the context
53 if (json.isNotEmpty()) {
54 val jsonNode = mapper.readValue<JsonNode>(json, JsonNode::class.java)
55 ?: throw BluePrintProcessorException("couldn't get json node from json")
57 JacksonUtils.removeJsonNullNode(jsonNode)
58 jsonNode.fields().forEach { entry ->
59 velocityContext.put(entry.key, entry.value)
63 val stringWriter = StringWriter()
64 Velocity.evaluate(velocityContext, stringWriter, "TemplateData", template)
66 return stringWriter.toString()