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