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.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.net.InetAddress;
35 import java.net.UnknownHostException;
36 import java.util.ArrayList;
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 java.util.zip.ZipInputStream;
47 import org.apache.commons.io.FileUtils;
48 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
49 import org.onap.sdc.ci.tests.execute.setup.ExtentTestActions;
50 import org.onap.sdc.ci.tests.execute.setup.SetupCDTest;
51 import org.yaml.snakeyaml.Yaml;
53 import com.aventstack.extentreports.Status;
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 File getConfigFile(String configFileName) throws Exception {
140 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
141 if (!configFile.exists()) {
142 configFile = new File(FileHandling.getConfFilesPath() + configFileName);
147 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
149 File dir = new File(filepath);
150 List<String> filenames = new ArrayList<String>();
152 FilenameFilter extensionFilter = new FilenameFilter() {
153 public boolean accept(File dir, String name) {
154 return name.endsWith(extension);
158 if (dir.isDirectory()) {
159 for (File file : dir.listFiles(extensionFilter)) {
160 filenames.add(file.getName());
162 return filenames.toArray();
165 } catch (Exception e) {
171 public static String[] getArtifactsFromZip(String filepath, String zipFilename){
173 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
174 Enumeration<? extends ZipEntry> entries = zipFile.entries();
176 String[] artifactNames = new String[zipFile.size() - 1];
179 while(entries.hasMoreElements()){
180 ZipEntry nextElement = entries.nextElement();
181 if (!nextElement.isDirectory()){
182 if (!nextElement.getName().equals("MANIFEST.json")){
183 String name = nextElement.getName();
184 artifactNames[i++] = name;
189 return artifactNames;
191 catch(ZipException zipEx){
192 System.err.println("Error in zip file named : " + zipFilename);
193 zipEx.printStackTrace();
194 } catch (IOException e) {
195 System.err.println("Unhandled exception : ");
203 public static Object[] getZipFileNamesFromFolder(String filepath) {
204 return filterFileNamesFromFolder(filepath, ".zip");
207 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
209 for (String artifact : artifactsArr){
210 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
211 if (extensionFile.equals(reqExtension)){
219 public static synchronized File getLastModifiedFileFromDir() throws Exception{
220 return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
223 public static synchronized File getLastModifiedFileFromDir(String dirPath){
224 File dir = new File(dirPath);
225 File[] files = dir.listFiles();
227 assertTrue("File not found under directory " + dirPath, false);
231 File lastModifiedFile = files[0];
232 for (int i = 1; i < files.length; i++) {
233 if(files[i].isDirectory()) {
236 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
237 lastModifiedFile = files[i];
240 return lastModifiedFile;
243 public static void deleteDirectory(String directoryPath) {
244 File dir = new File(directoryPath);
246 FileUtils.deleteDirectory(dir);
247 } catch (IOException e) {
248 System.out.println("Failed to delete " + dir);
249 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir);
253 public static void createDirectory(String directoryPath) {
254 File directory = new File(String.valueOf(directoryPath));
255 if (! directory.exists()){
262 * The method append data to existing file, if file not exists - create it
265 * @param leftSpaceCount
266 * @throws IOException
268 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
270 BufferedWriter bw = null;
271 FileWriter fw = null;
272 if(!pathToFile.exists()){
273 createEmptyFile(pathToFile);
276 fw = new FileWriter(pathToFile, true);
277 bw = new BufferedWriter(fw);
278 StringBuilder sb = new StringBuilder();
279 if(leftSpaceCount > 0 ){
280 for(int i = 0; i < leftSpaceCount; i++){
284 bw.write(sb.toString() + text);
288 } catch (Exception e) {
289 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
294 public static void cleanCurrentDownloadDir() throws IOException {
296 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
298 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
305 public static boolean isFileDownloaded(String downloadPath, String fileName) {
306 boolean flag = false;
307 File dir = new File(downloadPath);
308 File[] dir_contents = dir.listFiles();
309 for (int i = 0; i < dir_contents.length; i++) {
310 if (dir_contents[i].getName().equals(fileName))
316 public static String getMD5OfFile(File file) throws IOException {
317 String content = FileUtils.readFileToString(file);
318 String md5 = GeneralUtility.calculateMD5ByString(content);
322 public static File createEmptyFile(String fileToCreate) {
323 File file= new File(fileToCreate);
328 file.createNewFile();
329 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
330 } catch (IOException e) {
331 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
337 public static File createEmptyFile(File fileToCreate) {
339 if(fileToCreate.exists()){
340 deleteFile(fileToCreate);
342 fileToCreate.createNewFile();
343 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
344 } catch (IOException e) {
345 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
351 public static void deleteFile(File file){
356 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
358 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
368 * get file list from directory by extension array
370 * @param okFileExtensions
373 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
375 List<File> fileList = new ArrayList<>();
376 File[] files = directory.listFiles();
378 for (String extension : okFileExtensions){
379 for(File file : files){
380 if (file.getName().toLowerCase().endsWith(extension)){
388 private static final int BUFFER_SIZE = 4096;
389 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
390 File destDir = new File(destDirectory);
391 if (!destDir.exists()) {
394 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
395 ZipEntry entry = zipIn.getNextEntry();
396 // iterates over entries in the zip file
397 while (entry != null) {
399 if(System.getProperty("os.name").contains("Windows")){
400 entryName = entry.getName().replaceAll("/", "\\"+File.separator);
402 entryName = entry.getName();
404 String filePath = destDirectory + entryName;
405 String currPath = destDirectory;
406 String[] dirs = entryName.split("\\"+File.separator);
408 for(int i = 0; i<dirs.length;++i){
410 if(!entry.isDirectory() && i==dirs.length-1){
411 extractFile(zipIn, filePath);
413 if(currPath.endsWith(File.separator)){
414 currPath = currPath + currToken;
416 currPath = currPath + File.separator + currToken;
418 // if the entry is a directory, make the directory
419 File dir = new File(currPath);
424 entry = zipIn.getNextEntry();
429 private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
430 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
431 byte[] bytesIn = new byte[BUFFER_SIZE];
433 while ((read = zipIn.read(bytesIn)) != -1) {
434 bos.write(bytesIn, 0, read);
439 public static int getFileCountFromDefaulDownloadDirectory(){
440 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
444 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
445 Properties prop = new Properties();
446 InputStream input = null;
449 input = new FileInputStream(fullPath);
451 value = (prop.getProperty(key));
453 } catch (IOException ex) {
454 ex.printStackTrace();
459 } catch (IOException e) {
465 return value.replaceAll("\"","");
468 public static String getExecutionHostAddress() {
470 String computerName = null;
472 computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·");
473 System.out.println(computerName);
474 if (computerName.indexOf(".") > -1)
475 computerName = computerName.substring(0,
476 computerName.indexOf(".")).toUpperCase();
477 } catch (UnknownHostException e) {
478 System.out.println("Uknown hostAddress");
480 return computerName != null ? computerName : "Uknown hostAddress";
483 public static Map<?, ?> loadCredentialsFile(String path, String filename) throws Exception {
484 File credentialsFileRemote = new File(path + filename);
485 Map<?, ?> yamlFile = FileHandling.parseYamlFile(credentialsFileRemote.getAbsolutePath());