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