Adding some minor features
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / resource-api / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / resource / api / TemplateController.kt
1 /*
2  * Copyright © 2019 Bell Canada
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.onap.ccsdk.cds.blueprintsprocessor.resource.api
18
19 import com.fasterxml.jackson.databind.JsonNode
20 import io.swagger.annotations.Api
21 import io.swagger.annotations.ApiOperation
22 import io.swagger.annotations.ApiParam
23 import kotlinx.coroutines.runBlocking
24 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.TemplateResolution
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.resource.resolution.db.TemplateResolutionService
26 import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException
27 import org.onap.ccsdk.cds.controllerblueprints.core.utils.JacksonUtils
28 import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes
29 import org.springframework.http.MediaType
30 import org.springframework.http.ResponseEntity
31 import org.springframework.security.access.prepost.PreAuthorize
32 import org.springframework.web.bind.annotation.PathVariable
33 import org.springframework.web.bind.annotation.PostMapping
34 import org.springframework.web.bind.annotation.RequestBody
35 import org.springframework.web.bind.annotation.RequestMapping
36 import org.springframework.web.bind.annotation.RequestMethod
37 import org.springframework.web.bind.annotation.RequestParam
38 import org.springframework.web.bind.annotation.ResponseBody
39 import org.springframework.web.bind.annotation.RestController
40
41 /**
42  * Exposes Template Resolution API to store and retrieve rendered template results.
43  *
44  * @author Serge Simard
45  * @version 1.0
46  */
47 @RestController
48 @RequestMapping("/api/v1/template")
49 @Api(
50     value = "Resource Template",
51     description = "Interaction with resolved templates"
52 )
53 open class TemplateController(private val templateResolutionService: TemplateResolutionService) {
54
55     @RequestMapping(
56         path = ["/health-check"],
57         method = [RequestMethod.GET],
58         produces = [MediaType.APPLICATION_JSON_VALUE]
59     )
60     @ResponseBody
61     @ApiOperation(value = "Health Check", hidden = true)
62     fun templateControllerHealthCheck(): JsonNode = runBlocking {
63         JacksonUtils.getJsonNode("Success")
64     }
65
66     @RequestMapping(
67         path = [""],
68         method = [RequestMethod.GET],
69         produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
70     )
71     @ApiOperation(
72         value = "Retrieve a resolved template",
73         notes = "Retrieve a config template for a given CBA's action, identified by its blueprint name, blueprint version, " +
74             "artifact name and resolution key. An extra 'format' parameter can be passed to tell what content-type" +
75             " to expect in return"
76     )
77     @ResponseBody
78     @PreAuthorize("hasRole('USER')")
79     fun get(
80         @ApiParam(value = "Name of the CBA", required = true)
81         @RequestParam(value = "bpName") bpName: String,
82         @ApiParam(value = "Version of the CBA", required = true)
83         @RequestParam(value = "bpVersion") bpVersion: String,
84         @ApiParam(value = "Artifact name for which to retrieve a resolved resource", required = true)
85         @RequestParam(value = "artifactName") artifactName: String,
86         @ApiParam(value = "Resolution Key associated with the resolution", required = false)
87         @RequestParam(value = "resolutionKey", required = false, defaultValue = "") resolutionKey: String,
88         @ApiParam(value = "Resource Type associated with the resolution", required = false)
89         @RequestParam(value = "resourceType", required = false, defaultValue = "") resourceType: String,
90         @ApiParam(value = "Resource Id associated with the resolution", required = false)
91         @RequestParam(value = "resourceId", required = false, defaultValue = "") resourceId: String,
92         @ApiParam(
93             value = "Expected format of the template being retrieved",
94             defaultValue = MediaType.TEXT_PLAIN_VALUE,
95             required = true
96         )
97         @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String,
98         @ApiParam(value = "Occurrence of the template resolution (1-n)", required = false)
99         @RequestParam(value = "occurrence", required = false, defaultValue = "1") occurrence: Int = 1
100     ):
101         ResponseEntity<String> = runBlocking {
102
103             var result = ""
104
105             if (resolutionKey.isNotEmpty() && (resourceId.isNotEmpty() || resourceType.isNotEmpty())) {
106                 throw httpProcessorException(
107                     ErrorCatalogCodes.REQUEST_NOT_FOUND, ResourceApiDomains.RESOURCE_API,
108                     "Either retrieve resolved template using resolution-key OR using resource-id and resource-type."
109                 )
110             } else if (resolutionKey.isNotEmpty() && artifactName.isNotEmpty()) {
111                 result = templateResolutionService.findByResolutionKeyAndBlueprintNameAndBlueprintVersionAndArtifactName(
112                     bpName,
113                     bpVersion,
114                     artifactName,
115                     resolutionKey,
116                     occurrence
117                 )
118             } else if (resourceType.isNotEmpty() && resourceId.isNotEmpty() && artifactName.isNotEmpty()) {
119                 result =
120                     templateResolutionService.findByResoureIdAndResourceTypeAndBlueprintNameAndBlueprintVersionAndArtifactName(
121                         bpName,
122                         bpVersion,
123                         artifactName,
124                         resourceId,
125                         resourceType,
126                         occurrence
127                     )
128             } else {
129                 throw httpProcessorException(
130                     ErrorCatalogCodes.REQUEST_NOT_FOUND, ResourceApiDomains.RESOURCE_API,
131                     "Missing param. Either retrieve resolved template using artifact name and resolution-key OR using resource-id and resource-type."
132                 )
133             }
134
135             var expectedContentType = format
136             if (expectedContentType.indexOf('/') < 0) {
137                 expectedContentType = "application/$expectedContentType"
138             }
139             val expectedMediaType: MediaType = MediaType.valueOf(expectedContentType)
140
141             ResponseEntity.ok().contentType(expectedMediaType).body(result)
142         }
143
144     @PostMapping("/{bpName}/{bpVersion}/{artifactName}/{resolutionKey}", produces = [MediaType.APPLICATION_JSON_VALUE])
145     @ApiOperation(
146         value = "Store a resolved template w/ resolution-key",
147         notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
148             "artifact name and resolution key.",
149         response = TemplateResolution::class
150     )
151     @ResponseBody
152     @PreAuthorize("hasRole('USER')")
153     fun postWithResolutionKey(
154         @ApiParam(value = "Name of the CBA", required = true)
155         @PathVariable(value = "bpName") bpName: String,
156         @ApiParam(value = "Version of the CBA", required = true)
157         @PathVariable(value = "bpVersion") bpVersion: String,
158         @ApiParam(value = "Artifact name for which to retrieve a resolved resource", required = true)
159         @PathVariable(value = "artifactName") artifactName: String,
160         @ApiParam(value = "Resolution Key associated with the resolution", required = true)
161         @PathVariable(value = "resolutionKey") resolutionKey: String,
162         @ApiParam(value = "Template to store", required = true)
163         @RequestBody result: String
164     ): ResponseEntity<TemplateResolution> = runBlocking {
165
166         val resultStored =
167             templateResolutionService.write(bpName, bpVersion, artifactName, result, resolutionKey = resolutionKey)
168
169         ResponseEntity.ok().body(resultStored)
170     }
171
172     @RequestMapping(
173         path = ["/occurrences"],
174         method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE]
175     )
176     @ApiOperation(
177         value = "Get the map of resolved templates with 'occurrence' as the keys to the resolved templates ",
178         notes = "With optional 'occurrence' options, subset of stored resolved templates can be retrieved " +
179             "using the blueprint name, blueprint version, artifact name and the resolution-key.",
180         response = TemplateResolution::class,
181         responseContainer = "List",
182         produces = MediaType.APPLICATION_JSON_VALUE
183     )
184     @ResponseBody
185     @PreAuthorize("hasRole('USER')")
186     fun getOccurrences(
187         @ApiParam(value = "Name of the CBA.", required = true)
188         @RequestParam(value = "bpName", required = true) bpName: String,
189         @ApiParam(value = "Version of the CBA.", required = true)
190         @RequestParam(value = "bpVersion", required = true) bpVersion: String,
191         @ApiParam(value = "Artifact name for which to retrieve a resolved resource.", required = true)
192         @RequestParam(value = "artifactName", required = true, defaultValue = "") artifactName: String,
193         @ApiParam(value = "Resolution Key associated with the resolution.", required = true)
194         @RequestParam(value = "resolutionKey", required = true, defaultValue = "") resolutionKey: String,
195         @ApiParam(value = "Number of earlier N occurrences of the templates.", required = false)
196         @RequestParam(value = "firstN", required = false) firstN: Int?,
197         @ApiParam(value = "Number of latest N occurrences of the templates.", required = false)
198         @RequestParam(value = "lastN", required = false) lastN: Int?,
199         @ApiParam(value = "For Range option - 'begin' is the start occurrence of range of the templates.", required = false)
200         @RequestParam(value = "begin", required = false) begin: Int?,
201         @ApiParam(value = "For Range option - 'end' is the end occurrence of the range of the templates.", required = false)
202         @RequestParam(value = "end", required = false) end: Int?
203     ): ResponseEntity<Map<Int, List<TemplateResolution>>> = runBlocking {
204         when {
205             artifactName.isEmpty() -> "'artifactName' must not be empty"
206             resolutionKey.isEmpty() -> "'resolutionKey' must not be empty"
207             // Optional options - validate if provided
208             (firstN != null && lastN != null) -> "Retrieve occurrences using either 'firstN'  OR 'lastN' option"
209             ((firstN != null || lastN != null) && (begin != null || end != null)) -> "Retrieve occurrences using either 'firstN'  OR 'lastN' OR 'begin' and 'end' option."
210             ((begin != null && end == null) || (begin == null && end != null)) -> " Retrieving occurrences within range - please provide both 'begin' and 'end' option"
211             else -> null
212         }?.let { throw httpProcessorException(ErrorCatalogCodes.REQUEST_NOT_FOUND, ResourceApiDomains.RESOURCE_API, it) }
213
214         when {
215             firstN != null ->
216                 templateResolutionService.findFirstNOccurrences(bpName, bpVersion, artifactName, resolutionKey, firstN)
217             lastN != null ->
218                 templateResolutionService.findLastNOccurrences(bpName, bpVersion, artifactName, resolutionKey, lastN)
219             begin != null && end != null ->
220                 templateResolutionService.findOccurrencesWithinRange(bpName, bpVersion, artifactName, resolutionKey, begin, end)
221             else ->
222                 templateResolutionService.readWithResolutionKey(bpName, bpVersion, artifactName, resolutionKey).groupBy(TemplateResolution::occurrence).toSortedMap(reverseOrder())
223         }.let { result -> ResponseEntity.ok().body(result) }
224     }
225
226     @PostMapping(
227         "/{bpName}/{bpVersion}/{artifactName}/{resourceType}/{resourceId}",
228         produces = [MediaType.APPLICATION_JSON_VALUE]
229     )
230     @ApiOperation(
231         value = "Store a resolved template w/ resourceId and resourceType",
232         notes = "Store a template for a given CBA's action, identified by its blueprint name, blueprint version, " +
233             "artifact name, resourceId and resourceType.",
234         response = TemplateResolution::class
235     )
236     @ResponseBody
237     @PreAuthorize("hasRole('USER')")
238     fun postWithResourceIdAndResourceType(
239         @ApiParam(value = "Name of the CBA", required = true)
240         @PathVariable(value = "bpName") bpName: String,
241         @ApiParam(value = "Version of the CBA", required = true)
242         @PathVariable(value = "bpVersion") bpVersion: String,
243         @ApiParam(value = "Artifact name for which to retrieve a resolved resource", required = true)
244         @PathVariable(value = "artifactName") artifactName: String,
245         @ApiParam(value = "Resource Type associated with the resolution", required = false)
246         @PathVariable(value = "resourceType", required = true) resourceType: String,
247         @ApiParam(value = "Resource Id associated with the resolution", required = false)
248         @PathVariable(value = "resourceId", required = true) resourceId: String,
249         @ApiParam(value = "Template to store", required = true)
250         @RequestBody result: String
251     ): ResponseEntity<TemplateResolution> = runBlocking {
252
253         val resultStored =
254             templateResolutionService.write(bpName, bpVersion, artifactName, result, resourceId = resourceId, resourceType = resourceType)
255
256         ResponseEntity.ok().body(resultStored)
257     }
258
259     @RequestMapping(
260         path = [""],
261         method = [RequestMethod.DELETE], produces = [MediaType.APPLICATION_JSON_VALUE]
262     )
263     @PreAuthorize("hasRole('USER')")
264     fun deleteTemplates(
265         @ApiParam(value = "Name of the CBA", required = true)
266         @RequestParam(value = "bpName", required = true) bpName: String,
267         @ApiParam(value = "Version of the CBA", required = true)
268         @RequestParam(value = "bpVersion", required = true) bpVersion: String,
269         @ApiParam(value = "Artifact name", required = true)
270         @RequestParam(value = "artifactName", required = true, defaultValue = "") artifactName: String,
271         @ApiParam(value = "Resolution Key associated with the template", required = false)
272         @RequestParam(value = "resolutionKey", required = false) resolutionKey: String?,
273         @ApiParam(value = "resourceType associated with the template, must be used with resourceId", required = false)
274         @RequestParam(value = "resourceType", required = false) resourceType: String?,
275         @ApiParam(value = "Resolution Key associated with the template, must be used with resourceType", required = false)
276         @RequestParam(value = "resourceId", required = false) resourceId: String?,
277         @ApiParam(value = "Only delete last N occurrences", required = false)
278         @RequestParam(value = "lastN", required = false) lastN: Int?
279     ) = runBlocking {
280         when {
281             resolutionKey?.isNotBlank() == true -> templateResolutionService.deleteTemplates(
282                 bpName, bpVersion, artifactName, resolutionKey, lastN
283             )
284             resourceType?.isNotBlank() == true && resourceId?.isNotBlank() == true ->
285                 templateResolutionService.deleteTemplates(
286                     bpName, bpVersion, artifactName, resourceType, resourceId, lastN
287                 )
288             else -> throw httpProcessorException(
289                 ErrorCatalogCodes.REQUEST_NOT_FOUND,
290                 ResourceApiDomains.RESOURCE_API,
291                 "Either use resolutionKey or resourceType + resourceId. Values cannot be blank"
292             )
293         }.let { ResponseEntity.ok().body(DeleteResponse(it)) }
294     }
295 }