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 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;
35 import java.nio.file.Paths;
37 import java.util.zip.ZipEntry;
38 import java.util.zip.ZipException;
39 import java.util.zip.ZipFile;
40 import java.util.zip.ZipInputStream;
42 import static org.testng.AssertJUnit.assertTrue;
44 public class FileHandling {
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);
57 * The method return map fetched objects by pattern from yaml file
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);
70 @SuppressWarnings("unchecked")
71 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
72 Map<String, Object> objectMap = null;
74 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
75 if (objectUpdetedEnvFile instanceof HashMap) {
76 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
82 public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
83 @SuppressWarnings("unchecked")
84 Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
87 // -------------------------------------------------------------------------------------------------
91 * @param folder, folder name under "Files" folder
92 * @return path to given folder from perspective of working directory or sdc-vnfs repository
94 public static String getFilePath(String folder) {
95 String filepath = System.getProperty("filePath");
96 boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty());
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;
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;
107 public static String getBasePath() {
108 return System.getProperty("user.dir") + File.separator;
111 public static String getSdcVnfsPath() {
112 String vnfsPath = System.getProperty("vnfs.path");
113 if (vnfsPath != null && !vnfsPath.isEmpty()) {
116 return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
119 public static String getDriversPath() {
120 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
121 + File.separator + "ci" + File.separator + "drivers" + File.separator;
124 public static String getResourcesFilesPath() {
125 // return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
126 // + File.separator + "Files" + File.separator;
128 return getSdcVnfsPath() + File.separator + "ui-tests" + File.separator + "Files" + File.separator;
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;
136 public static String getCiFilesPath() {
137 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
138 + File.separator + "ci";
141 public static String getConfFilesPath() {
142 return getCiFilesPath() + File.separator + "conf" + File.separator;
145 public static String getTestSuitesFilesPath() {
146 return getCiFilesPath() + File.separator + "testSuites" + File.separator;
149 public static String getVnfRepositoryPath() {
150 return getFilePath("VNFs");
153 public static String getUpdateVSPVnfRepositoryPath() {
154 return getFilePath("UpdateVSP");
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);
165 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
167 File dir = new File(filepath);
168 List<String> filenames = new ArrayList<String>();
170 FilenameFilter extensionFilter = new FilenameFilter() {
171 public boolean accept(File dir, String name) {
172 return name.endsWith(extension);
176 if (dir.isDirectory()) {
177 for (File file : dir.listFiles(extensionFilter)) {
178 filenames.add(file.getName());
180 return filenames.toArray();
183 } catch (Exception e) {
189 public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
191 File dir = new File(filepath);
192 List<String> filenames = new ArrayList<String>();
194 FilenameFilter extensionFilter = new FilenameFilter() {
195 public boolean accept(File dir, String name) {
196 return name.endsWith(extension);
200 if (dir.isDirectory()) {
201 for (File file : dir.listFiles(extensionFilter)) {
202 filenames.add(file.getName());
205 filenames.removeAll(OnboardingUtils.exludeVnfList);
210 } catch (Exception e) {
216 public static String[] getArtifactsFromZip(String filepath, String zipFilename) {
218 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
219 Enumeration<? extends ZipEntry> entries = zipFile.entries();
221 List<String> artifactNames = new ArrayList<String>();
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);
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 : ");
247 // public static Object[] getZipFileNamesFromFolder(String filePath) {
248 // return filterFileNamesFromFolder(filePath, ".zip");
251 public static List<String> getZipFileNamesFromFolder(String filepath) {
252 return filterFileNamesListFromFolder(filepath, ".zip");
255 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension) {
257 for (String artifact : artifactsArr) {
258 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1, artifact.length());
259 if (extensionFile.equals(reqExtension)) {
268 * @return last modified file name from default directory
271 public static synchronized File getLastModifiedFileNameFromDir() throws Exception {
272 return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
277 * @return last modified file name from dirPath directory
279 public static synchronized File getLastModifiedFileNameFromDir(String dirPath) {
280 File dir = new File(dirPath);
281 File[] files = dir.listFiles();
283 assertTrue("File not found under directory " + dirPath, false);
287 File lastModifiedFile = files[0];
288 for (int i = 1; i < files.length; i++) {
289 if (files[i].isDirectory()) {
292 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
293 lastModifiedFile = files[i];
296 return lastModifiedFile;
299 public static void deleteDirectory(String directoryPath) {
300 File dir = new File(directoryPath);
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);
312 public static void createDirectory(String directoryPath) {
313 File directory = new File(String.valueOf(directoryPath));
314 if (!directory.exists()) {
321 * The method append data to existing file, if file not exists - create it
325 * @param leftSpaceCount
326 * @throws IOException
328 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException {
330 BufferedWriter bw = null;
331 FileWriter fw = null;
332 if (!pathToFile.exists()) {
333 createEmptyFile(pathToFile);
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++) {
344 bw.write(sb.toString() + text);
348 } catch (Exception e) {
349 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
353 public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException {
355 BufferedWriter bw = null;
356 FileWriter fw = null;
358 if (!pathToFile.exists()) {
359 createEmptyFile(pathToFile);
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++) {
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);
376 } catch (Exception e) {
377 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
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();
388 public static void cleanCurrentDownloadDir() throws IOException {
390 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
392 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
393 } catch (Exception e) {
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))
409 public static String getMD5OfFile(File file) throws IOException {
410 String content = FileUtils.readFileToString(file);
411 String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
415 public static File createEmptyFile(String fileToCreate) {
416 File file = new File(fileToCreate);
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);
430 public static File createEmptyFile(File fileToCreate) {
432 if (fileToCreate.exists()) {
433 deleteFile(fileToCreate);
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);
444 public static void deleteFile(File file) {
449 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
451 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
453 } catch (Exception e) {
461 * get file list from directory by extension array
464 * @param okFileExtensions
467 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions) {
469 List<File> fileList = new ArrayList<>();
470 File[] files = directory.listFiles();
472 for (String extension : okFileExtensions) {
473 for (File file : files) {
474 if (file.getName().toLowerCase().endsWith(extension)) {
482 private static final int BUFFER_SIZE = 4096;
484 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
485 File destDir = new File(destDirectory);
486 if (!destDir.exists()) {
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) {
494 if (System.getProperty("os.name").contains("Windows")) {
495 entryName = entry.getName().replaceAll("/", "\\" + File.separator);
497 entryName = entry.getName();
499 String filePath = destDirectory + entryName;
500 String currPath = destDirectory;
501 String[] dirs = entryName.split("\\" + File.separator);
503 for (int i = 0; i < dirs.length; ++i) {
505 if (!entry.isDirectory() && i == dirs.length - 1) {
506 extractFile(zipIn, filePath);
508 if (currPath.endsWith(File.separator)) {
509 currPath = currPath + currToken;
511 currPath = currPath + File.separator + currToken;
513 // if the entry is a directory, make the directory
514 File dir = new File(currPath);
519 entry = zipIn.getNextEntry();
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];
528 while ((read = zipIn.read(bytesIn)) != -1) {
529 bos.write(bytesIn, 0, read);
534 public static int getFileCountFromDefaulDownloadDirectory() {
535 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
539 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
540 Properties prop = new Properties();
541 InputStream input = null;
544 input = new FileInputStream(fullPath);
546 value = (prop.getProperty(key));
548 } catch (IOException ex) {
549 ex.printStackTrace();
554 } catch (IOException e) {
560 return value.replaceAll("\"", "");