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