aboutsummaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/functions/resource-resolution/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/functions/resource/resolution/mock/MockRestResourceResolutionProcessor.kt
blob: 77c90ba5194828412e754037b33de54349094f8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/*
 * Copyright © 2019 IBM, Bell Canada.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.mock

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import org.apache.commons.collections.MapUtils
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.ResourceResolutionConstants
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.RestResourceSource
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.processor.ResourceAssignmentProcessor
import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.utils.ResourceAssignmentUtils
import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintProcessorException
import org.onap.ccsdk.cds.controllerblueprints.core.BlueprintTypes
import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
import org.onap.ccsdk.cds.controllerblueprints.core.nullToEmpty
import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
import org.onap.ccsdk.cds.controllerblueprints.resource.dict.ResourceAssignment
import org.slf4j.LoggerFactory
import java.util.HashMap

class MockRestResourceResolutionProcessor(
    private val blueprintRestLibPropertyService:
        MockBlueprintRestLibPropertyService
) : ResourceAssignmentProcessor() {

    private val logger = LoggerFactory.getLogger(MockRestResourceResolutionProcessor::class.java)

    override fun resolveInputKeyMappingVariables(inputKeyMapping: Map<String, String>): Map<String, JsonNode> {
        val resolvedInputKeyMapping = HashMap<String, JsonNode>()
        if (MapUtils.isNotEmpty(inputKeyMapping)) {

            resolvedInputKeyMapping["service-instance-id"] = "10".asJsonPrimitive()
            resolvedInputKeyMapping["vnf_name"] = "vnf1".asJsonPrimitive()
            resolvedInputKeyMapping["vnf-id"] = "123456".asJsonPrimitive()
        }
        return resolvedInputKeyMapping
    }

    override fun getName(): String {
        return "${ResourceResolutionConstants.PREFIX_RESOURCE_RESOLUTION_PROCESSOR}source-rest"
    }

    override suspend fun processNB(executionRequest: ResourceAssignment) {
        try {
            // Check if It has Input
            if (!setFromInput(executionRequest)) {
                val dName = executionRequest.dictionaryName
                val dSource = executionRequest.dictionarySource
                val resourceDefinition = resourceDictionaries[dName]

                val resourceSource = resourceDefinition!!.sources[dSource]

                val resourceSourceProperties = resourceSource!!.properties

                val sourceProperties =
                    JacksonUtils.getInstanceFromMap(resourceSourceProperties!!, RestResourceSource::class.java)

                val path = nullToEmpty(sourceProperties.path)
                val inputKeyMapping = sourceProperties.inputKeyMapping

                val resolvedInputKeyMapping = resolveInputKeyMappingVariables(inputKeyMapping!!).toMutableMap()

                // Resolving content Variables
                val payload = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.payload), resolvedInputKeyMapping)
                val urlPath =
                    resolveFromInputKeyMapping(checkNotNull(sourceProperties.urlPath), resolvedInputKeyMapping)
                val verb = resolveFromInputKeyMapping(nullToEmpty(sourceProperties.verb), resolvedInputKeyMapping)

                logger.info(
                    "MockRestResource ($dSource) dictionary information: " +
                        "URL:($urlPath), input-key-mapping:($inputKeyMapping), output-key-mapping:(${sourceProperties.outputKeyMapping})"
                )

                // Get the Rest Client Service
                val restClientService = blueprintWebClientService(executionRequest)

                val response = restClientService.exchangeResource(verb, urlPath, payload)
                val responseStatusCode = response.status
                val responseBody = response.body
                if (responseStatusCode in 200..299 && !responseBody.isBlank()) {
                    populateResource(executionRequest, sourceProperties, responseBody, path)
                    restClientService.tearDown()
                } else {
                    val errMsg =
                        "Failed to get $dSource result for dictionary name ($dName) using urlPath ($urlPath) response_code: ($responseStatusCode)"
                    logger.warn(errMsg)
                    throw BlueprintProcessorException(errMsg)
                }
            }
        } catch (e: Exception) {
            ResourceAssignmentUtils.setFailedResourceDataValue(executionRequest, e.message)
            throw BlueprintProcessorException(
                "Failed in template resolutionKey ($executionRequest) assignments with: ${e.message}",
                e
            )
        }
    }

    override suspend fun recoverNB(runtimeException: RuntimeException, executionRequest: ResourceAssignment) {
        addError(runtimeException.message!!)
    }

    private fun blueprintWebClientService(resourceAssignment: ResourceAssignment): MockBlueprintWebClientService {
        return blueprintRestLibPropertyService.mockBlueprintWebClientService(resourceAssignment.dictionarySource!!)
    }

    @Throws(BlueprintProcessorException::class)
    private fun populateResource(
        resourceAssignment: ResourceAssignment,
        sourceProperties: RestResourceSource,
        restResponse: String,
        path: String
    ) {
        val type = nullToEmpty(resourceAssignment.property?.type)
        lateinit var entrySchemaType: String

        val outputKeyMapping = sourceProperties.outputKeyMapping

        val responseNode = JacksonUtils.jsonNode(restResponse).at(path)

        when (type) {
            in BlueprintTypes.validPrimitiveTypes() -> {
                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, responseNode)
            }
            in BlueprintTypes.validCollectionTypes() -> {
                // Array Types
                entrySchemaType = resourceAssignment.property!!.entrySchema!!.type
                val arrayNode = responseNode as ArrayNode

                if (entrySchemaType !in BlueprintTypes.validPrimitiveTypes()) {
                    val responseArrayNode = responseNode.toList()
                    for (responseSingleJsonNode in responseArrayNode) {

                        val arrayChildNode = JacksonUtils.objectMapper.createObjectNode()

                        outputKeyMapping!!.map {
                            val responseKeyValue = responseSingleJsonNode.get(it.key)
                            val propertyTypeForDataType = ResourceAssignmentUtils
                                .getPropertyType(raRuntimeService, entrySchemaType, it.key)

                            JacksonUtils.populateJsonNodeValues(
                                it.value,
                                responseKeyValue, propertyTypeForDataType, arrayChildNode
                            )
                        }
                        arrayNode.add(arrayChildNode)
                    }
                }
                // Set the List of Complex Values
                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, arrayNode)
            }
            else -> {
                // Complex Types
                entrySchemaType = resourceAssignment.property!!.type
                val objectNode = JacksonUtils.objectMapper.createObjectNode()
                outputKeyMapping!!.map {
                    val responseKeyValue = responseNode.get(it.key)
                    val propertyTypeForDataType = ResourceAssignmentUtils
                        .getPropertyType(raRuntimeService, entrySchemaType, it.key)
                    JacksonUtils.populateJsonNodeValues(it.value, responseKeyValue, propertyTypeForDataType, objectNode)
                }
                // Set the List of Complex Values
                ResourceAssignmentUtils.setResourceDataValue(resourceAssignment, raRuntimeService, objectNode)
            }
        }
    }
}