f510febbcfc72f952509fd800959f4e67160f73e
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-utilities-lib / src / main / java / org / openecomp / core / utilities / file / FileUtils.java
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
17 package org.openecomp.core.utilities.file;
18
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.openecomp.sdc.tosca.services.YamlUtil;
23
24 import java.io.ByteArrayInputStream;
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.URL;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.Collections;
34 import java.util.Enumeration;
35 import java.util.HashMap;
36 import java.util.LinkedList;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Objects;
40 import java.util.function.Function;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipInputStream;
43
44 /**
45  * The type File utils.
46  */
47 public class FileUtils {
48
49   /**
50    * Allows to consume an input stream open against a resource with a given file name.
51    *
52    * @param fileName the file name
53    * @param function logic to be applied to the input stream
54    */
55   public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
56
57     Objects.requireNonNull(fileName);
58
59     // the leading slash doesn't make sense and doesn't work when used with a class loader
60     URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
61         ? fileName.substring(1) : fileName);
62     if (resource == null) {
63       throw new IllegalArgumentException("Resource not found: " + fileName);
64     }
65
66     return readViaInputStream(resource, function);
67   }
68
69   /**
70    * Allows to consume an input stream open against a resource with a given URL.
71    *
72    * @param urlFile the url file
73    * @param function logic to be applied to the input stream
74    */
75   public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
76
77     Objects.requireNonNull(urlFile);
78     try (InputStream is = urlFile.openStream()) {
79       return function.apply(is);
80     } catch (IOException exception) {
81       throw new RuntimeException(exception);
82     }
83   }
84
85   /**
86    * Gets file input streams.
87    *
88    * @param fileName the file name
89    * @return the file input streams
90    */
91   public static List<URL> getAllLocations(String fileName) {
92
93     List<URL> urls = new LinkedList<>();
94     Enumeration<URL> urlFiles;
95
96     try {
97       urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
98       while (urlFiles.hasMoreElements()) {
99         urls.add(urlFiles.nextElement());
100       }
101
102
103     } catch (IOException exception) {
104       throw new RuntimeException(exception);
105     }
106
107     return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
108   }
109
110   /**
111    * Convert to bytes byte [ ].
112    *
113    * @param object    the object
114    * @param extension the extension
115    * @return the byte [ ]
116    */
117   public static byte[] convertToBytes(Object object, FileExtension extension) {
118     if (object != null) {
119       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
120         return new YamlUtil().objectToYaml(object).getBytes();
121       } else {
122         return JsonUtil.object2Json(object).getBytes();
123       }
124     } else {
125       return new byte[]{};
126     }
127   }
128
129   /**
130    * Convert to input stream input stream.
131    *
132    * @param object    the object
133    * @param extension the extension
134    * @return the input stream
135    */
136   public static InputStream convertToInputStream(Object object, FileExtension extension) {
137     if (object != null) {
138
139       byte[] content;
140
141       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
142         content = new YamlUtil().objectToYaml(object).getBytes();
143       } else {
144         content = JsonUtil.object2Json(object).getBytes();
145
146       }
147       return new ByteArrayInputStream(content);
148     } else {
149       return null;
150     }
151   }
152
153   /**
154    * Load file to input stream input stream.
155    *
156    * @param fileName the file name
157    * @return the input stream
158    */
159   public static InputStream loadFileToInputStream(String fileName) {
160     URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
161     try {
162       Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
163       while (en.hasMoreElements()) {
164         urlFile = en.nextElement();
165       }
166     } catch (IOException | NullPointerException exception) {
167       throw new RuntimeException(exception);
168     }
169     try {
170       if (urlFile != null) {
171         return urlFile.openStream();
172       } else {
173         throw new RuntimeException();
174       }
175     } catch (IOException | NullPointerException exception) {
176       throw new RuntimeException(exception);
177     }
178
179   }
180
181   /**
182    * To byte array byte [ ].
183    *
184    * @param input the input
185    * @return the byte [ ]
186    */
187   public static byte[] toByteArray(InputStream input) {
188     if (input == null) {
189       return new byte[0];
190     }
191     try {
192       return IOUtils.toByteArray(input);
193     } catch (IOException exception) {
194       throw new RuntimeException(
195           "error while converting input stream to byte array", exception);
196     }
197   }
198
199   /**
200    * Gets file without extention.
201    *
202    * @param fileName the file name
203    * @return the file without extention
204    */
205   public static String getFileWithoutExtention(String fileName) {
206     if (!fileName.contains(".")) {
207       return fileName;
208     }
209     return fileName.substring(0, fileName.lastIndexOf('.'));
210   }
211
212   public static String getFileExtension(String filename) {
213       return FilenameUtils.getExtension(filename);
214   }
215
216   public static String getNetworkPackageName(String filename) {
217     String[] split = filename.split("\\.");
218     String name = null;
219     if (split.length > 1) {
220       name = split[0];
221     }
222     return name;
223   }
224
225   /**
226    * Gets file content map from zip.
227    *
228    * @param zipData the zip data
229    * @return the file content map from zip
230    * @throws IOException the io exception
231    */
232   public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
233
234     try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData))) {
235
236       FileContentHandler mapFileContent = new FileContentHandler();
237
238       ZipEntry zipEntry;
239
240       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
241         mapFileContent.addFile(zipEntry.getName(), FileUtils.toByteArray(inputZipStream));
242       }
243
244       return mapFileContent;
245
246     } catch (RuntimeException exception) {
247       throw new IOException(exception);
248     }
249   }
250
251
252   /**
253    * The enum File extension.
254    */
255   public enum FileExtension {
256
257     /**
258      * Json file extension.
259      */
260     JSON("json"),
261     /**
262      * Yaml file extension.
263      */
264     YAML("yaml"),
265     /**
266      * Yml file extension.
267      */
268     YML("yml");
269
270     private final String displayName;
271
272     FileExtension(String displayName) {
273       this.displayName = displayName;
274     }
275
276     /**
277      * Gets display name.
278      *
279      * @return the display name
280      */
281     public String getDisplayName() {
282       return displayName;
283     }
284   }
285
286
287   /**
288    * Write files and folders map to disk in the given path
289    *
290    * @param fileContentHandler the file content handler
291    * @param dir                the dir
292    * @return a map containing file names and their absolute paths
293    * @throws IOException the io exception
294    */
295   public static Map<String, String> writeFilesFromFileContentHandler(FileContentHandler
296                                                                          fileContentHandler,
297                                                                      Path dir)
298       throws IOException {
299
300     File file;
301     File dirFile = dir.toFile();
302     Map<String, String> filePaths = new HashMap<>();
303     for (Map.Entry<String, byte[]> fileEntry : fileContentHandler.getFiles().entrySet()) {
304       file = new File(dirFile, fileEntry.getKey());
305       file.getParentFile().mkdirs();
306       filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
307       try (FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
308         fop.write(fileEntry.getValue());
309         fop.flush();
310       }
311     }
312
313     return filePaths;
314   }
315
316   /**
317    * Verify whether the provided extension is valid Yaml/Yml extension or not.
318    *
319    * @param fileExtension the file extension
320    * @return the boolean
321    */
322   public static boolean isValidYamlExtension(String fileExtension){
323     return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) ||
324         fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName());
325   }
326
327 }