5ee7c30bcfcc4ed9d23a15a4a18c5dbcbef17b76
[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         dirName = File.separator + dirName;
80         LOG.info("tmpdir = {}" , dirName);
81         if(!tmpDir.exists()) {
82             tmpDir.mkdirs();
83         }
84         File file = new File(tmpDir + File.separator + fileName);
85
86         try (OutputStream os = new FileOutputStream(file, true);) {
87             int read = 0;
88             byte[] bytes = new byte[1024];
89             while((read = uploadedInputStream.read(bytes)) != -1) {
90                 os.write(bytes, 0, read);
91             }
92             os.flush();
93             return file.getAbsolutePath();
94         }
95     }
96
97     /**
98      * get temp dirctory when upload package.
99      *
100      * @param dirName temp directory name
101      * @param fileName package name
102      * @return String
103      */
104     public static String getTempDir(String dirName, String fileName) {
105         return Thread.currentThread().getContextClassLoader().getResource("/").getPath() + dirName + File.separator
106                 + fileName.replace(CSAR_EXTENSION, "");
107     }
108
109     public static String getUnzipDir(String dirName) {
110         File tmpDir = new File(File.separator + dirName);
111         return tmpDir.getAbsolutePath().replace(CSAR_EXTENSION, "");
112     }
113
114     /**
115      * delete file.
116      *
117      * @param dirName the directory of file
118      * @param fileName file name
119      * @return boolean
120      */
121     public static boolean deleteFile(String dirName, String fileName) {
122         File tmpDir = new File(File.separator + dirName);
123         if(!tmpDir.exists()) {
124             return true;
125         }
126         File file = new File(tmpDir.getAbsolutePath() + File.separator + fileName);
127         if(file.exists()) {
128             boolean isFileDeleted=false;
129             String fileAbsPath = file.getAbsolutePath();
130             try {
131                 Files.delete(Paths.get(file.getPath()));
132                 isFileDeleted=true;
133             } catch (IOException e) {
134                 LOG.error("fail to delete {} {} ", fileAbsPath, e);
135             }
136             return isFileDeleted;
137         }
138         return true;
139     }
140
141     public static String getCatalogueCsarPath() {
142         return File.separator + CATALOGUE_CSAR_DIR_NAME;
143     }
144
145     public static String getCatalogueImagePath() {
146         return File.separator + CATALOGUE_IMAGE_DIR_NAME;
147     }
148
149     /**
150      * get file size.
151      *
152      * @param file file which to get the size
153      * @param fileUnit file unit
154      * @return String file size
155      */
156     public static String getFileSize(File file, int fileUnit) {
157         String fileSize = "";
158         DecimalFormat format = new DecimalFormat("#0.00");
159         if(file.exists()) {
160             fileSize = format.format((double)file.length() / fileUnit) + "M";
161         }
162         return fileSize;
163     }
164
165     public static String formatFileSize(double fileLength, int fileUnit) {
166         DecimalFormat format = new DecimalFormat("#0.00");
167         return format.format(fileLength / fileUnit) + "M";
168     }
169
170     /**
171      * fix package format.
172      *
173      * @param csarId package ID
174      * @return String
175      */
176     public static String formatCsar(String csarId) {
177         String result = csarId;
178         if(csarId.indexOf(CSAR_EXTENSION) < 0) {
179             result += CSAR_EXTENSION;
180         }
181         return result;
182     }
183
184     /**
185      * judge the file's format is yaml or not.
186      *
187      * @param file file to judge
188      * @return boolean
189      */
190     public static boolean isYamlFile(File file) {
191         return !file.isDirectory() && file.getName().indexOf(".yaml") != -1;
192     }
193
194     /**
195      * remove the csar suffix.
196      *
197      * @param csarName package name
198      * @return String
199      */
200     public static String removeCsarSuffix(String csarName) {
201         return csarName.replaceAll(CSAR_EXTENSION, "");
202     }
203
204     /**
205      * add the csar fuffix.
206      *
207      * @param csarName package name
208      * @return String
209      */
210     public static String addCsarSuffix(String csarName) {
211         if(csarName.indexOf(CSAR_EXTENSION) == -1) {
212             return csarName + CSAR_EXTENSION;
213         }
214         return csarName;
215     }
216
217     /**
218      * process file name.
219      *
220      * @param fileName file's name
221      * @return String
222      */
223     public static String processFileName(String fileName) {
224         int index = fileName.indexOf(".zip");
225         if(index == -1) {
226             return fileName;
227         }
228
229         return addCsarSuffix(fileName.replaceAll(".zip", ""));
230     }
231
232     /**
233      * exchange object to string.
234      *
235      * @param obj object
236      * @return String
237      */
238     public static String objectToString(Object obj) {
239         if(obj == null) {
240             return "";
241         }
242         Gson gson = new Gson();
243
244         return gson.toJson(obj);
245     }
246
247     public static String generateId() {
248         return UUID.randomUUID().toString();
249     }
250
251     /**
252      * get the size format according file size.
253      *
254      * @param fileSize file size
255      * @return size format
256      */
257     public static String getFormatFileSize(long fileSize) {
258         long kb = 1024;
259         long mb = kb * 1024;
260         long gb = mb * 1024;
261
262         if(fileSize >= gb) {
263             return String.format("%.1f GB", (float)fileSize / gb);
264         } else if(fileSize >= mb) {
265             float fi = (float)fileSize / mb;
266             return String.format(fi > 100 ? "%.0f MB" : "%.1f MB", fi);
267         } else if(fileSize >= kb) {
268             float fi = (float)fileSize / kb;
269             return String.format(fi > 100 ? "%.0f KB" : "%.1f KB", fi);
270         } else {
271             return String.format("%d B", fileSize);
272         }
273     }
274
275     /**
276      * get gson from json.
277      * 
278      * @param jsonString json string
279      * @param templateClass template class
280      * @return Template
281      */
282     public static <T> T fromJson(String jsonString, Class<T> templateClass) {
283         Gson gson = new Gson();
284         return gson.fromJson(jsonString, templateClass);
285     }
286
287 }