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.onap.sdc.frontend.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.onap.sdc.backend.ci.tests.config.Config;
27 import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils;
28 import org.openecomp.sdc.be.model.DataTypeDefinition;
29 import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions;
30 import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
31 import org.openecomp.sdc.common.util.GeneralUtility;
32 import org.yaml.snakeyaml.Yaml;
34 import java.io.BufferedOutputStream;
35 import java.io.BufferedWriter;
37 import java.io.FileInputStream;
38 import java.io.FileOutputStream;
39 import java.io.FileWriter;
40 import java.io.FilenameFilter;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.nio.file.Paths;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Enumeration;
47 import java.util.HashMap;
48 import java.util.List;
50 import java.util.Properties;
51 import java.util.zip.ZipEntry;
52 import java.util.zip.ZipException;
53 import java.util.zip.ZipFile;
54 import java.util.zip.ZipInputStream;
56 import static org.testng.AssertJUnit.assertTrue;
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
78 public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
79 Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
80 Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
84 @SuppressWarnings("unchecked")
85 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
86 Map<String, Object> objectMap = null;
88 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
89 if (objectUpdetedEnvFile instanceof HashMap) {
90 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
96 public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
97 @SuppressWarnings("unchecked")
98 Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
101 // -------------------------------------------------------------------------------------------------
105 * @param folder, folder name under "Files" folder
106 * @return path to given folder from perspective of working directory or sdc-vnfs repository
108 public static String getFilePath(String folder) {
109 String filepath = System.getProperty("filePath");
110 boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty());
112 // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory )
113 return FileHandling.getBasePath() + "src/test/resources/Files" + File.separator + folder + File.separator;
116 public static String getBasePath() {
117 return System.getProperty("user.dir") + File.separator;
120 public static String getSdcVnfsPath() {
121 String vnfsPath = System.getProperty("vnfs.path");
122 if (vnfsPath != null && !vnfsPath.isEmpty()) {
125 return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
128 public static String getResourcesFilesPath() {
129 return getSdcVnfsPath() + File.separator + "ui-tests" + File.separator + "Files" + File.separator;
132 public static String getCiFilesPath() {
133 return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
134 + File.separator + "ci";
137 public static String getConfFilesPath() {
138 return getCiFilesPath() + File.separator + "conf" + File.separator;
141 public static String getTestSuitesFilesPath() {
142 return getCiFilesPath() + File.separator + "testSuites" + File.separator;
145 public static String getVnfRepositoryPath() {
146 return getFilePath("VNFs");
149 public static String getUpdateVSPVnfRepositoryPath() {
150 return getFilePath("UpdateVSP");
153 public static File getConfigFile(String configFileName) throws Exception {
154 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
155 if (!configFile.exists()) {
156 configFile = new File(FileHandling.getConfFilesPath() + configFileName);
161 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
163 File dir = new File(filepath);
164 List<String> filenames = new ArrayList<String>();
166 FilenameFilter extensionFilter = new FilenameFilter() {
167 public boolean accept(File dir, String name) {
168 return name.endsWith(extension);
172 if (dir.isDirectory()) {
173 for (File file : dir.listFiles(extensionFilter)) {
174 filenames.add(file.getName());
176 return filenames.toArray();
179 } catch (Exception e) {
185 public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
187 File dir = new File(filepath);
188 List<String> filenames = new ArrayList<String>();
190 FilenameFilter extensionFilter = new FilenameFilter() {
191 public boolean accept(File dir, String name) {
192 return name.endsWith(extension);
196 if (dir.isDirectory()) {
197 for (File file : dir.listFiles(extensionFilter)) {
198 filenames.add(file.getName());
201 filenames.removeAll(OnboardingUtils.excludeXnfList);
206 } catch (Exception e) {
212 public static String[] getArtifactsFromZip(String filepath, String zipFilename) {
214 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
215 Enumeration<? extends ZipEntry> entries = zipFile.entries();
217 List<String> artifactNames = new ArrayList<String>();
219 while (entries.hasMoreElements()) {
220 ZipEntry nextElement = entries.nextElement();
221 if (!nextElement.isDirectory()) {
222 if (!nextElement.getName().equals("MANIFEST.json")) {
223 String name = nextElement.getName();
224 artifactNames.add(name);
229 // convert list to array
230 return artifactNames.toArray(new String[0]);
231 } catch (ZipException zipEx) {
232 System.err.println("Error in zip file named : " + zipFilename);
233 zipEx.printStackTrace();
234 } catch (IOException e) {
235 System.err.println("Unhandled exception : ");
243 public static List<String> getZipFileNamesFromFolder(String filepath) {
244 return filterFileNamesListFromFolder(filepath, ".zip");
247 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension) {
249 for (String artifact : artifactsArr) {
250 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1, artifact.length());
251 if (extensionFile.equals(reqExtension)) {
260 * @return last modified file name from default directory
263 public static synchronized File getLastModifiedFileNameFromDir() throws Exception {
264 return getLastModifiedFileNameFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
269 * @return last modified file name from dirPath directory
271 public static synchronized File getLastModifiedFileNameFromDir(String dirPath) {
272 File dir = new File(dirPath);
273 File[] files = dir.listFiles();
275 assertTrue("File not found under directory " + dirPath, false);
279 File lastModifiedFile = files[0];
280 for (int i = 1; i < files.length; i++) {
281 if (files[i].isDirectory()) {
284 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
285 lastModifiedFile = files[i];
288 return lastModifiedFile;
291 public static void deleteDirectory(String directoryPath) {
292 File dir = new File(directoryPath);
295 FileUtils.cleanDirectory(dir);
296 } catch (IllegalArgumentException e) {
297 System.out.println("Failed to clean " + dir);
298 } catch (IOException e) {
299 System.out.println("Failed to clean " + dir);
304 public static void createDirectory(String directoryPath) {
305 File directory = new File(String.valueOf(directoryPath));
306 if (!directory.exists()) {
313 * The method append data to existing file, if file not exists - create it
317 * @param leftSpaceCount
318 * @throws IOException
320 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException {
322 BufferedWriter bw = null;
323 FileWriter fw = null;
324 if (!pathToFile.exists()) {
325 createEmptyFile(pathToFile);
328 fw = new FileWriter(pathToFile, true);
329 bw = new BufferedWriter(fw);
330 StringBuilder sb = new StringBuilder();
331 if (leftSpaceCount > 0) {
332 for (int i = 0; i < leftSpaceCount; i++) {
336 bw.write(sb.toString() + text);
340 } catch (Exception e) {
341 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
345 public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException {
347 BufferedWriter bw = null;
348 FileWriter fw = null;
350 if (!pathToFile.exists()) {
351 createEmptyFile(pathToFile);
353 fw = new FileWriter(pathToFile, true);
354 bw = new BufferedWriter(fw);
355 StringBuilder sb = new StringBuilder();
356 if (leftSpaceCount > 0) {
357 for (int i = 0; i < leftSpaceCount; i++) {
361 for (Map.Entry<String, Pair<String, Object>> entry : dataMap.entrySet()) {
362 Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right);
363 bw.write(sb.toString() + record);
368 } catch (Exception e) {
369 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
373 public static void deleteLastDowloadedFiles(List<File> files) throws IOException {
374 for (File file : files) {
375 File fileToDelete = new File(Config.instance().getDownloadAutomationFolder() + file.getName());
376 fileToDelete.delete();
380 public static void cleanCurrentDownloadDir() throws IOException {
382 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
384 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
385 } catch (Exception e) {
390 public static boolean isFileDownloaded(String downloadPath, String fileName) {
391 File dir = new File(downloadPath);
392 File[] dir_contents = dir.listFiles();
393 return Arrays.stream(dir_contents).anyMatch(file -> file.getName().equals(fileName));
396 public static String getMD5OfFile(File file) throws IOException {
397 String content = FileUtils.readFileToString(file);
398 String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
402 public static File createEmptyFile(String fileToCreate) {
403 File file = new File(fileToCreate);
408 file.createNewFile();
409 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
410 } catch (IOException e) {
411 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
417 public static File createEmptyFile(File fileToCreate) {
419 if (fileToCreate.exists()) {
420 deleteFile(fileToCreate);
422 fileToCreate.createNewFile();
423 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
424 } catch (IOException e) {
425 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
431 public static void deleteFile(File file) {
436 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
438 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
440 } catch (Exception e) {
448 * get file list from directory by extension array
451 * @param okFileExtensions
454 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions) {
456 List<File> fileList = new ArrayList<>();
457 File[] files = directory.listFiles();
459 for (String extension : okFileExtensions) {
460 for (File file : files) {
461 if (file.getName().toLowerCase().endsWith(extension)) {
469 private static final int BUFFER_SIZE = 4096;
471 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
472 File destDir = new File(destDirectory);
473 if (!destDir.exists()) {
476 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
477 ZipEntry entry = zipIn.getNextEntry();
478 // iterates over entries in the zip file
479 while (entry != null) {
481 if (System.getProperty("os.name").contains("Windows")) {
482 entryName = entry.getName().replace("/", "\\" + File.separator);
484 entryName = entry.getName();
486 String filePath = destDirectory + entryName;
487 String currPath = destDirectory;
488 String[] dirs = entryName.split("\\" + File.separator);
490 for (int i = 0; i < dirs.length; ++i) {
492 if (!entry.isDirectory() && i == dirs.length - 1) {
493 extractFile(zipIn, filePath);
495 if (currPath.endsWith(File.separator)) {
496 currPath = currPath + currToken;
498 currPath = currPath + File.separator + currToken;
500 // if the entry is a directory, make the directory
501 File dir = new File(currPath);
506 entry = zipIn.getNextEntry();
511 private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
512 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
513 byte[] bytesIn = new byte[BUFFER_SIZE];
515 while ((read = zipIn.read(bytesIn)) != -1) {
516 bos.write(bytesIn, 0, read);
521 public static int getFileCountFromDefaulDownloadDirectory() {
522 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
526 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
527 Properties prop = new Properties();
528 InputStream input = null;
531 input = new FileInputStream(fullPath);
533 value = (prop.getProperty(key));
535 } catch (IOException ex) {
536 ex.printStackTrace();
541 } catch (IOException e) {
547 return value.replaceAll("\"", "");