81ca398813e96811639cc24b89a0830d0e0b4519
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / backend / ci / tests / utils / general / FileHandling.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2021 Nokia. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.sdc.backend.ci.tests.utils.general;
23
24 import static org.testng.AssertJUnit.assertTrue;
25
26 import com.aventstack.extentreports.Status;
27 import java.io.BufferedWriter;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileWriter;
31 import java.io.FilenameFilter;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.nio.file.Paths;
35 import java.util.ArrayList;
36 import java.util.EnumMap;
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 org.apache.commons.io.FileUtils;
46 import org.onap.sdc.backend.ci.tests.api.ComponentBaseTest;
47 import org.onap.sdc.backend.ci.tests.datatypes.enums.PackageTypeEnum;
48 import org.openecomp.sdc.be.model.DataTypeDefinition;
49 import org.openecomp.sdc.common.util.GeneralUtility;
50 import org.yaml.snakeyaml.Yaml;
51
52 public class FileHandling {
53
54 //      ------------------yaml parser methods----------------------------
55         public static Map<?, ?> parseYamlFile(String filePath) throws Exception {
56                 Yaml yaml = new Yaml();
57                 File file = new File(filePath);
58                 InputStream inputStream = new FileInputStream(file);
59                 Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
60                 return map;
61         }
62
63         /**
64          * The method return map fetched objects by pattern from yaml file
65          * @param yamlFile
66          * @param pattern
67          * @return
68          * @throws Exception
69          */
70         public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
71                 Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
72                 Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
73                 return objectMap;
74         }
75
76         @SuppressWarnings("unchecked")
77         public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
78                 Map<String, Object> objectMap = null;
79
80                 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
81                 if(objectUpdetedEnvFile instanceof HashMap){
82                         objectMap = (Map<String, Object>) objectUpdetedEnvFile;
83                 }
84                 return objectMap;
85         }
86
87
88         public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
89                 @SuppressWarnings("unchecked")
90                 Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
91                 return dataTypesMap;
92         }
93 //      -------------------------------------------------------------------------------------------------
94
95         /**
96          * @param folder, folder name under "Files" folder
97          * @return path to given folder from perspective of working directory or sdc-vnfs repository
98          */
99         public static String getFilePath(String folder) {
100                 // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory )
101                 return FileHandling.getBasePath() + "src/test/resources/Files" + File.separator + folder + File.separator;
102         }
103
104         public static String getBasePath() {
105                 return System.getProperty("user.dir") + File.separator;
106         }
107
108         public static String getSdcVnfsPath() {
109                 return  getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
110         }
111
112         public static String getDriversPath() {
113                 return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
114                                 + File.separator + "ci" + File.separator + "drivers" + File.separator;
115         }
116
117         public static String getResourcesFilesPath() {
118                 return getSdcVnfsPath()+ File.separator + "ui-tests" + File.separator + "Files" + File.separator;
119         }
120
121         public static String getResourcesEnvFilesPath() {
122                 return getBasePath() + File.separator + "src" + File.separator + "test" + File.separator + "resources"
123                                 + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator;
124         }
125
126         public static String getCiFilesPath() {
127                 return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
128                                 + File.separator + "ci";
129         }
130
131         public static String getConfFilesPath() {
132                 return getCiFilesPath() + File.separator + "conf" + File.separator;
133         }
134
135         private static final EnumMap<PackageTypeEnum, String> PACKAGE_REPOSITORY_PATHS_MAP = new EnumMap<>(Map.of(
136                 PackageTypeEnum.PNF, getPnfRepositoryPath(),
137                 PackageTypeEnum.CNF, getCnfRepositoryPath(),
138                 PackageTypeEnum.CNF_HELM, getCnfRepositoryForHelmValidatorPath(),
139                 PackageTypeEnum.VNF, getVnfRepositoryPath(),
140                 PackageTypeEnum.ETSI, getEtsiRepositoryPath(),
141                 PackageTypeEnum.VFC, getVfcRepositoryPath()
142         ));
143
144         public static String getVnfRepositoryPath() {
145                 return getFilePath("VNFs");
146         }
147
148         private static String getPnfRepositoryPath() {
149                 return getFilePath("PNFs");
150         }
151
152         private static String getCnfRepositoryPath() {
153                 return getFilePath("CNFs");
154         }
155
156         private static String getCnfRepositoryForHelmValidatorPath() {
157                 return getFilePath("CNFs/helm_validator");
158         }
159
160         private static String getEtsiRepositoryPath() { return getFilePath("ETSI"); }
161
162         private static String getVfcRepositoryPath() { return getFilePath("VFCs"); }
163
164         public static String getPackageRepositoryPath(PackageTypeEnum packageTypeEnum) {
165                 return PACKAGE_REPOSITORY_PATHS_MAP.get(packageTypeEnum);
166         }
167
168         public static String getPortMirroringRepositoryPath() {
169                 return getFilePath("PortMirroring");
170         }
171
172         public static File getConfigFile(String configFileName) throws Exception {
173                 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
174                 if (!configFile.exists()) {
175                         configFile = new File(FileHandling.getConfFilesPath() + configFileName);
176                 }
177                 return configFile;
178         }
179
180         public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
181                 try {
182                         File dir = new File(filepath);
183                         List<String> filenames = new ArrayList<String>();
184
185                         FilenameFilter extensionFilter = new FilenameFilter() {
186                                 public boolean accept(File dir, String name) {
187                                         return name.endsWith(extension);
188                                 }
189                         };
190
191                         if (dir.isDirectory()) {
192                                 for (File file : dir.listFiles(extensionFilter)) {
193                                         filenames.add(file.getName());
194                                 }
195                                 return filenames.toArray();
196                         }
197
198                 } catch (Exception e) {
199                         e.printStackTrace();
200                 }
201                 return null;
202         }
203
204         public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
205                 List<String> filenames = new ArrayList<String>();
206                 try {
207                         File dir = new File(filepath);
208
209                         FilenameFilter extensionFilter = new FilenameFilter() {
210                                 public boolean accept(File dir, String name) {
211                                         return name.endsWith(extension);
212                                 }
213                         };
214
215                         if (dir.isDirectory()) {
216                                 for (File file : dir.listFiles(extensionFilter)) {
217                                         filenames.add(file.getName());
218                                 }
219                                 return filenames;
220                         }
221
222                 } catch (Exception e) {
223                         e.printStackTrace();
224                 }
225                 return filenames;
226         }
227
228         public static String[] getArtifactsFromZip(String filepath, String zipFilename){
229                 try {
230                         ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
231                         Enumeration<? extends ZipEntry> entries = zipFile.entries();
232
233                         String[] artifactNames = new String[zipFile.size() - 1];
234
235                         int i = 0;
236                         while(entries.hasMoreElements()){
237                                 ZipEntry nextElement = entries.nextElement();
238                                 if (!nextElement.isDirectory()){
239                                         if (!nextElement.getName().equals("MANIFEST.json")){
240                                                 String name = nextElement.getName();
241                                                 artifactNames[i++] = name;
242                                         }
243                                 }
244                         }
245                         zipFile.close();
246                         return artifactNames;
247                 } catch(ZipException zipEx) {
248                         System.err.println("Error in zip file named : " +  zipFilename);
249                         zipEx.printStackTrace();
250                 } catch (IOException e) {
251                         System.err.println("Unhandled exception : ");
252                         e.printStackTrace();
253                 }
254
255                 return null;
256
257         }
258
259         public static List<String> getFileNamesFromZip(String zipFileLocation){
260                 try{
261                         ZipFile zipFile = new ZipFile(zipFileLocation);
262                         Enumeration<? extends ZipEntry> entries = zipFile.entries();
263
264                         List<String> artifactNames = new ArrayList<>();
265
266                         int i = 0;
267                         while(entries.hasMoreElements()){
268                                 ZipEntry nextElement = entries.nextElement();
269                                 if (!nextElement.isDirectory()){
270                                         String name = nextElement.getName();
271                                         artifactNames.add(name);
272                                 }
273                         }
274                         zipFile.close();
275                         return artifactNames;
276                 }
277                 catch(ZipException zipEx){
278                         System.err.println("Error in zip file named : " +  zipFileLocation);
279                         zipEx.printStackTrace();
280                 } catch (IOException e) {
281                         System.err.println("Unhandled exception : ");
282                         e.printStackTrace();
283                 }
284                 return null;
285         }
286
287         public static List<String> getZipFileNamesFromFolder(String filepath) {
288                 List<String> fileNamesListFromFolder = filterFileNamesListFromFolder(filepath, ".zip");
289                 fileNamesListFromFolder.addAll(filterFileNamesListFromFolder(filepath, ".csar"));
290                 return fileNamesListFromFolder;
291         }
292
293         public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
294                 int fileCounter = 0;
295                 for (String artifact : artifactsArr){
296                         String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
297                         if (extensionFile.equals(reqExtension)){
298                                 fileCounter++;
299                         }
300                 }
301                 return fileCounter;
302         }
303
304         /**
305          * @param dirPath
306          * @return last modified file name from dirPath directory
307          */
308         public static synchronized File getLastModifiedFileNameFromDir(String dirPath){
309             File dir = new File(dirPath);
310             File[] files = dir.listFiles();
311             if (files == null) {
312                 assertTrue("File not found under directory " + dirPath, false);
313                 return null;
314             }
315
316             File lastModifiedFile = files[0];
317             for (int i = 1; i < files.length; i++) {
318                 if(files[i].isDirectory()) {
319                         continue;
320                 }
321                 if (lastModifiedFile.lastModified()  < files[i].lastModified()) {
322                    lastModifiedFile = files[i];
323                 }
324             }
325             return lastModifiedFile;
326         }
327
328         public static void deleteDirectory(String directoryPath) {
329                 File dir = new File(directoryPath);
330                 try {
331                         FileUtils.cleanDirectory(dir);
332                 } catch (IllegalArgumentException e) {
333                         System.out.println("Failed to clean " + dir);
334                 } catch (IOException e) {
335                         System.out.println("Failed to clean " + dir);
336                 }
337         }
338
339         public static void createDirectory(String directoryPath) {
340                 File directory = new File(String.valueOf(directoryPath));
341             if (! directory.exists()){
342                 directory.mkdirs();
343             }
344         }
345
346
347         /**
348          * The method append data to existing file, if file not exists - create it
349          * @param pathToFile
350          * @param text
351          * @param leftSpaceCount
352          * @throws IOException
353          */
354         public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
355
356                 BufferedWriter bw = null;
357                 FileWriter fw = null;
358                 if(!pathToFile.exists()){
359                         createEmptyFile(pathToFile);
360                 }
361                 try {
362                         fw = new FileWriter(pathToFile, true);
363                         bw = new BufferedWriter(fw);
364                         StringBuilder sb = new StringBuilder();
365                         if(leftSpaceCount > 0 ){
366                                 for(int i = 0; i < leftSpaceCount; i++){
367                                         sb.append(" ");
368                                 }
369                         }
370                         bw.write(sb.toString() + text);
371                         bw.newLine();
372                         bw.close();
373                         fw.close();
374                 } catch (Exception e) {
375                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
376                 }
377         }
378
379         public static String getCreateDirByName(String dirName) {
380                 File dir = new File(dirName);
381                 dir.mkdir();
382                 if(!dir.exists()) {
383                 }
384
385                 return dir.getPath();
386         }
387
388         public static boolean isFileDownloaded(String downloadPath, String fileName) {
389                 boolean flag = false;
390                 File dir = new File(downloadPath);
391                 File[] dir_contents = dir.listFiles();
392                 for (int i = 0; i < dir_contents.length; i++) {
393                         if (dir_contents[i].getName().equals(fileName))
394                                 return flag = true;
395                 }
396                 return flag;
397         }
398
399         public static String getMD5OfFile(File file) throws IOException {
400                 String content = FileUtils.readFileToString(file);
401                 String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
402                 return md5;
403         }
404
405         public static File createEmptyFile(String fileToCreate) {
406                 File file= new File(fileToCreate);
407                 try {
408                         if(file.exists()){
409                                 deleteFile(file);
410                         }
411                         file.createNewFile();
412                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
413                 } catch (IOException e) {
414                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
415                         e.printStackTrace();
416                 }
417                 return file;
418         }
419
420         public static File createEmptyFile(File fileToCreate) {
421                 try {
422                         if(fileToCreate.exists()){
423                                 deleteFile(fileToCreate);
424                         }
425                         fileToCreate.createNewFile();
426                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
427                 } catch (IOException e) {
428                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
429                         e.printStackTrace();
430                 }
431                 return fileToCreate;
432         }
433
434         public static void deleteFile(File file){
435
436                 try{
437                 if(file.exists()){
438                         file.deleteOnExit();
439                         ComponentBaseTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
440                 }else{
441                         ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
442                 }
443         }catch(Exception e){
444                 e.printStackTrace();
445         }
446
447         }
448
449
450         /**
451          * get file list from directory by extension array
452          * @param directory
453          * @param okFileExtensions
454          * @return
455          */
456         public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
457
458                         List<File> fileList = new ArrayList<>();
459                         File[] files = directory.listFiles();
460
461                         for (String extension : okFileExtensions){
462                                 for(File file : files){
463                                         if (file.getName().toLowerCase().endsWith(extension)){
464                                                 fileList.add(file);
465                                         }
466                                 }
467                         }
468                         return fileList;
469         }
470
471     public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
472                 Properties prop = new Properties();
473                 InputStream input = null;
474                 String value = null;
475                 try {
476                         input = new FileInputStream(fullPath);
477                         prop.load(input);
478                         value = (prop.getProperty(key));
479
480                 } catch (IOException ex) {
481                         ex.printStackTrace();
482                 } finally {
483                         if (input != null) {
484                                 try {
485                                         input.close();
486                                 } catch (IOException e) {
487                                         e.printStackTrace();
488                                 }
489                         }
490                 }
491
492                 return value.replaceAll("\"","");
493         }
494
495     public static void overWriteExistindDir(String outputCsar) throws IOException {
496                 String basePath = getBasePath();
497                 String csarDir = FileHandling.getCreateDirByName("target/outputCsar");
498                 FileUtils.cleanDirectory(new File(csarDir));
499     }
500 }