"java.nio.Files#delete" should be preferred
[vnfsdk/refrepo.git] / vnfmarket-be / vnf-sdk-marketplace / src / main / java / org / onap / vnfsdk / marketplace / common / ToolUtil.java
1 /**
2  * Copyright 2017 Huawei Technologies Co., Ltd.
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.vnfsdk.marketplace.common;
18
19 import java.io.File;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.text.DecimalFormat;
25 import java.util.Collection;
26 import java.util.UUID;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import com.google.gson.Gson;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32
33 /**
34  * common utility class.
35  */
36 public class ToolUtil {
37
38     private static final Logger LOG = LoggerFactory.getLogger(ToolUtil.class);
39
40     public static final String CATALOGUE_CSAR_DIR_NAME = "csar";
41
42     public static final String CATALOGUE_IMAGE_DIR_NAME = "image";
43
44     public static final String CSAR_EXTENSION = ".csar";
45
46     public static final int FILE_PERCENT = 1024 * 1024; // 1M
47
48     private ToolUtil() {
49     }
50
51     public static boolean isEmptyString(String val) {
52         return val == null || "".equals(val);
53     }
54
55     public static boolean isTrimedEmptyString(String val) {
56         return val == null || "".equals(val.trim());
57     }
58
59     public static boolean isTrimedEmptyArray(String[] val) {
60         return val == null || val.length == 0;
61     }
62
63     public static boolean isEmptyCollection(Collection<?> coll) {
64         return null == coll || coll.isEmpty();
65     }
66
67     /**
68      * store chunk file to local temp directory.
69      *
70      * @param dirName directory name
71      * @param fileName file name
72      * @param uploadedInputStream upload input stream
73      * @return String
74      * @throws IOException e
75      */
76     public static String storeChunkFileInLocal(String dirName, String fileName, InputStream uploadedInputStream)
77             throws IOException {
78         File tmpDir = new File(dirName);
79         LOG.info("tmpdir = " + File.separator + dirName);
80         if(!tmpDir.exists()) {
81             tmpDir.mkdirs();
82         }
83         File file = new File(tmpDir + File.separator + fileName);
84
85         try (OutputStream os = new FileOutputStream(file, true);) {
86             int read = 0;
87             byte[] bytes = new byte[1024];
88             while((read = uploadedInputStream.read(bytes)) != -1) {
89                 os.write(bytes, 0, read);
90             }
91             os.flush();
92             return file.getAbsolutePath();
93         }
94     }
95
96     /**
97      * get temp dirctory when upload package.
98      *
99      * @param dirName temp directory name
100      * @param fileName package name
101      * @return String
102      */
103     public static String getTempDir(String dirName, String fileName) {
104         return Thread.currentThread().getContextClassLoader().getResource("/").getPath() + dirName + File.separator
105                 + fileName.replace(CSAR_EXTENSION, "");
106     }
107
108     public static String getUnzipDir(String dirName) {
109         File tmpDir = new File(File.separator + dirName);
110         return tmpDir.getAbsolutePath().replace(CSAR_EXTENSION, "");
111     }
112
113     /**
114      * delete file.
115      *
116      * @param dirName the directory of file
117      * @param fileName file name
118      * @return boolean
119      */
120     public static boolean deleteFile(String dirName, String fileName) {
121         File tmpDir = new File(File.separator + dirName);
122         if(!tmpDir.exists()) {
123             return true;
124         }
125         File file = new File(tmpDir.getAbsolutePath() + File.separator + fileName);
126         if(file.exists()) {
127             boolean isFileDeleted=false;
128             String fileAbsPath = file.getAbsolutePath();
129             try {
130                 Files.delete(Paths.get(file.getPath()));
131                 isFileDeleted=true;
132             } catch (IOException e) {
133                 LOG.error("fail to delete {} {} ", fileAbsPath, e);
134             }
135             return isFileDeleted;
136         }
137         return true;
138     }
139
140     public static String getCatalogueCsarPath() {
141         return File.separator + CATALOGUE_CSAR_DIR_NAME;
142     }
143
144     public static String getCatalogueImagePath() {
145         return File.separator + CATALOGUE_IMAGE_DIR_NAME;
146     }
147
148     /**
149      * get file size.
150      *
151      * @param file file which to get the size
152      * @param fileUnit file unit
153      * @return String file size
154      */
155     public static String getFileSize(File file, int fileUnit) {
156         String fileSize = "";
157         DecimalFormat format = new DecimalFormat("#0.00");
158         if(file.exists()) {
159             fileSize = format.format((double)file.length() / fileUnit) + "M";
160         }
161         return fileSize;
162     }
163
164     public static String formatFileSize(double fileLength, int fileUnit) {
165         DecimalFormat format = new DecimalFormat("#0.00");
166         return format.format(fileLength / fileUnit) + "M";
167     }
168
169     /**
170      * fix package format.
171      *
172      * @param csarId package ID
173      * @return String
174      */
175     public static String formatCsar(String csarId) {
176         String result = csarId;
177         if(csarId.indexOf(CSAR_EXTENSION) < 0) {
178             result += CSAR_EXTENSION;
179         }
180         return result;
181     }
182
183     /**
184      * judge the file's format is yaml or not.
185      *
186      * @param file file to judge
187      * @return boolean
188      */
189     public static boolean isYamlFile(File file) {
190         return !file.isDirectory() && file.getName().indexOf(".yaml") != -1;
191     }
192
193     /**
194      * remove the csar suffix.
195      *
196      * @param csarName package name
197      * @return String
198      */
199     public static String removeCsarSuffix(String csarName) {
200         return csarName.replaceAll(CSAR_EXTENSION, "");
201     }
202
203     /**
204      * add the csar fuffix.
205      *
206      * @param csarName package name
207      * @return String
208      */
209     public static String addCsarSuffix(String csarName) {
210         if(csarName.indexOf(CSAR_EXTENSION) == -1) {
211             return csarName + CSAR_EXTENSION;
212         }
213         return csarName;
214     }
215
216     /**
217      * process file name.
218      *
219      * @param fileName file's name
220      * @return String
221      */
222     public static String processFileName(String fileName) {
223         int index = fileName.indexOf(".zip");
224         if(index == -1) {
225             return fileName;
226         }
227
228         return addCsarSuffix(fileName.replaceAll(".zip", ""));
229     }
230
231     /**
232      * exchange object to string.
233      *
234      * @param obj object
235      * @return String
236      */
237     public static String objectToString(Object obj) {
238         if(obj == null) {
239             return "";
240         }
241         Gson gson = new Gson();
242
243         return gson.toJson(obj);
244     }
245
246     public static String generateId() {
247         return UUID.randomUUID().toString();
248     }
249
250     /**
251      * get the size format according file size.
252      *
253      * @param fileSize file size
254      * @return size format
255      */
256     public static String getFormatFileSize(long fileSize) {
257         long kb = 1024;
258         long mb = kb * 1024;
259         long gb = mb * 1024;
260
261         if(fileSize >= gb) {
262             return String.format("%.1f GB", (float)fileSize / gb);
263         } else if(fileSize >= mb) {
264             float fi = (float)fileSize / mb;
265             return String.format(fi > 100 ? "%.0f MB" : "%.1f MB", fi);
266         } else if(fileSize >= kb) {
267             float fi = (float)fileSize / kb;
268             return String.format(fi > 100 ? "%.0f KB" : "%.1f KB", fi);
269         } else {
270             return String.format("%d B", fileSize);
271         }
272     }
273
274     /**
275      * get gson from json.
276      * 
277      * @param jsonString json string
278      * @param templateClass template class
279      * @return Template
280      */
281     public static <T> T fromJson(String jsonString, Class<T> templateClass) {
282         Gson gson = new Gson();
283         return gson.fromJson(jsonString, templateClass);
284     }
285
286 }