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