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