[SDC] Onboarding 1710 rebase.
[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.openecomp.core.utilities.json.JsonUtil;
24 import org.openecomp.sdc.tosca.services.YamlUtil;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.net.URL;
32 import java.util.ArrayList;
33 import java.util.Enumeration;
34 import java.util.List;
35 import java.util.zip.ZipEntry;
36 import java.util.zip.ZipInputStream;
37
38 /**
39  * The type File utils.
40  */
41 public class FileUtils {
42
43   /**
44    * Gets file input stream.
45    *
46    * @param fileName the file name
47    * @return the file input stream
48    */
49   public static InputStream getFileInputStream(String fileName) {
50     URL urlFile = FileUtils.class.getClassLoader().getResource(fileName);
51     InputStream is;
52     try {
53       assert urlFile != null;
54       is = urlFile.openStream();
55     } catch (IOException exception) {
56       throw new RuntimeException(exception);
57     }
58     return is;
59   }
60
61   /**
62    * Gets file input stream.
63    *
64    * @param urlFile the url file
65    * @return the file input stream
66    */
67   public static InputStream getFileInputStream(URL urlFile) {
68     InputStream is;
69     try {
70       assert urlFile != null;
71       is = urlFile.openStream();
72     } catch (IOException exception) {
73       throw new RuntimeException(exception);
74     }
75     return is;
76   }
77
78   /**
79    * Gets file input streams.
80    *
81    * @param fileName the file name
82    * @return the file input streams
83    */
84   public static List<InputStream> getFileInputStreams(String fileName) {
85     Enumeration<URL> urlFiles;
86     List<InputStream> streams = new ArrayList<>();
87     InputStream is;
88     URL url;
89     try {
90       urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
91       while (urlFiles.hasMoreElements()) {
92         url = urlFiles.nextElement();
93         is = url.openStream();
94         streams.add(is);
95       }
96
97
98     } catch (IOException exception) {
99       throw new RuntimeException(exception);
100     }
101     return streams;
102   }
103
104   /**
105    * Convert to bytes byte [ ].
106    *
107    * @param object    the object
108    * @param extension the extension
109    * @return the byte [ ]
110    */
111   public static byte[] convertToBytes(Object object, FileExtension extension) {
112     if (object != null) {
113       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
114         return new YamlUtil().objectToYaml(object).getBytes();
115       } else {
116         return JsonUtil.object2Json(object).getBytes();
117       }
118     } else {
119       return new byte[]{};
120     }
121   }
122
123   /**
124    * Convert to input stream input stream.
125    *
126    * @param object    the object
127    * @param extension the extension
128    * @return the input stream
129    */
130   public static InputStream convertToInputStream(Object object, FileExtension extension) {
131     if (object != null) {
132
133       byte[] content;
134
135       if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
136         content = new YamlUtil().objectToYaml(object).getBytes();
137       } else {
138         content = JsonUtil.object2Json(object).getBytes();
139
140       }
141       return new ByteArrayInputStream(content);
142     } else {
143       return null;
144     }
145   }
146
147   /**
148    * Load file to input stream input stream.
149    *
150    * @param fileName the file name
151    * @return the input stream
152    */
153   public static InputStream loadFileToInputStream(String fileName) {
154     URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
155     try {
156       Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(fileName);
157       while (en.hasMoreElements()) {
158         urlFile = en.nextElement();
159       }
160     } catch (IOException | NullPointerException exception) {
161       throw new RuntimeException(exception);
162     }
163     try {
164       if (urlFile != null) {
165         return urlFile.openStream();
166       } else {
167         throw new RuntimeException();
168       }
169     } catch (IOException | NullPointerException exception) {
170       throw new RuntimeException(exception);
171     }
172
173   }
174
175   /**
176    * To byte array byte [ ].
177    *
178    * @param input the input
179    * @return the byte [ ]
180    */
181   public static byte[] toByteArray(InputStream input) {
182     ByteArrayOutputStream output = new ByteArrayOutputStream();
183     try {
184       copy(input, output);
185     } catch (IOException exception) {
186       throw new RuntimeException(
187           "error will convertion input stream to byte array:" + exception.getMessage());
188     }
189     return output.toByteArray();
190   }
191
192   /**
193    * Copy int.
194    *
195    * @param input  the input
196    * @param output the output
197    * @return the int
198    * @throws IOException the io exception
199    */
200   public static int copy(InputStream input, OutputStream output) throws IOException {
201     long count = copyLarge(input, output);
202     return count > 2147483647L ? -1 : (int) count;
203   }
204
205   private static long copyLarge(InputStream input, OutputStream output) throws IOException {
206     return copyLarge(input, output, new byte[4096]);
207   }
208
209   private static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
210       throws IOException {
211     long count = 0L;
212
213     int n1;
214     if (input == null) {
215       return count;
216     }
217     for (; -1 != (n1 = input.read(buffer)); count += (long) n1) {
218       output.write(buffer, 0, n1);
219     }
220
221     return count;
222
223
224   }
225
226   /**
227    * Gets file without extention.
228    *
229    * @param fileName the file name
230    * @return the file without extention
231    */
232   public static String getFileWithoutExtention(String fileName) {
233     if (!fileName.contains(".")) {
234       return fileName;
235     }
236     return fileName.substring(0, fileName.lastIndexOf("."));
237   }
238
239   /**
240    * Gets file content map from zip.
241    *
242    * @param zipData the zip data
243    * @return the file content map from zip
244    * @throws IOException the io exception
245    */
246   public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException {
247     ZipEntry zipEntry;
248     FileContentHandler mapFileContent = new FileContentHandler();
249     try {
250       ZipInputStream inputZipStream;
251
252       byte[] fileByteContent;
253       String currentEntryName;
254       inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData));
255
256       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
257         currentEntryName = zipEntry.getName();
258         fileByteContent = FileUtils.toByteArray(inputZipStream);
259         mapFileContent.addFile(currentEntryName, fileByteContent);
260       }
261
262     } catch (RuntimeException exception) {
263       throw new IOException(exception);
264     }
265     return mapFileContent;
266   }
267
268
269   /**
270    * The enum File extension.
271    */
272   public enum FileExtension {
273
274     /**
275      * Json file extension.
276      */
277     JSON("json"),
278     /**
279      * Yaml file extension.
280      */
281     YAML("yaml"),
282     /**
283      * Yml file extension.
284      */
285     YML("yml");
286
287     private String displayName;
288
289     FileExtension(String displayName) {
290       this.displayName = displayName;
291     }
292
293     /**
294      * Gets display name.
295      *
296      * @return the display name
297      */
298     public String getDisplayName() {
299       return displayName;
300     }
301   }
302
303
304 }