Add collaboration feature
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-utilities-lib / src / main / java / org / openecomp / core / utilities / file / FileUtils.java
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   //private final static Logger log = (Logger) LoggerFactory.getLogger(FileUtils.class.getName());
47
48   /**
49    * Allows to consume an input stream open against a resource with a given file name.
50    *
51    * @param fileName the file name
52    * @param function logic to be applied to the input stream
53    */
54   public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) {
55
56     Objects.requireNonNull(fileName);
57
58     // the leading slash doesn't make sense and doesn't work when used with a class loader
59     URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") ? 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 will convertion input stream to byte array:" + exception.getMessage());
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 != null && 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 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 }