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 org.apache.commons.io.FilenameUtils;
20 import org.apache.commons.io.IOUtils;
21 import org.openecomp.core.utilities.json.JsonUtil;
22 import org.onap.sdc.tosca.services.YamlUtil;
24 import java.io.ByteArrayInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
30 import java.nio.file.Path;
31 import java.util.Collections;
32 import java.util.Enumeration;
33 import java.util.HashMap;
34 import java.util.LinkedList;
35 import java.util.List;
37 import java.util.Objects;
38 import java.util.function.Function;
39 import java.util.zip.ZipEntry;
40 import java.util.zip.ZipInputStream;
43 * The type File utils.
45 public class FileUtils {
48 * Allows to consume an input stream open against a resource with a given file name.
50 * @param fileName the file name
51 * @param function logic to be applied to the input stream
53 public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
55 Objects.requireNonNull(fileName);
57 // the leading slash doesn't make sense and doesn't work when used with a class loader
58 URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
59 ? fileName.substring(1) : fileName);
60 if (resource == null) {
61 throw new IllegalArgumentException("Resource not found: " + fileName);
64 return readViaInputStream(resource, function);
68 * Allows to consume an input stream open against a resource with a given URL.
70 * @param urlFile the url file
71 * @param function logic to be applied to the input stream
73 public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
75 Objects.requireNonNull(urlFile);
76 try (InputStream is = urlFile.openStream()) {
77 return function.apply(is);
78 } catch (IOException exception) {
79 throw new RuntimeException(exception);
84 * Gets file input streams.
86 * @param fileName the file name
87 * @return the file input streams
89 public static List<URL> getAllLocations(String fileName) {
91 List<URL> urls = new LinkedList<>();
92 Enumeration<URL> urlFiles;
95 urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
96 while (urlFiles.hasMoreElements()) {
97 urls.add(urlFiles.nextElement());
101 } catch (IOException exception) {
102 throw new RuntimeException(exception);
105 return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
109 * Convert to bytes byte [ ].
111 * @param object the object
112 * @param extension the extension
113 * @return the byte [ ]
115 public static byte[] convertToBytes(Object object, FileExtension extension) {
116 if (object != null) {
117 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
118 return new YamlUtil().objectToYaml(object).getBytes();
120 return JsonUtil.object2Json(object).getBytes();
128 * Convert to input stream input stream.
130 * @param object the object
131 * @param extension the extension
132 * @return the input stream
134 public static InputStream convertToInputStream(Object object, FileExtension extension) {
135 if (object != null) {
139 if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
140 content = new YamlUtil().objectToYaml(object).getBytes();
142 content = JsonUtil.object2Json(object).getBytes();
145 return new ByteArrayInputStream(content);
152 * Load file to input stream input stream.
154 * @param fileName the file name
155 * @return the input stream
157 public static InputStream loadFileToInputStream(String fileName) {
158 URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
160 Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
161 while (en.hasMoreElements()) {
162 urlFile = en.nextElement();
164 } catch (IOException | NullPointerException exception) {
165 throw new RuntimeException(exception);
168 if (urlFile != null) {
169 return urlFile.openStream();
171 throw new RuntimeException();
173 } catch (IOException | NullPointerException exception) {
174 throw new RuntimeException(exception);
180 * To byte array byte [ ].
182 * @param input the input
183 * @return the byte [ ]
185 public static byte[] toByteArray(InputStream input) {
190 return IOUtils.toByteArray(input);
191 } catch (IOException exception) {
192 throw new RuntimeException(
193 "error while converting input stream to byte array", exception);
198 * Gets file without extention.
200 * @param fileName the file name
201 * @return the file without extention
203 public static String getFileWithoutExtention(String fileName) {
204 if (!fileName.contains(".")) {
207 return fileName.substring(0, fileName.lastIndexOf('.'));
210 public static String getFileExtension(String filename) {
211 return FilenameUtils.getExtension(filename);
214 public static String getNetworkPackageName(String filename) {
215 String[] split = filename.split("\\.");
217 if (split.length > 1) {
224 * Gets file content map from zip.
226 * @param zipData the zip data
227 * @return the file content map from zip
228 * @throws IOException the io exception
230 public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
232 try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData))) {
234 FileContentHandler mapFileContent = new FileContentHandler();
238 while ((zipEntry = inputZipStream.getNextEntry()) != null) {
239 mapFileContent.addFile(zipEntry.getName(), FileUtils.toByteArray(inputZipStream));
242 return mapFileContent;
244 } catch (RuntimeException exception) {
245 throw new IOException(exception);
251 * The enum File extension.
253 public enum FileExtension {
256 * Json file extension.
260 * Yaml file extension.
264 * Yml file extension.
268 private final String displayName;
270 FileExtension(String displayName) {
271 this.displayName = displayName;
277 * @return the display name
279 public String getDisplayName() {
286 * Write files and folders map to disk in the given path
288 * @param fileContentHandler the file content handler
290 * @return a map containing file names and their absolute paths
291 * @throws IOException the io exception
293 public static Map<String, String> writeFilesFromFileContentHandler(FileContentHandler
299 File dirFile = dir.toFile();
300 Map<String, String> filePaths = new HashMap<>();
301 for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
302 file = new File(dirFile, fileEntry.getKey());
303 file.getParentFile().mkdirs();
304 filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
305 try (FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
306 fop.write(fileEntry.getValue());
315 * Verify whether the provided extension is valid Yaml/Yml extension or not.
317 * @param fileExtension the file extension
318 * @return the boolean
320 public static boolean isValidYamlExtension(String fileExtension){
321 return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) ||
322 fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName());