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