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