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