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