Migrate "ms/controllerblueprints" from ccsdk/apps
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / apps / controllerblueprints / core / FileExtensionFunctions.kt
1 /*
2  *  Copyright © 2019 IBM.
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.apps.controllerblueprints.core
18
19 import org.apache.commons.io.FileUtils
20 import org.onap.ccsdk.apps.controllerblueprints.core.utils.BluePrintArchiveUtils
21 import java.io.File
22 import java.io.InputStream
23 import java.nio.file.Path
24 import java.nio.file.Paths
25
26 fun InputStream.toFile(path: String): File {
27     val file = File(path)
28     file.outputStream().use { this.copyTo(it) }
29     return file
30 }
31
32 fun File.reCreateDirs(): File {
33     if (this.exists()) {
34         this.deleteRecursively()
35     }
36     // this.mkdirs()
37     FileUtils.forceMkdir(this)
38     check(this.exists()) {
39         throw BluePrintException("failed to re create dir(${this.absolutePath})")
40     }
41     return this
42 }
43
44 fun File.compress(targetZipFileName: String): File {
45     return this.compress(Paths.get(targetZipFileName).toFile())
46 }
47
48 /**
49  * Compress the current Dir to the target zip file and return the target zip file
50  */
51 fun File.compress(targetZipFile: File): File {
52     BluePrintArchiveUtils.compress(this, targetZipFile, true)
53     return targetZipFile
54 }
55
56 fun File.deCompress(targetFileName: String): File {
57     return this.deCompress(Paths.get(targetFileName).toFile())
58 }
59
60 /**
61  * De-Compress the current zip file to the target file and return the target file
62  */
63 fun File.deCompress(targetFile: File): File {
64     BluePrintArchiveUtils.deCompress(this, targetFile.path)
65     return targetFile
66 }
67
68 fun deleteDir(path: String, vararg more: String?) {
69     normalizedFile(path, *more).deleteRecursively()
70 }
71
72 fun normalizedFile(path: String, vararg more: String?): File {
73     return Paths.get(path, *more).toFile().normalize()
74 }
75
76 fun normalizedPath(path: String, vararg more: String?): Path {
77     return Paths.get(path, *more).normalize().toAbsolutePath()
78 }
79
80 fun normalizedPathName(path: String, vararg more: String?): String {
81     return normalizedPath(path, *more).toString()
82 }
83