Add source-rest mapping
[ccsdk/cds.git] / ms / blueprintsprocessor / modules / inbounds / selfservice-api / src / main / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / selfservice / api / utils / Utils.kt
1 /*
2  * Copyright (C) 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 package org.onap.ccsdk.cds.blueprintsprocessor.selfservice.api.utils
17
18 import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintException
19 import org.springframework.http.HttpStatus
20 import org.springframework.http.codec.multipart.FilePart
21 import org.springframework.util.StringUtils
22 import java.io.File
23 import java.io.IOException
24 import java.nio.file.Path
25 import java.time.LocalDateTime
26 import java.time.ZoneId
27 import java.time.format.DateTimeFormatter
28 import java.util.*
29
30 const val INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE = 500
31
32 fun currentTimestamp(): String {
33     val now = LocalDateTime.now(ZoneId.systemDefault())
34     val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
35     return formatter.format(now)
36 }
37
38
39 @Throws(BluePrintException::class, IOException::class)
40 fun saveCBAFile(filePart: FilePart, targetDirectory: Path): Path {
41
42     val fileName = StringUtils.cleanPath(filePart.filename())
43
44     if (StringUtils.getFilenameExtension(fileName) != "zip") {
45         throw BluePrintException("Invalid file extension required ZIP")
46     }
47
48     val changedFileName = UUID.randomUUID().toString() + ".zip"
49
50     val targetLocation = targetDirectory.resolve(changedFileName)
51
52     val file = File(targetLocation.toString())
53     if (file.exists()) {
54         file.delete()
55     }
56     file.createNewFile()
57
58     filePart.transferTo(file)
59
60     return targetLocation
61 }
62
63 fun determineHttpStatusCode(statusCode: Int): HttpStatus {
64
65     try {
66         return HttpStatus.valueOf(statusCode)
67     } catch (exception: Exception) {
68         //if statusCode cannot be converted to a proper HttpStatus, the resource still needs to assign a HTTP status
69         // code to the response. In this case, a 500 Internal Server Error will be returned as default.
70         return HttpStatus.valueOf(INTERNAL_SERVER_ERROR_HTTP_STATUS_CODE)
71     }
72 }