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