e70ad923a2025639ffef4b199e631d9c62ac4297
[sdc.git] /
1 /*
2  * Copyright © 2016-2017 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.IOException;
26 import java.io.InputStream;
27 import java.net.URL;
28 import java.util.Collections;
29 import java.util.Enumeration;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.Objects;
33 import java.util.function.Function;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipInputStream;
36
37 /**
38  * The type File utils.
39  */
40 public class FileUtils {
41
42   /**
43    * Allows to consume an input stream open against a resource with a given file name.
44    *
45    * @param fileName the file name
46    * @param function logic to be applied to the input stream
47    */
48   public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
49
50     Objects.requireNonNull(fileName);
51
52     // the leading slash doesn't make sense and doesn't work when used with a class loader
53     URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
54         ? fileName.substring(1) : fileName);
55     if (resource == null) {
56       throw new IllegalArgumentException("Resource not found: " + fileName);
57     }
58
59     return readViaInputStream(resource, function);
60   }
61
62   /**
63    * Allows to consume an input stream open against a resource with a given URL.
64    *
65    * @param urlFile the url file
66    * @param function logic to be applied to the input stream
67    */
68   public static <T> T readViaInputStream(URL urlFile, Function<InputStream, T> function) {
69
70     Objects.requireNonNull(urlFile);
71     try (InputStream is = urlFile.openStream()) {
72       return function.apply(is);
73     } catch (IOException exception) {
74       throw new RuntimeException(exception);
75     }
76   }
77
78   /**
79    * Gets file input streams.
80    *
81    * @param fileName the file name
82    * @return the file input streams
83    */
84   public static List<URL> getAllLocations(String fileName) {
85
86     List<URL> urls = new LinkedList<>();
87     Enumeration<URL> urlFiles;
88
89     try {
90       urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
91       while (urlFiles.hasMoreElements()) {
92         urls.add(urlFiles.nextElement());
93       }
94
95
96     } catch (IOException exception) {
97       throw new RuntimeException(exception);
98     }
99
100     return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
101   }
102
103   /**
104    * Convert to bytes byte [ ].
105    *
106    * @param object    the object
107    * @param extension the extension
108    * @return the byte [ ]
109    */
110   public static byte[] convertToBytes(Object object, FileExtension extension) {
111     if (object != null) {
112       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
113         return new YamlUtil().objectToYaml(object).getBytes();
114       } else {
115         return JsonUtil.object2Json(object).getBytes();
116       }
117     } else {
118       return new byte[]{};
119     }
120   }
121
122   /**
123    * Convert to input stream input stream.
124    *
125    * @param object    the object
126    * @param extension the extension
127    * @return the input stream
128    */
129   public static InputStream convertToInputStream(Object object, FileExtension extension) {
130     if (object != null) {
131
132       byte[] content;
133
134       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
135         content = new YamlUtil().objectToYaml(object).getBytes();
136       } else {
137         content = JsonUtil.object2Json(object).getBytes();
138
139       }
140       return new ByteArrayInputStream(content);
141     } else {
142       return null;
143     }
144   }
145
146   /**
147    * Load file to input stream input stream.
148    *
149    * @param fileName the file name
150    * @return the input stream
151    */
152   public static InputStream loadFileToInputStream(String fileName) {
153     URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
154     try {
155       Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
156       while (en.hasMoreElements()) {
157         urlFile = en.nextElement();
158       }
159     } catch (IOException | NullPointerException exception) {
160       throw new RuntimeException(exception);
161     }
162     try {
163       if (urlFile != null) {
164         return urlFile.openStream();
165       } else {
166         throw new RuntimeException();
167       }
168     } catch (IOException | NullPointerException exception) {
169       throw new RuntimeException(exception);
170     }
171
172   }
173
174   /**
175    * To byte array byte [ ].
176    *
177    * @param input the input
178    * @return the byte [ ]
179    */
180   public static byte[] toByteArray(InputStream input) {
181     if (input == null) {
182       return new byte[0];
183     }
184     try {
185       return IOUtils.toByteArray(input);
186     } catch (IOException exception) {
187       throw new RuntimeException(
188           "error while converting input stream to byte array", exception);
189     }
190   }
191
192   /**
193    * Gets file without extention.
194    *
195    * @param fileName the file name
196    * @return the file without extention
197    */
198   public static String getFileWithoutExtention(String fileName) {
199     if (!fileName.contains(".")) {
200       return fileName;
201     }
202     return fileName.substring(0, fileName.lastIndexOf('.'));
203   }
204
205   public static String getFileExtension(String filename) {
206       return FilenameUtils.getExtension(filename);
207   }
208
209   public static String getNetworkPackageName(String filename) {
210     String[] split = filename.split("\\.");
211     String name = null;
212     if (split.length > 1) {
213       name = split[0];
214     }
215     return name;
216   }
217
218   /**
219    * Gets file content map from zip.
220    *
221    * @param zipData the zip data
222    * @return the file content map from zip
223    * @throws IOException the io exception
224    */
225   public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
226
227     try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData))) {
228
229       FileContentHandler mapFileContent = new FileContentHandler();
230
231       ZipEntry zipEntry;
232
233       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
234         mapFileContent.addFile(zipEntry.getName(), FileUtils.toByteArray(inputZipStream));
235       }
236
237       return mapFileContent;
238
239     } catch (RuntimeException exception) {
240       throw new IOException(exception);
241     }
242   }
243
244
245   /**
246    * The enum File extension.
247    */
248   public enum FileExtension {
249
250     /**
251      * Json file extension.
252      */
253     JSON("json"),
254     /**
255      * Yaml file extension.
256      */
257     YAML("yaml"),
258     /**
259      * Yml file extension.
260      */
261     YML("yml");
262
263     private final String displayName;
264
265     FileExtension(String displayName) {
266       this.displayName = displayName;
267     }
268
269     /**
270      * Gets display name.
271      *
272      * @return the display name
273      */
274     public String getDisplayName() {
275       return displayName;
276     }
277   }
278
279
280 }