2 * Copyright © 2016-2018 European Support Limited
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.openecomp.core.utilities.file;
18 import java.io.ByteArrayInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
24 import java.nio.file.Path;
25 import java.util.Collections;
26 import java.util.Enumeration;
27 import java.util.HashMap;
28 import java.util.LinkedList;
29 import java.util.List;
31 import java.util.Objects;
32 import java.util.function.Function;
33 import org.apache.commons.io.FilenameUtils;
34 import org.apache.commons.io.IOUtils;
35 import org.onap.sdc.tosca.services.YamlUtil;
36 import org.openecomp.core.utilities.json.JsonUtil;
37 import org.openecomp.sdc.common.zip.ZipUtils;
38 import org.openecomp.sdc.common.zip.exception.ZipException;
41 * The type File utils.
43 public class FileUtils {
46 * Allows to consume an input stream open against a resource with a given file name.
48 * @param fileName the file name
49 * @param function logic to be applied to the input stream
51 public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
52 Objects.requireNonNull(fileName);
53 // the leading slash doesn't make sense and doesn't work when used with a class loader
54 URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") ? fileName.substring(1) : fileName);
55 if (resource == null) {
56 throw new IllegalArgumentException("Resource not found: " + fileName);
58 return readViaInputStream(resource, function);
62 * Allows to consume an input stream open against a resource with a given URL.
64 * @param urlFile the url file
65 * @param function logic to be applied to the input stream
67 public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
68 Objects.requireNonNull(urlFile);
69 try (InputStream is = urlFile.openStream()) {
70 return function.apply(is);
71 } catch (IOException exception) {
72 throw new RuntimeException(exception);
77 * Gets file input streams.
79 * @param fileName the file name
80 * @return the file input streams
82 public static List<URL> getAllLocations(String fileName) {
83 List<URL> urls = new LinkedList<>();
84 Enumeration<URL> urlFiles;
86 urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
87 while (urlFiles.hasMoreElements()) {
88 urls.add(urlFiles.nextElement());
90 } catch (IOException exception) {
91 throw new RuntimeException(exception);
93 return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
97 * Convert to bytes byte [ ].
99 * @param object the object
100 * @param extension the extension
101 * @return the byte [ ]
103 public static byte[] convertToBytes(Object object, FileExtension extension) {
104 if (object != null) {
105 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
106 return new YamlUtil().objectToYaml(object).getBytes();
108 return JsonUtil.object2Json(object).getBytes();
116 * Convert to input stream input stream.
118 * @param object the object
119 * @param extension the extension
120 * @return the input stream
122 public static InputStream convertToInputStream(Object object, FileExtension extension) {
123 if (object != null) {
125 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
126 content = new YamlUtil().objectToYaml(object).getBytes();
128 content = JsonUtil.object2Json(object).getBytes();
130 return new ByteArrayInputStream(content);
137 * Load file to input stream input stream.
139 * @param fileName the file name
140 * @return the input stream
142 public static InputStream loadFileToInputStream(String fileName) {
143 URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
145 Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
146 while (en.hasMoreElements()) {
147 urlFile = en.nextElement();
149 } catch (IOException | NullPointerException exception) {
150 throw new RuntimeException(exception);
153 if (urlFile != null) {
154 return urlFile.openStream();
156 throw new RuntimeException();
158 } catch (IOException | NullPointerException exception) {
159 throw new RuntimeException(exception);
164 * To byte array byte [ ].
166 * @param input the input
167 * @return the byte [ ]
169 public static byte[] toByteArray(InputStream input) {
174 return IOUtils.toByteArray(input);
175 } catch (IOException exception) {
176 throw new RuntimeException("error while converting input stream to byte array", exception);
181 * Gets file without extention.
183 * @param fileName the file name
184 * @return the file without extention
186 public static String getFileWithoutExtention(String fileName) {
187 if (!fileName.contains(".")) {
190 return fileName.substring(0, fileName.lastIndexOf('.'));
193 public static String getFileExtension(String filename) {
194 return FilenameUtils.getExtension(filename);
197 public static String getNetworkPackageName(String filename) {
198 String[] split = filename.split("\\.");
200 if (split.length > 1) {
207 * Gets file content map from zip.
209 * @param zipData the zip data
210 * @return the file content map from zip
211 * @throws ZipException when an error occurs while extracting zip files
213 public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws ZipException {
214 final Map<String, byte[]> zipFileAndByteMap = ZipUtils.readZip(zipData, true);
215 final FileContentHandler fileContentHandler = new FileContentHandler();
216 zipFileAndByteMap.forEach((path, bytes) -> {
218 fileContentHandler.addFolder(path);
220 fileContentHandler.addFile(path, bytes);
223 return fileContentHandler;
227 * Write files and folders map to disk in the given path
229 * @param fileContentHandler the file content handler
231 * @return a map containing file names and their absolute paths
232 * @throws IOException the io exception
234 public static Map<String, String> writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler, final Path dir)
236 final File dirFile = dir.toFile();
237 final Map<String, String> filePaths = new HashMap<>();
239 for (final String folderPath : fileContentHandler.getFolderList()) {
240 file = new File(dirFile, folderPath);
241 filePaths.put(folderPath, file.getAbsolutePath());
242 if (!file.exists() && !file.mkdirs()) {
243 throw new IOException("Could not create directory " + file.getAbsolutePath());
246 for (final Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
247 file = new File(dirFile, fileEntry.getKey());
248 filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
249 final byte[] fileBytes = fileEntry.getValue();
250 if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
251 throw new IOException("Could not create parent directory for " + file.getAbsolutePath());
253 try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
254 fop.write(fileBytes);
262 * Verify whether the provided extension is valid Yaml/Yml extension or not.
264 * @param fileExtension the file extension
265 * @return the boolean
267 public static boolean isValidYamlExtension(String fileExtension) {
268 return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) || fileExtension
269 .equalsIgnoreCase(FileExtension.YAML.getDisplayName());
273 * The enum File extension.
275 public enum FileExtension {
277 * Json file extension.
281 * Yaml file extension.
285 * Yml file extension.
288 private final String displayName;
290 FileExtension(String displayName) {
291 this.displayName = displayName;
297 * @return the display name
299 public String getDisplayName() {