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