summaryrefslogtreecommitdiffstats
path: root/ms/controllerblueprints/modules/service/src/main/kotlin/org/onap/ccsdk/cds/controllerblueprints/service/handler/BluePrintModelHandler.kt
blob: c54bf87feef2b6b798acd9a7bcc28f22efbb910a (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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
 * Copyright © 2017-2018 AT&T Intellectual Property.
 * Modifications Copyright © 2019 Bell Canada.
 * Modifications Copyright © 2019 IBM.
 *
 * 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.controllerblueprints.service.handler

import org.onap.ccsdk.cds.controllerblueprints.core.*
import org.onap.ccsdk.cds.controllerblueprints.core.config.BluePrintLoadConfiguration
import org.onap.ccsdk.cds.controllerblueprints.core.data.ErrorCode
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintCatalogService
import org.onap.ccsdk.cds.controllerblueprints.core.interfaces.BluePrintEnhancerService
import org.onap.ccsdk.cds.controllerblueprints.service.domain.BlueprintModel
import org.onap.ccsdk.cds.controllerblueprints.service.domain.BlueprintModelSearch
import org.onap.ccsdk.cds.controllerblueprints.service.repository.ControllerBlueprintModelContentRepository
import org.onap.ccsdk.cds.controllerblueprints.service.repository.ControllerBlueprintModelRepository
import org.onap.ccsdk.cds.controllerblueprints.service.repository.ControllerBlueprintModelSearchRepository
import org.onap.ccsdk.cds.controllerblueprints.service.utils.BluePrintEnhancerUtils
import org.slf4j.LoggerFactory
import org.springframework.core.io.ByteArrayResource
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.http.codec.multipart.FilePart
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.File
import java.io.IOException
import java.util.*

/**
 * BlueprintModelHandler Purpose: Handler service to handle the request from BlurPrintModelRest
 *
 * @author Brinda Santh
 * @version 1.0
 */

@Service
open class BluePrintModelHandler(private val bluePrintCatalogService: BluePrintCatalogService,
                                 private val bluePrintLoadConfiguration: BluePrintLoadConfiguration,
                                 private val blueprintModelSearchRepository: ControllerBlueprintModelSearchRepository,
                                 private val blueprintModelRepository: ControllerBlueprintModelRepository,
                                 private val blueprintModelContentRepository: ControllerBlueprintModelContentRepository,
                                 private val bluePrintEnhancerService: BluePrintEnhancerService) {

    private val log = LoggerFactory.getLogger(BluePrintModelHandler::class.java)!!

    /**
     * This is a getAllBlueprintModel method to retrieve all the BlueprintModel in Database
     *
     * @return List<BlueprintModelSearch> list of the controller blueprint archives
    </BlueprintModelSearch> */
    open fun allBlueprintModel(): List<BlueprintModelSearch> {
        return blueprintModelSearchRepository.findAll()
    }

    /**
     * This is a saveBlueprintModel method
     *
     * @param filePart filePart
     * @return Mono<BlueprintModelSearch>
     * @throws BluePrintException BluePrintException
    </BlueprintModelSearch> */
    @Throws(BluePrintException::class)
    open suspend fun saveBlueprintModel(filePart: FilePart): BlueprintModelSearch {
        val saveId = UUID.randomUUID().toString()
        val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, saveId)
        try {
            //Recreate the Dir
            normalizedFile(bluePrintLoadConfiguration.blueprintArchivePath, saveId).reCreateDirs()
            val deCompressedFile = normalizedFile(blueprintArchive, "cba.zip")
            // Copy the File Part to Local File
            BluePrintEnhancerUtils.copyFromFilePart(filePart, deCompressedFile)
            // Save the Copied file to Database
            val blueprintId = bluePrintCatalogService.saveToDatabase(saveId, deCompressedFile, false)
            // Check and Return the Saved File
            val blueprintModelSearch = blueprintModelSearchRepository.findById(blueprintId).get()
            log.info("Save($saveId) successful for blueprint(${blueprintModelSearch.artifactName}) " +
                    "version(${blueprintModelSearch.artifactVersion})")
            return blueprintModelSearch
        } catch (e: IOException) {
            throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
                    "Error in Save CBA: ${e.message}", e)
        } finally {
            deleteDir(blueprintArchive)
        }
    }


    /**
     * This is a searchBlueprintModels method
     *
     * @param tags tags
     * @return List<BlueprintModelSearch>
    </BlueprintModelSearch> */
    open fun searchBlueprintModels(tags: String): List<BlueprintModelSearch> {
        return blueprintModelSearchRepository.findByTagsContainingIgnoreCase(tags)
    }

    /**
     * This is a getBlueprintModelSearchByNameAndVersion method
     *
     * @param name name
     * @param version version
     * @return BlueprintModelSearch
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open fun getBlueprintModelSearchByNameAndVersion(name: String, version: String): BlueprintModelSearch {
        val blueprintModelSearch: BlueprintModelSearch
        val dbBlueprintModel = blueprintModelSearchRepository
                .findByArtifactNameAndArtifactVersion(name, version)
        if (dbBlueprintModel.isPresent) {
            blueprintModelSearch = dbBlueprintModel.get()
        } else {
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value,
                    String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version))
        }
        return blueprintModelSearch
    }

    /**
     * This is a downloadBlueprintModelFileByNameAndVersion method to download a Blueprint by Name and Version
     *
     * @param name name
     * @param version version
     * @return ResponseEntity<Resource>
     * @throws BluePrintException BluePrintException
    </Resource> */
    @Throws(BluePrintException::class)
    open fun downloadBlueprintModelFileByNameAndVersion(name: String,
                                                        version: String): ResponseEntity<Resource> {
        val blueprintModel: BlueprintModel
        try {
            blueprintModel = getBlueprintModelByNameAndVersion(name, version)
        } catch (e: BluePrintException) {
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e)
        }

        val fileName = blueprintModel.id + ".zip"
        val file = blueprintModel.blueprintModelContent.content
        return prepareResourceEntity(fileName, file)
    }

    /**
     * This is a downloadBlueprintModelFile method to find the target file to download and return a file resource
     *
     * @return ResponseEntity<Resource>
     * @throws BluePrintException BluePrintException
    </Resource> */
    @Throws(BluePrintException::class)
    open fun downloadBlueprintModelFile(id: String): ResponseEntity<Resource> {
        val blueprintModel: BlueprintModel
        try {
            blueprintModel = getBlueprintModel(id)
        } catch (e: BluePrintException) {
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, String.format("Error while " + "downloading the CBA file: %s", e.message), e)
        }

        val fileName = blueprintModel.id + ".zip"
        val file = blueprintModel.blueprintModelContent.content
        return prepareResourceEntity(fileName, file)
    }

    /**
     * @return ResponseEntity<Resource>
    </Resource> */
    private fun prepareResourceEntity(fileName: String, file: ByteArray): ResponseEntity<Resource> {
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("text/plain"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"$fileName\"")
                .body(ByteArrayResource(file))
    }

    /**
     * This is a getBlueprintModel method
     *
     * @param id id
     * @return BlueprintModel
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open fun getBlueprintModel(id: String): BlueprintModel {
        val blueprintModel: BlueprintModel
        val dbBlueprintModel = blueprintModelRepository.findById(id)
        if (dbBlueprintModel.isPresent) {
            blueprintModel = dbBlueprintModel.get()
        } else {
            val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id)
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg)
        }
        return blueprintModel
    }

    /**
     * This is a getBlueprintModelByNameAndVersion method
     *
     * @param name name
     * @param version version
     * @return BlueprintModel
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open fun getBlueprintModelByNameAndVersion(name: String, version: String): BlueprintModel {
        val blueprintModel = blueprintModelRepository
                .findByArtifactNameAndArtifactVersion(name, version)
        if (blueprintModel != null) {
            return blueprintModel
        } else {
            val msg = String.format(BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG, name, version)
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg)
        }
    }

    /**
     * This is a getBlueprintModelSearch method
     *
     * @param id id
     * @return BlueprintModelSearch
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open fun getBlueprintModelSearch(id: String): BlueprintModelSearch {
        val blueprintModelSearch: BlueprintModelSearch
        val dbBlueprintModel = blueprintModelSearchRepository.findById(id)
        if (dbBlueprintModel.isPresent) {
            blueprintModelSearch = dbBlueprintModel.get()
        } else {
            val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id)
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg)
        }

        return blueprintModelSearch
    }

    /**
     * This is a deleteBlueprintModel method
     *
     * @param id id
     * @throws BluePrintException BluePrintException
     */
    @Transactional
    @Throws(BluePrintException::class)
    open fun deleteBlueprintModel(id: String) {
        val dbBlueprintModel = blueprintModelRepository.findById(id)
        if (dbBlueprintModel.isPresent) {
            blueprintModelContentRepository.deleteByBlueprintModel(dbBlueprintModel.get())
            blueprintModelRepository.delete(dbBlueprintModel.get())
        } else {
            val msg = String.format(BLUEPRINT_MODEL_ID_FAILURE_MSG, id)
            throw BluePrintException(ErrorCode.RESOURCE_NOT_FOUND.value, msg)
        }
    }

    /**
     * This is a CBA enrichBlueprint method
     * Save the Zip File in archive location and extract the cba content.
     * Populate the Enhancement Location
     * Enhance the CBA content
     * Compress the Enhanced Content
     * Return back the the compressed content back to the caller.
     *
     * @param filePart filePart
     * @return ResponseEntity<Resource>
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open suspend fun enrichBlueprint(filePart: FilePart): ResponseEntity<Resource> {
        val enhanceId = UUID.randomUUID().toString()
        val blueprintArchive = normalizedPathName(bluePrintLoadConfiguration.blueprintArchivePath, enhanceId)
        val blueprintWorkingDir = normalizedPathName(bluePrintLoadConfiguration.blueprintWorkingPath, enhanceId)
        try {
            BluePrintEnhancerUtils.decompressFilePart(filePart, blueprintArchive, blueprintWorkingDir)

            // Enhance the Blue Prints
            bluePrintEnhancerService.enhance(blueprintWorkingDir)

            return BluePrintEnhancerUtils.compressToFilePart(blueprintWorkingDir, blueprintArchive)

        } catch (e: IOException) {
            throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
                    "Error in Enriching CBA: ${e.message}", e)
        } finally {
            BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir)
        }
    }

    /**
     * This is a publishBlueprintModel method to change the status published to YES
     *
     * @param filePart filePart
     * @return BlueprintModelSearch
     * @throws BluePrintException BluePrintException
     */
    @Throws(BluePrintException::class)
    open suspend fun publishBlueprint(filePart: FilePart): BlueprintModelSearch {
        val publishId = UUID.randomUUID().toString()
        val blueprintArchive = bluePrintLoadConfiguration.blueprintArchivePath.plus(File.separator).plus(publishId)
        val blueprintWorkingDir = bluePrintLoadConfiguration.blueprintWorkingPath.plus(File.separator).plus(publishId)
        try {
            val compressedFilePart = BluePrintEnhancerUtils
                    .extractCompressFilePart(filePart, blueprintArchive, blueprintWorkingDir)

            val blueprintId = bluePrintCatalogService.saveToDatabase(publishId, compressedFilePart, true)

            return blueprintModelSearchRepository.findById(blueprintId).get()

        } catch (e: Exception) {
            throw BluePrintException(ErrorCode.IO_FILE_INTERRUPT.value,
                    "Error in Publishing CBA: ${e.message}", e)
        } finally {
            BluePrintEnhancerUtils.cleanEnhancer(blueprintArchive, blueprintWorkingDir)
        }
    }

    companion object {

        private const val BLUEPRINT_MODEL_ID_FAILURE_MSG = "failed to get blueprint model id(%s) from repo"
        private const val BLUEPRINT_MODEL_NAME_VERSION_FAILURE_MSG = "failed to get blueprint model by name(%s)" + " and version(%s) from repo"
    }
}