2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.sdc.backend.ci.tests.utils.general;
24 import static org.testng.AssertJUnit.assertTrue;
26 import com.aventstack.extentreports.Status;
27 import java.io.BufferedWriter;
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;
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;
52 public class FileHandling {
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);
64 * The method return map fetched objects by pattern from yaml file
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);
76 @SuppressWarnings("unchecked")
77 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
78 Map<String, Object> objectMap = null;
80 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
81 if(objectUpdetedEnvFile instanceof HashMap){
82 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
88 public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception {
89 @SuppressWarnings("unchecked")
90 Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath);
93 // -------------------------------------------------------------------------------------------------
96 * @param folder, folder name under "Files" folder
97 * @return path to given folder from perspective of working directory or sdc-vnfs repository
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;
104 public static String getBasePath() {
105 return System.getProperty("user.dir") + File.separator;
108 public static String getSdcVnfsPath() {
109 return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString();
112 public static String getDriversPath() {
113 return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
114 + File.separator + "ci" + File.separator + "drivers" + File.separator;
117 public static String getResourcesFilesPath() {
118 return getSdcVnfsPath()+ File.separator + "ui-tests" + File.separator + "Files" + File.separator;
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;
126 public static String getCiFilesPath() {
127 return getBasePath() + "src" + File.separator + "test" + File.separator + "resources"
128 + File.separator + "ci";
131 public static String getConfFilesPath() {
132 return getCiFilesPath() + File.separator + "conf" + File.separator;
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()
144 public static String getVnfRepositoryPath() {
145 return getFilePath("VNFs");
148 private static String getPnfRepositoryPath() {
149 return getFilePath("PNFs");
152 private static String getCnfRepositoryPath() {
153 return getFilePath("CNFs");
156 private static String getCnfRepositoryForHelmValidatorPath() {
157 return getFilePath("CNFs/helm_validator");
160 private static String getEtsiRepositoryPath() { return getFilePath("ETSI"); }
162 private static String getVfcRepositoryPath() { return getFilePath("VFCs"); }
164 public static String getPackageRepositoryPath(PackageTypeEnum packageTypeEnum) {
165 return PACKAGE_REPOSITORY_PATHS_MAP.get(packageTypeEnum);
168 public static String getPortMirroringRepositoryPath() {
169 return getFilePath("PortMirroring");
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);
180 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
182 File dir = new File(filepath);
183 List<String> filenames = new ArrayList<String>();
185 FilenameFilter extensionFilter = new FilenameFilter() {
186 public boolean accept(File dir, String name) {
187 return name.endsWith(extension);
191 if (dir.isDirectory()) {
192 for (File file : dir.listFiles(extensionFilter)) {
193 filenames.add(file.getName());
195 return filenames.toArray();
198 } catch (Exception e) {
204 public static List<String> filterFileNamesListFromFolder(String filepath, String extension) {
205 List<String> filenames = new ArrayList<String>();
207 File dir = new File(filepath);
209 FilenameFilter extensionFilter = new FilenameFilter() {
210 public boolean accept(File dir, String name) {
211 return name.endsWith(extension);
215 if (dir.isDirectory()) {
216 for (File file : dir.listFiles(extensionFilter)) {
217 filenames.add(file.getName());
222 } catch (Exception e) {
228 public static String[] getArtifactsFromZip(String filepath, String zipFilename){
230 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
231 Enumeration<? extends ZipEntry> entries = zipFile.entries();
233 String[] artifactNames = new String[zipFile.size() - 1];
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;
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 : ");
259 public static List<String> getFileNamesFromZip(String zipFileLocation){
261 ZipFile zipFile = new ZipFile(zipFileLocation);
262 Enumeration<? extends ZipEntry> entries = zipFile.entries();
264 List<String> artifactNames = new ArrayList<>();
267 while(entries.hasMoreElements()){
268 ZipEntry nextElement = entries.nextElement();
269 if (!nextElement.isDirectory()){
270 String name = nextElement.getName();
271 artifactNames.add(name);
275 return artifactNames;
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 : ");
287 public static List<String> getZipFileNamesFromFolder(String filepath) {
288 List<String> fileNamesListFromFolder = filterFileNamesListFromFolder(filepath, ".zip");
289 fileNamesListFromFolder.addAll(filterFileNamesListFromFolder(filepath, ".csar"));
290 return fileNamesListFromFolder;
293 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
295 for (String artifact : artifactsArr){
296 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
297 if (extensionFile.equals(reqExtension)){
306 * @return last modified file name from dirPath directory
308 public static synchronized File getLastModifiedFileNameFromDir(String dirPath){
309 File dir = new File(dirPath);
310 File[] files = dir.listFiles();
312 assertTrue("File not found under directory " + dirPath, false);
316 File lastModifiedFile = files[0];
317 for (int i = 1; i < files.length; i++) {
318 if(files[i].isDirectory()) {
321 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
322 lastModifiedFile = files[i];
325 return lastModifiedFile;
328 public static void deleteDirectory(String directoryPath) {
329 File dir = new File(directoryPath);
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);
339 public static void createDirectory(String directoryPath) {
340 File directory = new File(String.valueOf(directoryPath));
341 if (! directory.exists()){
348 * The method append data to existing file, if file not exists - create it
351 * @param leftSpaceCount
352 * @throws IOException
354 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
356 BufferedWriter bw = null;
357 FileWriter fw = null;
358 if(!pathToFile.exists()){
359 createEmptyFile(pathToFile);
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++){
370 bw.write(sb.toString() + text);
374 } catch (Exception e) {
375 ComponentBaseTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
379 public static String getCreateDirByName(String dirName) {
380 File dir = new File(dirName);
385 return dir.getPath();
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))
399 public static String getMD5OfFile(File file) throws IOException {
400 String content = FileUtils.readFileToString(file);
401 String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content);
405 public static File createEmptyFile(String fileToCreate) {
406 File file= new File(fileToCreate);
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);
420 public static File createEmptyFile(File fileToCreate) {
422 if(fileToCreate.exists()){
423 deleteFile(fileToCreate);
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);
434 public static void deleteFile(File file){
439 ComponentBaseTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
441 ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
451 * get file list from directory by extension array
453 * @param okFileExtensions
456 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
458 List<File> fileList = new ArrayList<>();
459 File[] files = directory.listFiles();
461 for (String extension : okFileExtensions){
462 for(File file : files){
463 if (file.getName().toLowerCase().endsWith(extension)){
471 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
472 Properties prop = new Properties();
473 InputStream input = null;
476 input = new FileInputStream(fullPath);
478 value = (prop.getProperty(key));
480 } catch (IOException ex) {
481 ex.printStackTrace();
486 } catch (IOException e) {
492 return value.replaceAll("\"","");
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));