Optimize Build
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / frontend / ci / tests / utilities / FileHandling.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.onap.sdc.frontend.ci.tests.utilities;
22
23 import com.aventstack.extentreports.Status;
24 import com.clearspring.analytics.util.Pair;
25 import org.apache.commons.io.FileUtils;
26 import org.onap.sdc.backend.ci.tests.config.Config;
27 import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils;
28 import org.openecomp.sdc.be.model.DataTypeDefinition;
29 import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions;
30 import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
31 import org.openecomp.sdc.common.util.GeneralUtility;
32 import org.yaml.snakeyaml.Yaml;
33
34 import java.io.BufferedOutputStream;
35 import java.io.BufferedWriter;
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.FileOutputStream;
39 import java.io.FileWriter;
40 import java.io.FilenameFilter;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Properties;
51 import java.util.zip.ZipEntry;
52 import java.util.zip.ZipException;
53 import java.util.zip.ZipFile;
54 import java.util.zip.ZipInputStream;
55
56 import static org.testng.AssertJUnit.assertTrue;
57
58 public class FileHandling {
59
60     //  ------------------yaml parser methods----------------------------
61     public static Map<?, ?> parseYamlFile(String filePath) throws Exception {
62         Yaml yaml = new Yaml();
63         File file = new File(filePath);
64         InputStream inputStream = new FileInputStream(file);
65         Map<?, ?> map = new HashMap<>();
66         map = (Map<?, ?>) yaml.load(inputStream);
67         return map;
68     }
69
70     /**
71      * The method return map fetched objects by pattern from yaml file
72      *
73      * @param yamlFile
74      * @param pattern
75      * @return
76      * @throws Exception
77      */
78     public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
79         Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
80         Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
81         return objectMap;
82     }
83
84     @SuppressWarnings("unchecked")
85     public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
86         Map<String, Object> objectMap = null;
87
88         Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
89         if (objectUpdetedEnvFile instanceof HashMap) {
90             objectMap = (Map<String, Object>) objectUpdetedEnvFile;
91         }
92         return objectMap;
93     }
94
95
96     public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
97         @SuppressWarnings("unchecked")
98         Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
99         return dataTypesMap;
100     }
101 //      -------------------------------------------------------------------------------------------------
102
103
104     /**
105      * @param folder, folder name under "Files" folder
106      * @return path to given folder from perspective of working directory or sdc-vnfs repository
107      */
108     public static String getFilePath(String folder) {
109         String filepath = System.getProperty("filePath");
110         boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty());
111
112         // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory )
113         return FileHandling.getBasePath() + "src/test/resources/Files" + File.separator + folder + File.separator;
114     }
115
116     public static String getBasePath() {
117         return System.getProperty("user.dir") + File.separator;
118     }
119
120     public static String getSdcVnfsPath() {
121         String vnfsPath = System.getProperty("vnfs.path");
122         if (vnfsPath != null && !vnfsPath.isEmpty()) {
123             return vnfsPath;
124         }
125         return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
126     }
127
128     public static String getResourcesFilesPath() {
129         return getSdcVnfsPath() + File.separator + "ui-tests" + File.separator + "Files" + File.separator;
130     }
131
132     public static String getCiFilesPath() {
133         return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
134                 + File.separator + "ci";
135     }
136
137     public static String getConfFilesPath() {
138         return getCiFilesPath() + File.separator + "conf" + File.separator;
139     }
140
141     public static String getTestSuitesFilesPath() {
142         return getCiFilesPath() + File.separator + "testSuites" + File.separator;
143     }
144
145     public static String getVnfRepositoryPath() {
146         return getFilePath("VNFs");
147     }
148
149     public static String getUpdateVSPVnfRepositoryPath() {
150         return getFilePath("UpdateVSP");
151     }
152
153     public static File getConfigFile(String configFileName) throws Exception {
154         File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
155         if (!configFile.exists()) {
156             configFile = new File(FileHandling.getConfFilesPath() + configFileName);
157         }
158         return configFile;
159     }
160
161     public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
162         try {
163             File dir = new File(filepath);
164             List<String> filenames = new ArrayList<String>();
165
166             FilenameFilter extensionFilter = new FilenameFilter() {
167                 public boolean accept(File dir, String name) {
168                     return name.endsWith(extension);
169                 }
170             };
171
172             if (dir.isDirectory()) {
173                 for (File file : dir.listFiles(extensionFilter)) {
174                     filenames.add(file.getName());
175                 }
176                 return filenames.toArray();
177             }
178
179         } catch (Exception e) {
180             e.printStackTrace();
181         }
182         return null;
183     }
184
185     public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
186         try {
187             File dir = new File(filepath);
188             List<String> filenames = new ArrayList<String>();
189
190             FilenameFilter extensionFilter = new FilenameFilter() {
191                 public boolean accept(File dir, String name) {
192                     return name.endsWith(extension);
193                 }
194             };
195
196             if (dir.isDirectory()) {
197                 for (File file : dir.listFiles(extensionFilter)) {
198                     filenames.add(file.getName());
199                 }
200
201                 filenames.removeAll(OnboardingUtils.excludeXnfList);
202
203                 return filenames;
204             }
205
206         } catch (Exception e) {
207             e.printStackTrace();
208         }
209         return null;
210     }
211
212     public static String[] getArtifactsFromZip(String filepath, String zipFilename) {
213         try {
214             ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
215             Enumeration<? extends ZipEntry> entries = zipFile.entries();
216
217             List<String> artifactNames = new ArrayList<String>();
218
219             while (entries.hasMoreElements()) {
220                 ZipEntry nextElement = entries.nextElement();
221                 if (!nextElement.isDirectory()) {
222                     if (!nextElement.getName().equals("MANIFEST.json")) {
223                         String name = nextElement.getName();
224                         artifactNames.add(name);
225                     }
226                 }
227             }
228             zipFile.close();
229             // convert list to array
230             return artifactNames.toArray(new String[0]);
231         } catch (ZipException zipEx) {
232             System.err.println("Error in zip file named : " + zipFilename);
233             zipEx.printStackTrace();
234         } catch (IOException e) {
235             System.err.println("Unhandled exception : ");
236             e.printStackTrace();
237         }
238
239         return null;
240
241     }
242
243     public static List<String> getZipFileNamesFromFolder(String filepath) {
244         return filterFileNamesListFromFolder(filepath, ".zip");
245     }
246
247     public static int countFilesInZipFile(String[] artifactsArr, String reqExtension) {
248         int fileCounter = 0;
249         for (String artifact : artifactsArr) {
250             String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1, artifact.length());
251             if (extensionFile.equals(reqExtension)) {
252                 fileCounter++;
253             }
254         }
255         return fileCounter;
256     }
257
258
259     /**
260      * @return last modified file name from default directory
261      * @throws Exception
262      */
263     public static synchronized File getLastModifiedFileNameFromDir() throws Exception {
264         return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
265     }
266
267     /**
268      * @param dirPath
269      * @return last modified file name from dirPath directory
270      */
271     public static synchronized File getLastModifiedFileNameFromDir(String dirPath) {
272         File dir = new File(dirPath);
273         File[] files = dir.listFiles();
274         if (files == null) {
275             assertTrue("File not found under directory " + dirPath, false);
276             return null;
277         }
278
279         File lastModifiedFile = files[0];
280         for (int i = 1; i < files.length; i++) {
281             if (files[i].isDirectory()) {
282                 continue;
283             }
284             if (lastModifiedFile.lastModified() < files[i].lastModified()) {
285                 lastModifiedFile = files[i];
286             }
287         }
288         return lastModifiedFile;
289     }
290
291     public static void deleteDirectory(String directoryPath) {
292         File dir = new File(directoryPath);
293         if (dir.exists()) {
294             try {
295                 FileUtils.cleanDirectory(dir);
296             } catch (IllegalArgumentException e) {
297                 System.out.println("Failed to clean " + dir);
298             } catch (IOException e) {
299                 System.out.println("Failed to clean " + dir);
300             }
301         }
302     }
303
304     public static void createDirectory(String directoryPath) {
305         File directory = new File(String.valueOf(directoryPath));
306         if (!directory.exists()) {
307             directory.mkdirs();
308         }
309     }
310
311
312     /**
313      * The method append data to existing file, if file not exists - create it
314      *
315      * @param pathToFile
316      * @param text
317      * @param leftSpaceCount
318      * @throws IOException
319      */
320     public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException {
321
322         BufferedWriter bw = null;
323         FileWriter fw = null;
324         if (!pathToFile.exists()) {
325             createEmptyFile(pathToFile);
326         }
327         try {
328             fw = new FileWriter(pathToFile, true);
329             bw = new BufferedWriter(fw);
330             StringBuilder sb = new StringBuilder();
331             if (leftSpaceCount > 0) {
332                 for (int i = 0; i < leftSpaceCount; i++) {
333                     sb.append(" ");
334                 }
335             }
336             bw.write(sb.toString() + text);
337             bw.newLine();
338             bw.close();
339             fw.close();
340         } catch (Exception e) {
341             SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
342         }
343     }
344
345     public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException {
346
347         BufferedWriter bw = null;
348         FileWriter fw = null;
349         try {
350             if (!pathToFile.exists()) {
351                 createEmptyFile(pathToFile);
352             }
353             fw = new FileWriter(pathToFile, true);
354             bw = new BufferedWriter(fw);
355             StringBuilder sb = new StringBuilder();
356             if (leftSpaceCount > 0) {
357                 for (int i = 0; i < leftSpaceCount; i++) {
358                     sb.append(" ");
359                 }
360             }
361             for (Map.Entry<String, Pair<String, Object>> entry : dataMap.entrySet()) {
362                 Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right);
363                 bw.write(sb.toString() + record);
364                 bw.newLine();
365             }
366             bw.close();
367             fw.close();
368         } catch (Exception e) {
369             SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
370         }
371     }
372
373     public static void deleteLastDowloadedFiles(List<File> files) throws IOException {
374         for (File file : files) {
375             File fileToDelete = new File(Config.instance().getDownloadAutomationFolder() + file.getName());
376             fileToDelete.delete();
377         }
378     }
379
380     public static void cleanCurrentDownloadDir() throws IOException {
381         try {
382             ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
383             System.gc();
384             FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
385         } catch (Exception e) {
386
387         }
388     }
389
390     public static boolean isFileDownloaded(String downloadPath, String fileName) {
391         File dir = new File(downloadPath);
392         File[] dir_contents = dir.listFiles();
393         return Arrays.stream(dir_contents).anyMatch(file -> file.getName().equals(fileName));
394     }
395
396     public static String getMD5OfFile(File file) throws IOException {
397         String content = FileUtils.readFileToString(file);
398         String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
399         return md5;
400     }
401
402     public static File createEmptyFile(String fileToCreate) {
403         File file = new File(fileToCreate);
404         try {
405             if (file.exists()) {
406                 deleteFile(file);
407             }
408             file.createNewFile();
409             SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
410         } catch (IOException e) {
411             SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
412             e.printStackTrace();
413         }
414         return file;
415     }
416
417     public static File createEmptyFile(File fileToCreate) {
418         try {
419             if (fileToCreate.exists()) {
420                 deleteFile(fileToCreate);
421             }
422             fileToCreate.createNewFile();
423             SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
424         } catch (IOException e) {
425             SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
426             e.printStackTrace();
427         }
428         return fileToCreate;
429     }
430
431     public static void deleteFile(File file) {
432
433         try {
434             if (file.exists()) {
435                 file.deleteOnExit();
436                 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
437             } else {
438                 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
439             }
440         } catch (Exception e) {
441             e.printStackTrace();
442         }
443
444     }
445
446
447     /**
448      * get file list from directory by extension array
449      *
450      * @param directory
451      * @param okFileExtensions
452      * @return
453      */
454     public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions) {
455
456         List<File> fileList = new ArrayList<>();
457         File[] files = directory.listFiles();
458
459         for (String extension : okFileExtensions) {
460             for (File file : files) {
461                 if (file.getName().toLowerCase().endsWith(extension)) {
462                     fileList.add(file);
463                 }
464             }
465         }
466         return fileList;
467     }
468
469     private static final int BUFFER_SIZE = 4096;
470
471     public static void unzip(String zipFilePath, String destDirectory) throws IOException {
472         File destDir = new File(destDirectory);
473         if (!destDir.exists()) {
474             destDir.mkdir();
475         }
476         ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
477         ZipEntry entry = zipIn.getNextEntry();
478 //         iterates over entries in the zip file
479         while (entry != null) {
480             String entryName;
481             if (System.getProperty("os.name").contains("Windows")) {
482                 entryName = entry.getName().replace("/", "\\" + File.separator);
483             } else {
484                 entryName = entry.getName();
485             }
486             String filePath = destDirectory + entryName;
487             String currPath = destDirectory;
488             String[] dirs = entryName.split("\\" + File.separator);
489             String currToken;
490             for (int i = 0; i < dirs.length; ++i) {
491                 currToken = dirs[i];
492                 if (!entry.isDirectory() && i == dirs.length - 1) {
493                     extractFile(zipIn, filePath);
494                 } else {
495                     if (currPath.endsWith(File.separator)) {
496                         currPath = currPath + currToken;
497                     } else {
498                         currPath = currPath + File.separator + currToken;
499                     }
500 //                     if the entry is a directory, make the directory
501                     File dir = new File(currPath);
502                     dir.mkdir();
503                 }
504             }
505             zipIn.closeEntry();
506             entry = zipIn.getNextEntry();
507         }
508         zipIn.close();
509     }
510
511     private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
512         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
513         byte[] bytesIn = new byte[BUFFER_SIZE];
514         int read = 0;
515         while ((read = zipIn.read(bytesIn)) != -1) {
516             bos.write(bytesIn, 0, read);
517         }
518         bos.close();
519     }
520
521     public static int getFileCountFromDefaulDownloadDirectory() {
522         return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
523     }
524
525
526     public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
527         Properties prop = new Properties();
528         InputStream input = null;
529         String value = null;
530         try {
531             input = new FileInputStream(fullPath);
532             prop.load(input);
533             value = (prop.getProperty(key));
534
535         } catch (IOException ex) {
536             ex.printStackTrace();
537         } finally {
538             if (input != null) {
539                 try {
540                     input.close();
541                 } catch (IOException e) {
542                     e.printStackTrace();
543                 }
544             }
545         }
546
547         return value.replaceAll("\"", "");
548     }
549 }