2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.ci.tests.utilities;
23 import static org.testng.AssertJUnit.assertTrue;
25 import java.io.BufferedOutputStream;
26 import java.io.BufferedWriter;
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.nio.file.Paths;
35 import java.util.ArrayList;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.Properties;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipException;
43 import java.util.zip.ZipFile;
44 import java.util.zip.ZipInputStream;
46 import org.apache.commons.io.FileUtils;
47 import org.openecomp.sdc.be.model.DataTypeDefinition;
48 import org.openecomp.sdc.ci.tests.config.Config;
49 import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions;
50 import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
51 import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils;
52 import org.openecomp.sdc.common.util.GeneralUtility;
53 import org.yaml.snakeyaml.Yaml;
55 import com.aventstack.extentreports.Status;
56 import com.clearspring.analytics.util.Pair;
58 public class FileHandling {
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);
71 * The method return map fetched objects by pattern from yaml file
77 public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
78 Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
79 Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
83 @SuppressWarnings("unchecked")
84 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
85 Map<String, Object> objectMap = null;
87 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
88 if(objectUpdetedEnvFile instanceof HashMap){
89 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
95 public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
96 @SuppressWarnings("unchecked")
97 Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
100 // -------------------------------------------------------------------------------------------------
104 * @param folder, folder name under "Files" folder
105 * @return path to given folder from perspective of working directory or sdc-vnfs repository
107 public static String getFilePath(String folder) {
108 String filepath = System.getProperty("filePath");
109 boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty());
111 // return folder from perspective of sdc-vnfs repository
112 if (isFilePathEmptyOrNull && ( System.getProperty("os.name").contains("Windows") || System.getProperty("os.name").contains("Mac"))) {
113 return FileHandling.getResourcesFilesPath() + folder + File.separator;
116 // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory )
117 return FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator;
120 public static String getBasePath() {
121 return System.getProperty("user.dir") + File.separator;
124 public static String getSdcVnfsPath() {
125 return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
128 public static String getDriversPath() {
129 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
130 + File.separator + "ci" + File.separator + "drivers" + File.separator;
133 public static String getResourcesFilesPath() {
134 // return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
135 // + File.separator + "Files" + File.separator;
137 return getSdcVnfsPath()+ File.separator + "ui-tests" + File.separator + "Files" + File.separator;
140 public static String getResourcesEnvFilesPath() {
141 return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources"
142 + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator;
145 public static String getCiFilesPath() {
146 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
147 + File.separator + "ci";
150 public static String getConfFilesPath() {
151 return getCiFilesPath() + File.separator + "conf" + File.separator;
154 public static String getTestSuitesFilesPath() {
155 return getCiFilesPath() + File.separator + "testSuites" + File.separator;
158 public static String getVnfRepositoryPath() {
159 return getFilePath("VNFs");
162 public static String getUpdateVSPVnfRepositoryPath() {
163 return getFilePath("UpdateVSP");
166 public static File getConfigFile(String configFileName) throws Exception {
167 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
168 if (!configFile.exists()) {
169 configFile = new File(FileHandling.getConfFilesPath() + configFileName);
174 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
176 File dir = new File(filepath);
177 List<String> filenames = new ArrayList<String>();
179 FilenameFilter extensionFilter = new FilenameFilter() {
180 public boolean accept(File dir, String name) {
181 return name.endsWith(extension);
185 if (dir.isDirectory()) {
186 for (File file : dir.listFiles(extensionFilter)) {
187 filenames.add(file.getName());
189 return filenames.toArray();
192 } catch (Exception e) {
198 public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
200 File dir = new File(filepath);
201 List<String> filenames = new ArrayList<String>();
203 FilenameFilter extensionFilter = new FilenameFilter() {
204 public boolean accept(File dir, String name) {
205 return name.endsWith(extension);
209 if (dir.isDirectory()) {
210 for (File file : dir.listFiles(extensionFilter)) {
211 filenames.add(file.getName());
214 filenames.removeAll(OnboardingUtils.exludeVnfList);
219 } catch (Exception e) {
225 public static String[] getArtifactsFromZip(String filepath, String zipFilename){
227 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
228 Enumeration<? extends ZipEntry> entries = zipFile.entries();
230 List<String> artifactNames = new ArrayList<String>();
232 while(entries.hasMoreElements()){
233 ZipEntry nextElement = entries.nextElement();
234 if (!nextElement.isDirectory()){
235 if (!nextElement.getName().equals("MANIFEST.json")){
236 String name = nextElement.getName();
237 artifactNames.add(name);
242 // convert list to array
243 return artifactNames.toArray(new String[0]);
245 catch(ZipException zipEx){
246 System.err.println("Error in zip file named : " + zipFilename);
247 zipEx.printStackTrace();
248 } catch (IOException e) {
249 System.err.println("Unhandled exception : ");
257 // public static Object[] getZipFileNamesFromFolder(String filePath) {
258 // return filterFileNamesFromFolder(filePath, ".zip");
261 public static List<String> getZipFileNamesFromFolder(String filepath) {
262 return filterFileNamesListFromFolder(filepath, ".zip");
265 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
267 for (String artifact : artifactsArr){
268 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
269 if (extensionFile.equals(reqExtension)){
278 * @return last modified file name from default directory
281 public static synchronized File getLastModifiedFileNameFromDir() throws Exception{
282 return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
287 * @return last modified file name from dirPath directory
289 public static synchronized File getLastModifiedFileNameFromDir(String dirPath){
290 File dir = new File(dirPath);
291 File[] files = dir.listFiles();
293 assertTrue("File not found under directory " + dirPath, false);
297 File lastModifiedFile = files[0];
298 for (int i = 1; i < files.length; i++) {
299 if(files[i].isDirectory()) {
302 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
303 lastModifiedFile = files[i];
306 return lastModifiedFile;
309 public static void deleteDirectory(String directoryPath) {
310 File dir = new File(directoryPath);
312 FileUtils.cleanDirectory(dir);
313 } catch (IOException e) {
314 System.out.println("Failed to delete " + dir);
315 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir);
319 public static void createDirectory(String directoryPath) {
320 File directory = new File(String.valueOf(directoryPath));
321 if (! directory.exists()){
328 * The method append data to existing file, if file not exists - create it
331 * @param leftSpaceCount
332 * @throws IOException
334 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
336 BufferedWriter bw = null;
337 FileWriter fw = null;
338 if(!pathToFile.exists()){
339 createEmptyFile(pathToFile);
342 fw = new FileWriter(pathToFile, true);
343 bw = new BufferedWriter(fw);
344 StringBuilder sb = new StringBuilder();
345 if(leftSpaceCount > 0 ){
346 for(int i = 0; i < leftSpaceCount; i++){
350 bw.write(sb.toString() + text);
354 } catch (Exception e) {
355 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
359 public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException{
361 BufferedWriter bw = null;
362 FileWriter fw = null;
364 if(!pathToFile.exists()){
365 createEmptyFile(pathToFile);
367 fw = new FileWriter(pathToFile, true);
368 bw = new BufferedWriter(fw);
369 StringBuilder sb = new StringBuilder();
370 if(leftSpaceCount > 0 ){
371 for(int i = 0; i < leftSpaceCount; i++){
375 for(Map.Entry<String, Pair<String, Object>> entry : dataMap.entrySet()){
376 Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right);
377 bw.write(sb.toString() + record);
382 } catch (Exception e) {
383 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
387 public static void deleteLastDowloadedFiles(List<File> files) throws IOException {
388 for (File file : files) {
389 File fileToDelete =new File(Config.instance().getWindowsDownloadDirectory()+file.getName());
390 fileToDelete.delete();
394 public static void cleanCurrentDownloadDir() throws IOException {
396 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
398 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
405 public static boolean isFileDownloaded(String downloadPath, String fileName) {
406 boolean flag = false;
407 File dir = new File(downloadPath);
408 File[] dir_contents = dir.listFiles();
409 for (int i = 0; i < dir_contents.length; i++) {
410 if (dir_contents[i].getName().equals(fileName))
416 public static String getMD5OfFile(File file) throws IOException {
417 String content = FileUtils.readFileToString(file);
418 String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
422 public static File createEmptyFile(String fileToCreate) {
423 File file= new File(fileToCreate);
428 file.createNewFile();
429 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
430 } catch (IOException e) {
431 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
437 public static File createEmptyFile(File fileToCreate) {
439 if(fileToCreate.exists()){
440 deleteFile(fileToCreate);
442 fileToCreate.createNewFile();
443 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
444 } catch (IOException e) {
445 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
451 public static void deleteFile(File file){
456 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
458 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
468 * get file list from directory by extension array
470 * @param okFileExtensions
473 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
475 List<File> fileList = new ArrayList<>();
476 File[] files = directory.listFiles();
478 for (String extension : okFileExtensions){
479 for(File file : files){
480 if (file.getName().toLowerCase().endsWith(extension)){
488 private static final int BUFFER_SIZE = 4096;
489 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
490 File destDir = new File(destDirectory);
491 if (!destDir.exists()) {
494 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
495 ZipEntry entry = zipIn.getNextEntry();
496 // iterates over entries in the zip file
497 while (entry != null) {
499 if(System.getProperty("os.name").contains("Windows")){
500 entryName = entry.getName().replaceAll("/", "\\"+File.separator);
502 entryName = entry.getName();
504 String filePath = destDirectory + entryName;
505 String currPath = destDirectory;
506 String[] dirs = entryName.split("\\"+File.separator);
508 for(int i = 0; i<dirs.length;++i){
510 if(!entry.isDirectory() && i==dirs.length-1){
511 extractFile(zipIn, filePath);
513 if(currPath.endsWith(File.separator)){
514 currPath = currPath + currToken;
516 currPath = currPath + File.separator + currToken;
518 // if the entry is a directory, make the directory
519 File dir = new File(currPath);
524 entry = zipIn.getNextEntry();
529 private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
530 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
531 byte[] bytesIn = new byte[BUFFER_SIZE];
533 while ((read = zipIn.read(bytesIn)) != -1) {
534 bos.write(bytesIn, 0, read);
539 public static int getFileCountFromDefaulDownloadDirectory(){
540 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
544 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
545 Properties prop = new Properties();
546 InputStream input = null;
549 input = new FileInputStream(fullPath);
551 value = (prop.getProperty(key));
553 } catch (IOException ex) {
554 ex.printStackTrace();
559 } catch (IOException e) {
565 return value.replaceAll("\"","");