786def961adf3f74744497eeb026b09e55edb0cb
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.core.utilities.file;
22
23 import org.apache.commons.io.FilenameUtils;
24 import org.apache.commons.io.IOUtils;
25 import org.openecomp.core.utilities.json.JsonUtil;
26 import org.openecomp.sdc.tosca.services.YamlUtil;
27
28 import java.io.ByteArrayInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.net.URL;
32 import java.util.Collections;
33 import java.util.Enumeration;
34 import java.util.LinkedList;
35 import java.util.List;
36 import java.util.Objects;
37 import java.util.function.Function;
38 import java.util.zip.ZipEntry;
39 import java.util.zip.ZipInputStream;
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 will convertion input stream to byte array:" + exception.getMessage());
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 IOException the io exception
228    */
229   public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
230
231     try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData))) {
232
233       FileContentHandler mapFileContent = new FileContentHandler();
234
235       ZipEntry zipEntry;
236
237       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
238         mapFileContent.addFile(zipEntry.getName(), FileUtils.toByteArray(inputZipStream));
239       }
240
241       return mapFileContent;
242
243     } catch (RuntimeException exception) {
244       throw new IOException(exception);
245     }
246   }
247
248
249   /**
250    * The enum File extension.
251    */
252   public enum FileExtension {
253
254     /**
255      * Json file extension.
256      */
257     JSON("json"),
258     /**
259      * Yaml file extension.
260      */
261     YAML("yaml"),
262     /**
263      * Yml file extension.
264      */
265     YML("yml");
266
267     private String displayName;
268
269     FileExtension(String displayName) {
270       this.displayName = displayName;
271     }
272
273     /**
274      * Gets display name.
275      *
276      * @return the display name
277      */
278     public String getDisplayName() {
279       return displayName;
280     }
281   }
282
283
284 }