Code Improvements-Vnfsdk-refrepo sonar issue fixes
[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         return folder.exists() || folder.mkdirs();
61     }
62
63     /**
64      * delete file.
65      *
66      * @param file
67      *            the file to delete
68      * @return boolean
69      */
70     public static boolean deleteFile(File file) {
71         String hintInfo = file.isDirectory() ? "dir " : "file ";
72         String fileAbsPath = "";
73         boolean isFileDeleted=false;
74         try {
75             if (file.exists()){
76             Files.delete(Paths.get(file.getPath()));
77             fileAbsPath = file.getAbsolutePath();
78             logger.info("delete {} {}" ,hintInfo, fileAbsPath);
79             }
80             else{
81                  logger.info("file not exist. no need delete {} {}" ,hintInfo , fileAbsPath);
82             }
83             isFileDeleted=true;
84
85         } catch (IOException e) {
86             logger.error("fail to delete {} {} ", hintInfo, fileAbsPath, e);
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         boolean isFileDeleted=false;
199         String fileAbsPath = file.getAbsolutePath();
200         try {
201             Files.delete(Paths.get(file.getPath()));
202             isFileDeleted=true;
203         } catch (IOException e) {
204             logger.error("fail to delete {} {} ", fileAbsPath, e);
205         }
206         return isFileDeleted;
207     }
208
209     public static boolean validateStream(FileInputStream ifs) {
210
211         if (null == ifs) {
212             logger.error("File stream is null");
213             return false;
214         }
215
216         try {
217             if (!ifs.getFD().valid()) {
218                 logger.error("File descriptor is not valid");
219                 return false;
220             }
221         } catch (IOException e) {
222             logger.error("Exception while getting File descriptor", e);
223         }
224
225         return true;
226     }
227
228     public static boolean validatePath(String path) {
229         if (!new File(path).isDirectory()) {
230             logger.error("File is not a directory");
231             return false;
232         }
233         return true;
234     }
235
236     public static boolean validateFile(File fileData) {
237         if (null == fileData) {
238             logger.error("File data is null");
239             return false;
240         }
241
242         if (MAX_PACKAGE_SIZE < fileData.length()) {
243             logger.error("File size is greater than 50 MB {}", fileData.length());
244             return false;
245         }
246
247         return true;
248     }
249 }