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.
17 package org.openecomp.core.utilities.file;
19 import java.io.ByteArrayInputStream;
21 import java.io.FileOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
25 import java.nio.file.Path;
26 import java.util.Collections;
27 import java.util.Enumeration;
28 import java.util.HashMap;
29 import java.util.LinkedList;
30 import java.util.List;
32 import java.util.Objects;
33 import java.util.function.Function;
34 import org.apache.commons.io.FilenameUtils;
35 import org.apache.commons.io.IOUtils;
36 import org.onap.sdc.tosca.services.YamlUtil;
37 import org.openecomp.core.utilities.json.JsonUtil;
38 import org.openecomp.sdc.common.zip.ZipUtils;
39 import org.openecomp.sdc.common.zip.exception.ZipException;
42 * The type File utils.
44 public class FileUtils {
47 * Allows to consume an input stream open against a resource with a given file name.
49 * @param fileName the file name
50 * @param function logic to be applied to the input stream
52 public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
54 Objects.requireNonNull(fileName);
56 // the leading slash doesn't make sense and doesn't work when used with a class loader
57 URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
58 ? fileName.substring(1) : fileName);
59 if (resource == null) {
60 throw new IllegalArgumentException("Resource not found: " + fileName);
63 return readViaInputStream(resource, function);
67 * Allows to consume an input stream open against a resource with a given URL.
69 * @param urlFile the url file
70 * @param function logic to be applied to the input stream
72 public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
74 Objects.requireNonNull(urlFile);
75 try (InputStream is = urlFile.openStream()) {
76 return function.apply(is);
77 } catch (IOException exception) {
78 throw new RuntimeException(exception);
83 * Gets file input streams.
85 * @param fileName the file name
86 * @return the file input streams
88 public static List<URL> getAllLocations(String fileName) {
90 List<URL> urls = new LinkedList<>();
91 Enumeration<URL> urlFiles;
94 urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
95 while (urlFiles.hasMoreElements()) {
96 urls.add(urlFiles.nextElement());
100 } catch (IOException exception) {
101 throw new RuntimeException(exception);
104 return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
108 * Convert to bytes byte [ ].
110 * @param object the object
111 * @param extension the extension
112 * @return the byte [ ]
114 public static byte[] convertToBytes(Object object, FileExtension extension) {
115 if (object != null) {
116 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
117 return new YamlUtil().objectToYaml(object).getBytes();
119 return JsonUtil.object2Json(object).getBytes();
127 * Convert to input stream input stream.
129 * @param object the object
130 * @param extension the extension
131 * @return the input stream
133 public static InputStream convertToInputStream(Object object, FileExtension extension) {
134 if (object != null) {
138 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
139 content = new YamlUtil().objectToYaml(object).getBytes();
141 content = JsonUtil.object2Json(object).getBytes();
144 return new ByteArrayInputStream(content);
151 * Load file to input stream input stream.
153 * @param fileName the file name
154 * @return the input stream
156 public static InputStream loadFileToInputStream(String fileName) {
157 URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
159 Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
160 while (en.hasMoreElements()) {
161 urlFile = en.nextElement();
163 } catch (IOException | NullPointerException exception) {
164 throw new RuntimeException(exception);
167 if (urlFile != null) {
168 return urlFile.openStream();
170 throw new RuntimeException();
172 } catch (IOException | NullPointerException exception) {
173 throw new RuntimeException(exception);
179 * To byte array byte [ ].
181 * @param input the input
182 * @return the byte [ ]
184 public static byte[] toByteArray(InputStream input) {
189 return IOUtils.toByteArray(input);
190 } catch (IOException exception) {
191 throw new RuntimeException(
192 "error while converting input stream to byte array", exception);
197 * Gets file without extention.
199 * @param fileName the file name
200 * @return the file without extention
202 public static String getFileWithoutExtention(String fileName) {
203 if (!fileName.contains(".")) {
206 return fileName.substring(0, fileName.lastIndexOf('.'));
209 public static String getFileExtension(String filename) {
210 return FilenameUtils.getExtension(filename);
213 public static String getNetworkPackageName(String filename) {
214 String[] split = filename.split("\\.");
216 if (split.length > 1) {
223 * Gets file content map from zip.
225 * @param zipData the zip data
226 * @return the file content map from zip
227 * @throws ZipException when an error occurs while extracting zip files
229 public static FileContentHandler getFileContentMapFromZip(byte[] zipData)
230 throws ZipException {
231 final Map<String, byte[]> zipFileAndByteMap = ZipUtils.readZip(zipData, true);
232 final FileContentHandler fileContentHandler = new FileContentHandler();
233 zipFileAndByteMap.forEach((path, bytes) -> {
235 fileContentHandler.addFolder(path);
237 fileContentHandler.addFile(path, bytes);
240 return fileContentHandler;
245 * The enum File extension.
247 public enum FileExtension {
250 * Json file extension.
254 * Yaml file extension.
258 * Yml file extension.
262 private final String displayName;
264 FileExtension(String displayName) {
265 this.displayName = displayName;
271 * @return the display name
273 public String getDisplayName() {
280 * Write files and folders map to disk in the given path
282 * @param fileContentHandler the file content handler
284 * @return a map containing file names and their absolute paths
285 * @throws IOException the io exception
287 public static Map<String, String> writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler,
288 final Path dir) throws IOException {
289 final File dirFile = dir.toFile();
290 final Map<String, String> filePaths = new HashMap<>();
292 for (final String folderPath : fileContentHandler.getFolderList()) {
293 file = new File(dirFile, folderPath);
294 filePaths.put(folderPath, file.getAbsolutePath());
295 if (!file.exists() && !file.mkdirs()) {
296 throw new IOException("Could not create directory " + file.getAbsolutePath());
299 for (final Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
300 file = new File(dirFile, fileEntry.getKey());
301 filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
302 final byte[] fileBytes = fileEntry.getValue();
303 if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
304 throw new IOException("Could not create parent directory for " + file.getAbsolutePath());
306 try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
307 fop.write(fileBytes);
316 * Verify whether the provided extension is valid Yaml/Yml extension or not.
318 * @param fileExtension the file extension
319 * @return the boolean
321 public static boolean isValidYamlExtension(String fileExtension){
322 return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) ||
323 fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName());