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.util.ArrayList;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.Properties;
40 import java.util.zip.ZipEntry;
41 import java.util.zip.ZipException;
42 import java.util.zip.ZipFile;
43 import java.util.zip.ZipInputStream;
45 import org.apache.commons.io.FileUtils;
46 import org.openecomp.sdc.ci.tests.config.Config;
47 import org.openecomp.sdc.ci.tests.execute.setup.ExtentTestActions;
48 import org.openecomp.sdc.ci.tests.execute.setup.SetupCDTest;
49 import org.openecomp.sdc.common.util.GeneralUtility;
50 import org.yaml.snakeyaml.Yaml;
52 import com.aventstack.extentreports.Status;
53 import com.clearspring.analytics.util.Pair;
55 public class FileHandling {
57 // ------------------yaml parser methods----------------------------
58 public static Map<?, ?> parseYamlFile(String filePath) throws Exception {
59 Yaml yaml = new Yaml();
60 File file = new File(filePath);
61 InputStream inputStream = new FileInputStream(file);
62 Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
67 * The method return map fetched objects by pattern from yaml file
73 public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
74 Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
75 Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
79 @SuppressWarnings("unchecked")
80 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
81 Map<String, Object> objectMap = null;
83 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
84 if(objectUpdetedEnvFile instanceof HashMap){
85 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
90 // -------------------------------------------------------------------------------------------------
92 public static String getFilePath(String folder) {
93 String filepath = System.getProperty("filepath");
94 if (filepath == null && System.getProperty("os.name").contains("Windows")) {
95 filepath = FileHandling.getResourcesFilesPath() + folder + File.separator;
98 else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
99 filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator;
102 System.out.println(filepath);
107 public static String getBasePath() {
108 return System.getProperty("user.dir") + File.separator;
111 public static String getDriversPath() {
112 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
113 + File.separator + "ci" + File.separator + "drivers" + File.separator;
116 public static String getResourcesFilesPath() {
117 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
118 + File.separator + "Files" + File.separator;
121 public static String getResourcesEnvFilesPath() {
122 return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources"
123 + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator;
126 public static String getCiFilesPath() {
127 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
128 + File.separator + "ci";
131 public static String getConfFilesPath() {
132 return getCiFilesPath() + File.separator + "conf" + File.separator;
135 public static String getTestSuitesFilesPath() {
136 return getCiFilesPath() + File.separator + "testSuites" + File.separator;
139 public static String getVnfRepositoryPath() {
140 return getFilePath("VNFs");
143 public static File getConfigFile(String configFileName) throws Exception {
144 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
145 if (!configFile.exists()) {
146 configFile = new File(FileHandling.getConfFilesPath() + configFileName);
151 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
153 File dir = new File(filepath);
154 List<String> filenames = new ArrayList<String>();
156 FilenameFilter extensionFilter = new FilenameFilter() {
157 public boolean accept(File dir, String name) {
158 return name.endsWith(extension);
162 if (dir.isDirectory()) {
163 for (File file : dir.listFiles(extensionFilter)) {
164 filenames.add(file.getName());
166 return filenames.toArray();
169 } catch (Exception e) {
175 public static String[] getArtifactsFromZip(String filepath, String zipFilename){
177 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
178 Enumeration<? extends ZipEntry> entries = zipFile.entries();
180 String[] artifactNames = new String[zipFile.size() - 1];
183 while(entries.hasMoreElements()){
184 ZipEntry nextElement = entries.nextElement();
185 if (!nextElement.isDirectory()){
186 if (!nextElement.getName().equals("MANIFEST.json")){
187 String name = nextElement.getName();
188 artifactNames[i++] = name;
193 return artifactNames;
195 catch(ZipException zipEx){
196 System.err.println("Error in zip file named : " + zipFilename);
197 zipEx.printStackTrace();
198 } catch (IOException e) {
199 System.err.println("Unhandled exception : ");
207 public static Object[] getZipFileNamesFromFolder(String filepath) {
208 return filterFileNamesFromFolder(filepath, ".zip");
211 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
213 for (String artifact : artifactsArr){
214 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
215 if (extensionFile.equals(reqExtension)){
223 public static synchronized File getLastModifiedFileFromDir() throws Exception{
224 return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
227 public static synchronized File getLastModifiedFileFromDir(String dirPath){
228 File dir = new File(dirPath);
229 File[] files = dir.listFiles();
231 assertTrue("File not found under directory " + dirPath, false);
235 File lastModifiedFile = files[0];
236 for (int i = 1; i < files.length; i++) {
237 if(files[i].isDirectory()) {
240 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
241 lastModifiedFile = files[i];
244 return lastModifiedFile;
247 public static void deleteDirectory(String directoryPath) {
248 File dir = new File(directoryPath);
250 FileUtils.deleteDirectory(dir);
251 } catch (IOException e) {
252 System.out.println("Failed to delete " + dir);
253 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir);
257 public static void createDirectory(String directoryPath) {
258 File directory = new File(String.valueOf(directoryPath));
259 if (! directory.exists()){
266 * The method append data to existing file, if file not exists - create it
269 * @param leftSpaceCount
270 * @throws IOException
272 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
274 BufferedWriter bw = null;
275 FileWriter fw = null;
276 if(!pathToFile.exists()){
277 createEmptyFile(pathToFile);
280 fw = new FileWriter(pathToFile, true);
281 bw = new BufferedWriter(fw);
282 StringBuilder sb = new StringBuilder();
283 if(leftSpaceCount > 0 ){
284 for(int i = 0; i < leftSpaceCount; i++){
288 bw.write(sb.toString() + text);
292 } catch (Exception e) {
293 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
297 public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> dataMap, Integer leftSpaceCount) throws IOException{
299 BufferedWriter bw = null;
300 FileWriter fw = null;
302 if(!pathToFile.exists()){
303 createEmptyFile(pathToFile);
305 fw = new FileWriter(pathToFile, true);
306 bw = new BufferedWriter(fw);
307 StringBuilder sb = new StringBuilder();
308 if(leftSpaceCount > 0 ){
309 for(int i = 0; i < leftSpaceCount; i++){
313 for(Map.Entry<String, Pair<String, Object>> entry : dataMap.entrySet()){
314 Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right);
315 bw.write(sb.toString() + record);
320 } catch (Exception e) {
321 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
325 public static void deleteLastDowloadedFiles(List<File> files) throws IOException {
326 for (File file : files) {
327 File fileToDelete =new File(Config.instance().getWindowsDownloadDirectory()+file.getName());
328 fileToDelete.delete();
332 public static void cleanCurrentDownloadDir() throws IOException {
334 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
336 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
343 public static boolean isFileDownloaded(String downloadPath, String fileName) {
344 boolean flag = false;
345 File dir = new File(downloadPath);
346 File[] dir_contents = dir.listFiles();
347 for (int i = 0; i < dir_contents.length; i++) {
348 if (dir_contents[i].getName().equals(fileName))
354 public static String getMD5OfFile(File file) throws IOException {
355 String content = FileUtils.readFileToString(file);
356 String md5 = GeneralUtility.calculateMD5ByString(content);
360 public static File createEmptyFile(String fileToCreate) {
361 File file= new File(fileToCreate);
366 file.createNewFile();
367 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
368 } catch (IOException e) {
369 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
375 public static File createEmptyFile(File fileToCreate) {
377 if(fileToCreate.exists()){
378 deleteFile(fileToCreate);
380 fileToCreate.createNewFile();
381 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
382 } catch (IOException e) {
383 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
389 public static void deleteFile(File file){
394 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
396 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
406 * get file list from directory by extension array
408 * @param okFileExtensions
411 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
413 List<File> fileList = new ArrayList<>();
414 File[] files = directory.listFiles();
416 for (String extension : okFileExtensions){
417 for(File file : files){
418 if (file.getName().toLowerCase().endsWith(extension)){
426 private static final int BUFFER_SIZE = 4096;
427 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
428 File destDir = new File(destDirectory);
429 if (!destDir.exists()) {
432 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
433 ZipEntry entry = zipIn.getNextEntry();
434 // iterates over entries in the zip file
435 while (entry != null) {
437 if(System.getProperty("os.name").contains("Windows")){
438 entryName = entry.getName().replaceAll("/", "\\"+File.separator);
440 entryName = entry.getName();
442 String filePath = destDirectory + entryName;
443 String currPath = destDirectory;
444 String[] dirs = entryName.split("\\"+File.separator);
446 for(int i = 0; i<dirs.length;++i){
448 if(!entry.isDirectory() && i==dirs.length-1){
449 extractFile(zipIn, filePath);
451 if(currPath.endsWith(File.separator)){
452 currPath = currPath + currToken;
454 currPath = currPath + File.separator + currToken;
456 // if the entry is a directory, make the directory
457 File dir = new File(currPath);
462 entry = zipIn.getNextEntry();
467 private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
468 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
469 byte[] bytesIn = new byte[BUFFER_SIZE];
471 while ((read = zipIn.read(bytesIn)) != -1) {
472 bos.write(bytesIn, 0, read);
477 public static int getFileCountFromDefaulDownloadDirectory(){
478 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
482 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
483 Properties prop = new Properties();
484 InputStream input = null;
487 input = new FileInputStream(fullPath);
489 value = (prop.getProperty(key));
491 } catch (IOException ex) {
492 ex.printStackTrace();
497 } catch (IOException e) {
503 return value.replaceAll("\"","");