2 * Copyright 2017 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.vnfsdk.marketplace.common;
18 import java.io.BufferedOutputStream;
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;
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
40 public final class FileUtil {
42 public static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
44 private static final int BUFFER_SIZE = 2 * 1024 * 1024;
46 private static final int MAX_PACKAGE_SIZE = 50 * 1024 * 1024;
47 private static Gson gson = new Gson();
60 public static boolean createDirectory(String dir) {
61 File folder = new File(dir);
62 return folder.exists() || folder.mkdirs();
72 public static boolean deleteFile(File file) {
73 String hintInfo = file.isDirectory() ? "dir " : "file ";
74 String fileAbsPath = "";
75 boolean isFileDeleted=false;
78 Files.delete(Paths.get(file.getPath()));
79 fileAbsPath = file.getAbsolutePath();
80 logger.info("delete {} {}" ,hintInfo, fileAbsPath);
83 logger.info("file not exist. no need delete {} {}" ,hintInfo , fileAbsPath);
87 } catch (IOException e) {
88 logger.error("fail to delete {} {} ", hintInfo, fileAbsPath, e);
100 * @return unzip file name
101 * @throws IOException
104 public static List<String> unzip(String zipFileName, String extPlace) throws IOException {
105 List<String> unzipFileNams = new ArrayList<>();
107 try (ZipFile zipFile = new ZipFile(zipFileName);) {
108 Enumeration<?> fileEn = zipFile.entries();
109 byte[] buffer = new byte[BUFFER_SIZE];
111 while (fileEn.hasMoreElements()) {
112 ZipEntry entry = (ZipEntry) fileEn.nextElement();
113 if (entry.isDirectory()) {
117 File file = new File(extPlace, entry.getName());
118 if (!file.getParentFile().exists()) {
119 createDirectory(file.getParentFile().getAbsolutePath());
122 try (InputStream input = zipFile.getInputStream(entry);
123 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));) {
125 while ((length = input.read(buffer)) != -1) {
126 bos.write(buffer, 0, length);
128 unzipFileNams.add(file.getAbsolutePath());
132 return unzipFileNams;
135 public static boolean checkFileExists(String filePath) {
136 File file = new File(filePath);
137 return file.exists();
140 public static boolean deleteFile(String filePath) {
141 File file = new File(filePath);
142 return deleteFile(file);
145 public static boolean writeJsonDatatoFile(String fileAbsPath, Object obj) {
146 logger.info("Write JsonData to file : {} " , fileAbsPath);
148 boolean bResult = false;
149 if (checkFileExists(fileAbsPath)) {
150 deleteFile(fileAbsPath);
153 try(FileWriter writer = new FileWriter(new File(fileAbsPath))) {
154 gson.toJson(obj, writer);
156 } catch (Exception e) { //NOSONAR
157 logger.info("Exception: writeJsonDatatoFile-->{} {}" , fileAbsPath, e);
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);
168 logger.info("read JsonData from file : {}" , fileAbsPath);
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
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
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);
186 public static boolean deleteDirectory(String path) {
187 File file = new File(path);
188 return deleteDirectory(file);
191 public static boolean deleteDirectory(File file) {
192 if (!file.exists()) {
195 if (file.isDirectory()) {
196 for (File f : file.listFiles()) {
200 boolean isFileDeleted=false;
201 String fileAbsPath = file.getAbsolutePath();
203 Files.delete(Paths.get(file.getPath()));
205 } catch (IOException e) {
206 logger.error("fail to delete {} {} ", fileAbsPath, e);
208 return isFileDeleted;
211 public static boolean validateStream(FileInputStream ifs) {
214 logger.error("File stream is null");
219 if (!ifs.getFD().valid()) {
220 logger.error("File descriptor is not valid");
223 } catch (IOException e) {
224 logger.error("Exception while getting File descriptor", e);
230 public static boolean validatePath(String path) {
231 if (!new File(path).isDirectory()) {
232 logger.error("File is not a directory");
238 public static boolean validateFile(File fileData) {
239 if (null == fileData) {
240 logger.error("File data is null");
244 if (MAX_PACKAGE_SIZE < fileData.length()) {
245 logger.error("File size is greater than 50 MB {}", fileData.length());
253 * Search file in folder
258 public static List<File> searchFiles(File folder, String keyword) {
259 List<File> result = new ArrayList<File>();
263 File[] subFolders = folder.listFiles(new FileFilter() {
265 public boolean accept(File file) {
266 if (file.isDirectory()) {
269 if (file.getName().toLowerCase().contains(keyword)) {
276 if (subFolders != null) {
277 for (File file : subFolders) {
281 result.addAll(searchFiles(file, keyword));