Merge "Fixnig file import in script, import and template&mapping."
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / configs-api / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / configs / api / ResourceConfigSnapshotController.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.configs.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.config.snapshots.db.ResourceConfigSnapshot
25 import org.onap.ccsdk.cds.blueprintsprocessor.functions.config.snapshots.db.ResourceConfigSnapshotService
26 import org.onap.ccsdk.cds.controllerblueprints.core.asJsonPrimitive
27 import org.onap.ccsdk.cds.controllerblueprints.core.httpProcessorException
28 import org.onap.ccsdk.cds.error.catalog.core.ErrorCatalogCodes
29 import org.onap.ccsdk.cds.error.catalog.core.utils.errorCauseOrDefault
30 import org.springframework.http.MediaType
31 import org.springframework.http.ResponseEntity
32 import org.springframework.security.access.prepost.PreAuthorize
33 import org.springframework.web.bind.annotation.PathVariable
34 import org.springframework.web.bind.annotation.PostMapping
35 import org.springframework.web.bind.annotation.RequestBody
36 import org.springframework.web.bind.annotation.RequestMapping
37 import org.springframework.web.bind.annotation.RequestMethod
38 import org.springframework.web.bind.annotation.RequestParam
39 import org.springframework.web.bind.annotation.ResponseBody
40 import org.springframework.web.bind.annotation.RestController
41
42 /**
43  * Exposes Resource Configuration Snapshot API to store and retrieve stored resource configurations.
44  *
45  * @author Serge Simard
46  * @version 1.0
47  */
48 @RestController
49 @RequestMapping("/api/v1/configs")
50 @Api(
51     value = "/api/v1/configs",
52     description = "Interaction with stored configurations."
53 )
54 open class ResourceConfigSnapshotController(private val resourceConfigSnapshotService: ResourceConfigSnapshotService) {
55
56     @RequestMapping(
57         path = ["/health-check"],
58         method = [RequestMethod.GET],
59         produces = [MediaType.APPLICATION_JSON_VALUE]
60     )
61     @ResponseBody
62     @ApiOperation(value = "Health Check", hidden = true)
63     fun ressCfgSnapshotControllerHealthCheck(): JsonNode = runBlocking {
64         "Success".asJsonPrimitive()
65     }
66
67     @RequestMapping(
68         path = [""],
69         method = [RequestMethod.GET],
70         produces = [MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE]
71     )
72     @ApiOperation(
73         value = "Retrieve a resource configuration snapshot.",
74         notes = "Retrieve a config snapshot, identified by its Resource Id and Type. " +
75                 "An extra 'format' parameter can be passed to tell what content-type is expected."
76     )
77     @ResponseBody
78     @PreAuthorize("hasRole('USER')")
79     fun get(
80         @ApiParam(value = "Resource Type associated of the resource configuration snapshot.", required = false)
81         @RequestParam(value = "resourceType", required = true) resourceType: String,
82
83         @ApiParam(value = "Resource Id associated of the resource configuration snapshot.", required = false)
84         @RequestParam(value = "resourceId", required = true) resourceId: String,
85
86         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = false)
87         @RequestParam(value = "status", required = false, defaultValue = "RUNNING") status: String,
88
89         @ApiParam(
90             value = "Expected format of the snapshot being retrieved.", defaultValue = MediaType.TEXT_PLAIN_VALUE,
91             required = false
92         )
93         @RequestParam(value = "format", required = false, defaultValue = MediaType.TEXT_PLAIN_VALUE) format: String
94     ):
95
96             ResponseEntity<String> = runBlocking {
97
98         var configSnapshot = ""
99
100         if (resourceType.isNotEmpty() && resourceId.isNotEmpty()) {
101             try {
102                 configSnapshot = resourceConfigSnapshotService.findByResourceIdAndResourceTypeAndStatus(
103                     resourceId,
104                     resourceType, ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
105                 )
106             } catch (ex: NoSuchElementException) {
107                 throw httpProcessorException(ErrorCatalogCodes.RESOURCE_NOT_FOUND, ConfigsApiDomains.CONFIGS_API,
108                         "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
109                         ex.errorCauseOrDefault())
110             } catch (ex: Exception) {
111                 throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
112                         "Could not find configuration snapshot entry for type $resourceType and Id $resourceId",
113                         ex.errorCauseOrDefault())
114             }
115         } else {
116             throw httpProcessorException(ErrorCatalogCodes.INVALID_REQUEST_FORMAT, ConfigsApiDomains.CONFIGS_API,
117                     "Missing param. You must specify resource-id and resource-type.")
118         }
119
120         var expectedContentType = format
121         if (expectedContentType.indexOf('/') < 0) {
122             expectedContentType = "application/$expectedContentType"
123         }
124         val expectedMediaType: MediaType = MediaType.valueOf(expectedContentType)
125
126         ResponseEntity.ok().contentType(expectedMediaType).body(configSnapshot)
127     }
128
129     @PostMapping(
130         "/{resourceType}/{resourceId}/{status}",
131         produces = [MediaType.APPLICATION_JSON_VALUE]
132     )
133     @ApiOperation(
134         value = "Store a resource configuration snapshot identified by resourceId, resourceType, status.",
135         notes = "Store a resource configuration snapshot, identified by its resourceId and resourceType, " +
136                 "and optionally its status, either RUNNING or CANDIDATE.",
137         response = ResourceConfigSnapshot::class, produces = MediaType.APPLICATION_JSON_VALUE
138     )
139     @ResponseBody
140     @PreAuthorize("hasRole('USER')")
141     fun postWithResourceIdAndResourceType(
142         @ApiParam(value = "Resource Type associated with the resolution.", required = false)
143         @PathVariable(value = "resourceType", required = true) resourceType: String,
144         @ApiParam(value = "Resource Id associated with the resolution.", required = false)
145         @PathVariable(value = "resourceId", required = true) resourceId: String,
146         @ApiParam(value = "Status of the snapshot being retrieved.", defaultValue = "RUNNING", required = true)
147         @PathVariable(value = "status", required = true) status: String,
148         @ApiParam(value = "Config snapshot to store.", required = true)
149         @RequestBody snapshot: String
150     ): ResponseEntity<ResourceConfigSnapshot> = runBlocking {
151
152         val resultStored =
153             resourceConfigSnapshotService.write(
154                 snapshot, resourceId, resourceType,
155                 ResourceConfigSnapshot.Status.valueOf(status.toUpperCase())
156             )
157
158         ResponseEntity.ok().body(resultStored)
159     }
160 }