60ff1c172a75c2d08fa6d2ccb9334a16e1934e6c
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
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.openecomp.core.utilities.file;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.File;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.URL;
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;
30 import java.util.Map;
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;
39
40 /**
41  * The type File utils.
42  */
43 public class FileUtils {
44
45     /**
46      * Allows to consume an input stream open against a resource with a given file name.
47      *
48      * @param fileName the file name
49      * @param function logic to be applied to the input stream
50      */
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);
57         }
58         return readViaInputStream(resource, function);
59     }
60
61     /**
62      * Allows to consume an input stream open against a resource with a given URL.
63      *
64      * @param urlFile  the url file
65      * @param function logic to be applied to the input stream
66      */
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);
73         }
74     }
75
76     /**
77      * Gets file input streams.
78      *
79      * @param fileName the file name
80      * @return the file input streams
81      */
82     public static List<URL> getAllLocations(String fileName) {
83         List<URL> urls = new LinkedList<>();
84         Enumeration<URL> urlFiles;
85         try {
86             urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
87             while (urlFiles.hasMoreElements()) {
88                 urls.add(urlFiles.nextElement());
89             }
90         } catch (IOException exception) {
91             throw new RuntimeException(exception);
92         }
93         return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
94     }
95
96     /**
97      * Convert to bytes byte [ ].
98      *
99      * @param object    the object
100      * @param extension the extension
101      * @return the byte [ ]
102      */
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();
107             } else {
108                 return JsonUtil.object2Json(object).getBytes();
109             }
110         } else {
111             return new byte[]{};
112         }
113     }
114
115     /**
116      * Convert to input stream input stream.
117      *
118      * @param object    the object
119      * @param extension the extension
120      * @return the input stream
121      */
122     public static InputStream convertToInputStream(Object object, FileExtension extension) {
123         if (object != null) {
124             byte[] content;
125             if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
126                 content = new YamlUtil().objectToYaml(object).getBytes();
127             } else {
128                 content = JsonUtil.object2Json(object).getBytes();
129             }
130             return new ByteArrayInputStream(content);
131         } else {
132             return null;
133         }
134     }
135
136     /**
137      * Load file to input stream input stream.
138      *
139      * @param fileName the file name
140      * @return the input stream
141      */
142     public static InputStream loadFileToInputStream(String fileName) {
143         URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
144         try {
145             Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
146             while (en.hasMoreElements()) {
147                 urlFile = en.nextElement();
148             }
149         } catch (IOException | NullPointerException exception) {
150             throw new RuntimeException(exception);
151         }
152         try {
153             if (urlFile != null) {
154                 return urlFile.openStream();
155             } else {
156                 throw new RuntimeException();
157             }
158         } catch (IOException | NullPointerException exception) {
159             throw new RuntimeException(exception);
160         }
161     }
162
163     /**
164      * To byte array byte [ ].
165      *
166      * @param input the input
167      * @return the byte [ ]
168      */
169     public static byte[] toByteArray(InputStream input) {
170         if (input == null) {
171             return new byte[0];
172         }
173         try {
174             return IOUtils.toByteArray(input);
175         } catch (IOException exception) {
176             throw new RuntimeException("error while converting input stream to byte array", exception);
177         }
178     }
179
180     /**
181      * Gets file without extention.
182      *
183      * @param fileName the file name
184      * @return the file without extention
185      */
186     public static String getFileWithoutExtention(String fileName) {
187         if (!fileName.contains(".")) {
188             return fileName;
189         }
190         return fileName.substring(0, fileName.lastIndexOf('.'));
191     }
192
193     public static String getFileExtension(String filename) {
194         return FilenameUtils.getExtension(filename);
195     }
196
197     public static String getNetworkPackageName(String filename) {
198         String[] split = filename.split("\\.");
199         String name = null;
200         if (split.length > 1) {
201             name = split[0];
202         }
203         return name;
204     }
205
206     /**
207      * Gets file content map from zip.
208      *
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
212      */
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) -> {
217             if (bytes == null) {
218                 fileContentHandler.addFolder(path);
219             } else {
220                 fileContentHandler.addFile(path, bytes);
221             }
222         });
223         return fileContentHandler;
224     }
225
226     /**
227      * Write files and folders map to disk in the given path
228      *
229      * @param fileContentHandler the file content handler
230      * @param dir                the dir
231      * @return a map containing file names and their absolute paths
232      * @throws IOException the io exception
233      */
234     public static Map<String, String> writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler, final Path dir)
235         throws IOException {
236         final File dirFile = dir.toFile();
237         final Map<String, String> filePaths = new HashMap<>();
238         File file;
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());
244             }
245         }
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());
252             }
253             try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
254                 fop.write(fileBytes);
255                 fop.flush();
256             }
257         }
258         return filePaths;
259     }
260
261     /**
262      * Verify whether the provided extension is valid Yaml/Yml extension or not.
263      *
264      * @param fileExtension the file extension
265      * @return the boolean
266      */
267     public static boolean isValidYamlExtension(String fileExtension) {
268         return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) || fileExtension
269             .equalsIgnoreCase(FileExtension.YAML.getDisplayName());
270     }
271
272     /**
273      * The enum File extension.
274      */
275     public enum FileExtension {
276         /**
277          * Json file extension.
278          */
279         JSON("json"),
280         /**
281          * Yaml file extension.
282          */
283         YAML("yaml"),
284         /**
285          * Yml file extension.
286          */
287         YML("yml");
288         private final String displayName;
289
290         FileExtension(String displayName) {
291             this.displayName = displayName;
292         }
293
294         /**
295          * Gets display name.
296          *
297          * @return the display name
298          */
299         public String getDisplayName() {
300             return displayName;
301         }
302     }
303 }