2 * Copyright © 2019 IBM.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.ccsdk.cds.controllerblueprints.core
19 import kotlinx.coroutines.Dispatchers
20 import kotlinx.coroutines.withContext
21 import org.apache.commons.io.FileUtils
22 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils
24 import java.io.InputStream
25 import java.nio.charset.Charset
26 import java.nio.file.Path
27 import java.nio.file.Paths
29 fun InputStream.toFile(path: String): File {
31 file.outputStream().use { this.copyTo(it) }
35 fun File.reCreateDirs(): File {
37 this.deleteRecursively()
40 FileUtils.forceMkdir(this)
41 check(this.exists()) {
42 throw BluePrintException("failed to re create dir(${this.absolutePath})")
47 fun File.compress(targetZipFileName: String): File {
48 return this.compress(Paths.get(targetZipFileName).toFile())
52 * Compress the current Dir to the target zip file and return the target zip file
54 fun File.compress(targetZipFile: File): File {
55 BluePrintArchiveUtils.compress(this, targetZipFile, true)
59 fun File.deCompress(targetFileName: String): File {
60 return this.deCompress(Paths.get(targetFileName).toFile())
64 * De-Compress the current zip file to the target file and return the target file
66 fun File.deCompress(targetFile: File): File {
67 BluePrintArchiveUtils.deCompress(this, targetFile.path)
71 fun deleteDir(path: String, vararg more: String?) {
72 normalizedFile(path, *more).deleteRecursively()
75 fun checkFileExists(file: File, lazyMessage: () -> Any) {
77 val message = lazyMessage()
78 throw IllegalStateException(message.toString())
82 fun normalizedFile(path: String, vararg more: String?): File {
83 return Paths.get(path, *more).toFile().normalize()
86 fun normalizedPath(path: String, vararg more: String?): Path {
87 return Paths.get(path, *more).toAbsolutePath().normalize()
90 fun normalizedPathName(path: String, vararg more: String?): String {
91 return normalizedPath(path, *more).toString()
94 suspend fun File.reCreateNBDirs(): File = withContext(Dispatchers.IO) {
98 suspend fun deleteNBDir(path: String, vararg more: String?): Boolean = withContext(Dispatchers.IO) {
99 normalizedFile(path, *more).deleteRecursively()
102 suspend fun File.readNBText(): String = withContext(Dispatchers.IO) {
103 readText(Charset.defaultCharset())
106 suspend fun File.readNBLines(): List<String> = withContext(Dispatchers.IO) {
107 readLines(Charset.defaultCharset())