TEST SONAR VERIFY JOBS
[vnfsdk/refrepo.git] / vnfmarket-be / vnf-sdk-marketplace / src / main / java / org / onap / vnfsdk / marketplace / common / FileUtil.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 package org.onap.vnfsdk.marketplace.common;
17
18 import java.io.BufferedOutputStream;
19 import java.io.File;
20 import java.io.FileFilter;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.FileReader;
24 import java.io.FileWriter;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.ArrayList;
28 import java.util.Enumeration;
29 import java.util.List;
30 import java.util.zip.ZipEntry;
31 import java.util.zip.ZipFile;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import com.google.gson.Gson;
35 import com.google.gson.stream.JsonReader;
36
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
39
40 public final class FileUtil {
41
42     public static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
43
44     private static final int BUFFER_SIZE = 2 * 1024 * 1024;
45
46     private static final int MAX_PACKAGE_SIZE = 50 * 1024 * 1024;
47     private static Gson gson = new Gson();
48
49     private FileUtil() {
50         //Empty constructor
51     }
52
53     /**
54      * create dir.
55      *
56      * @param dir
57      *            dir to create
58      * @return boolean
59      */
60     public static boolean createDirectory(String dir) {
61         File folder = new File(dir);
62         return (folder.exists() || folder.mkdirs());
63     }
64
65     /**
66      * delete file.
67      *
68      * @param file
69      *            the file to delete
70      * @return boolean
71      */
72     public static boolean deleteFile(File file) {
73         String hintInfo = file.isDirectory() ? "dir " : "file ";
74         String fileAbsPath = "";
75         boolean isFileDeleted=false;
76         try {
77             if (file.exists()){
78                 Files.delete(Paths.get(file.getPath()));
79                 fileAbsPath = file.getAbsolutePath();
80                 logger.info("delete {} {}" ,hintInfo, fileAbsPath);
81             }
82             else{
83                 logger.info("file not exist. no need delete {} {}" ,hintInfo , fileAbsPath);
84             }
85             isFileDeleted=true;
86
87         } catch (IOException e) {
88             logger.error("fail to delete {} {} ", hintInfo, fileAbsPath, e);
89         }
90         return isFileDeleted;
91     }
92
93     /**
94      * unzip zip file.
95      *
96      * @param zipFileName
97      *            file name to zip
98      * @param extPlace
99      *            extPlace
100      * @return unzip file name
101      * @throws IOException
102      *             e1
103      */
104     public static List<String> unzip(String zipFileName, String extPlace) throws IOException {
105         List<String> unzipFileNams = new ArrayList<>();
106
107         try (ZipFile zipFile = new ZipFile(zipFileName);) {
108             Enumeration<?> fileEn = zipFile.entries();
109             byte[] buffer = new byte[BUFFER_SIZE];
110
111             while (fileEn.hasMoreElements()) {
112                 ZipEntry entry = (ZipEntry) fileEn.nextElement();
113                 if (entry.isDirectory()) {
114                     continue;
115                 }
116
117                 File file = new File(extPlace, entry.getName());
118                 if (!file.getParentFile().exists()) {
119                     createDirectory(file.getParentFile().getAbsolutePath());
120                 }
121
122                 try (InputStream input = zipFile.getInputStream(entry);
123                      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));) {
124                     int length = 0;
125                     while ((length = input.read(buffer)) != -1) {
126                         bos.write(buffer, 0, length);
127                     }
128                     unzipFileNams.add(file.getAbsolutePath());
129                 }
130             }
131         }
132         return unzipFileNams;
133     }
134
135     public static boolean checkFileExists(String filePath) {
136         File file = new File(filePath);
137         return file.exists();
138     }
139
140     public static boolean deleteFile(String filePath) {
141         File file = new File(filePath);
142         return deleteFile(file);
143     }
144
145     public static boolean writeJsonDatatoFile(String fileAbsPath, Object obj) {
146         logger.info("Write JsonData to file : {} " , fileAbsPath);
147
148         boolean bResult = false;
149         if (checkFileExists(fileAbsPath)) {
150             deleteFile(fileAbsPath);
151         }
152
153         try(FileWriter writer = new FileWriter(new File(fileAbsPath))) {
154             gson.toJson(obj, writer);
155             bResult = true;
156         } catch (Exception e) { //NOSONAR
157             logger.info("Exception: writeJsonDatatoFile-->{} {}" , fileAbsPath, e);
158         }
159         return bResult;
160     }
161
162     public static <T> Object readJsonDatafFromFile(String fileAbsPath, Class<T> clazz) {
163         if (!checkFileExists(fileAbsPath)) {
164             logger.info("read JsonData from file , file not found : {}" ,fileAbsPath);
165             return null;
166         }
167
168         logger.info("read JsonData from file : {}" , fileAbsPath);
169
170         T obj = null;
171         /*
172            Gson will ignore the unknown fields and simply match the fields that it's able to.
173            ref: https://www.baeldung.com/gson-deserialization-guide
174
175            By default, Gson just ignores extra JSON elements that do not have matching Java fields.
176            ref: https://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html
177         */
178         try(JsonReader jsonReader = new JsonReader(new FileReader(fileAbsPath))) {
179             obj = gson.fromJson(jsonReader, clazz);
180         } catch (Exception e1) { //NOSONAR
181             logger.info("IOException Exception: writeJsonDatatoFile-->{} {}" , fileAbsPath, e1);
182         }
183         return obj;
184     }
185
186     public static boolean deleteDirectory(String path) {
187         File file = new File(path);
188         return deleteDirectory(file);
189     }
190
191     public static boolean deleteDirectory(File file) {
192         if (!file.exists()) {
193             return true;
194         }
195         if (file.isDirectory()) {
196             for (File f : file.listFiles()) {
197                 deleteDirectory(f);
198             }
199         }
200         boolean isFileDeleted=false;
201         String fileAbsPath = file.getAbsolutePath();
202         try {
203             Files.delete(Paths.get(file.getPath()));
204             isFileDeleted=true;
205         } catch (IOException e) {
206             logger.error("fail to delete {} {} ", fileAbsPath, e);
207         }
208         return isFileDeleted;
209     }
210
211     public static boolean validateStream(FileInputStream ifs) {
212
213         if (null == ifs) {
214             logger.error("File stream is null");
215             return false;
216         }
217
218         try {
219             if (!ifs.getFD().valid()) {
220                 logger.error("File descriptor is not valid");
221                 return false;
222             }
223         } catch (IOException e) {
224             logger.error("Exception while getting File descriptor", e);
225         }
226
227         return true;
228     }
229
230     public static boolean validatePath(String path) {
231         if (!new File(path).isDirectory()) {
232             logger.error("File is not a directory");
233             return false;
234         }
235         return true;
236     }
237
238     public static boolean validateFile(File fileData) {
239         if (null == fileData) {
240             logger.error("File data is null");
241             return false;
242         }
243
244         if (MAX_PACKAGE_SIZE < fileData.length()) {
245             logger.error("File size is greater than 50 MB {}", fileData.length());
246             return false;
247         }
248
249         return true;
250     }
251
252     /**
253      * Search file in folder
254      * @param folder
255      * @param keyword
256      * @return
257      */
258     public static List<File> searchFiles(File folder,  String keyword) {
259         List<File> result = new ArrayList<File>();
260         if (folder.isFile())
261             result.add(folder);
262
263         File[] subFolders = folder.listFiles(new FileFilter() {
264             @Override
265             public boolean accept(File file) {
266                 if (file.isDirectory()) {
267                     return true;
268                 }
269                 if (file.getName().toLowerCase().contains(keyword)) {
270                     return true;
271                 }
272                 return false;
273             }
274         });
275
276         if (subFolders != null) {
277             for (File file : subFolders) {
278                 if (file.isFile()) {
279                     result.add(file);
280                 } else {
281                     result.addAll(searchFiles(file, keyword));
282                 }
283             }
284         }
285         return result;
286     }
287 }