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.execute.setup.ExtentTestActions;
49 import org.onap.sdc.ci.tests.execute.setup.SetupCDTest;
50 import org.yaml.snakeyaml.Yaml;
52 import com.aventstack.extentreports.Status;
54 public class FileHandling {
56 // ------------------yaml parser methods----------------------------
57 public static Map<?, ?> parseYamlFile(String filePath) throws Exception {
58 Yaml yaml = new Yaml();
59 File file = new File(filePath);
60 InputStream inputStream = new FileInputStream(file);
61 Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
66 * The method return map fetched objects by pattern from yaml file
72 public static Map<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception {
73 Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString());
74 Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern);
78 @SuppressWarnings("unchecked")
79 public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) {
80 Map<String, Object> objectMap = null;
82 Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern);
83 if(objectUpdetedEnvFile instanceof HashMap){
84 objectMap = (Map<String, Object>) objectUpdetedEnvFile;
89 // -------------------------------------------------------------------------------------------------
91 public static String getFilePath(String folder) {
92 String filepath = System.getProperty("filepath");
93 if (filepath == null && System.getProperty("os.name").contains("Windows")) {
94 filepath = FileHandling.getResourcesFilesPath() + folder + File.separator;
97 else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){
98 filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator;
101 System.out.println(filepath);
106 public static String getBasePath() {
107 return System.getProperty("user.dir") + File.separator;
110 public static String getDriversPath() {
111 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
112 + File.separator + "ci" + File.separator + "drivers" + File.separator;
115 public static String getResourcesFilesPath() {
116 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
117 + File.separator + "Files" + File.separator;
120 public static String getResourcesEnvFilesPath() {
121 return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources"
122 + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator;
125 public static String getCiFilesPath() {
126 return getBasePath() + "src" + File.separator + "main" + File.separator + "resources"
127 + File.separator + "ci";
130 public static String getConfFilesPath() {
131 return getCiFilesPath() + File.separator + "conf" + File.separator;
134 public static String getTestSuitesFilesPath() {
135 return getCiFilesPath() + File.separator + "testSuites" + File.separator;
138 public static File getConfigFile(String configFileName) throws Exception {
139 File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName);
140 if (!configFile.exists()) {
141 configFile = new File(FileHandling.getConfFilesPath() + configFileName);
146 public static Object[] filterFileNamesFromFolder(String filepath, String extension) {
148 File dir = new File(filepath);
149 List<String> filenames = new ArrayList<String>();
151 FilenameFilter extensionFilter = new FilenameFilter() {
152 public boolean accept(File dir, String name) {
153 return name.endsWith(extension);
157 if (dir.isDirectory()) {
158 for (File file : dir.listFiles(extensionFilter)) {
159 filenames.add(file.getName());
161 return filenames.toArray();
164 } catch (Exception e) {
170 public static String[] getArtifactsFromZip(String filepath, String zipFilename){
172 ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename);
173 Enumeration<? extends ZipEntry> entries = zipFile.entries();
175 String[] artifactNames = new String[zipFile.size() - 1];
178 while(entries.hasMoreElements()){
179 ZipEntry nextElement = entries.nextElement();
180 if (!nextElement.isDirectory()){
181 if (!nextElement.getName().equals("MANIFEST.json")){
182 String name = nextElement.getName();
183 artifactNames[i++] = name;
188 return artifactNames;
190 catch(ZipException zipEx){
191 System.err.println("Error in zip file named : " + zipFilename);
192 zipEx.printStackTrace();
193 } catch (IOException e) {
194 System.err.println("Unhandled exception : ");
202 public static Object[] getZipFileNamesFromFolder(String filepath) {
203 return filterFileNamesFromFolder(filepath, ".zip");
206 public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){
208 for (String artifact : artifactsArr){
209 String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length());
210 if (extensionFile.equals(reqExtension)){
218 public static synchronized File getLastModifiedFileFromDir() throws Exception{
219 return getLastModifiedFileFromDir(SetupCDTest.getWindowTest().getDownloadDirectory());
222 public static synchronized File getLastModifiedFileFromDir(String dirPath){
223 File dir = new File(dirPath);
224 File[] files = dir.listFiles();
226 assertTrue("File not found under directory " + dirPath, false);
230 File lastModifiedFile = files[0];
231 for (int i = 1; i < files.length; i++) {
232 if(files[i].isDirectory()) {
235 if (lastModifiedFile.lastModified() < files[i].lastModified()) {
236 lastModifiedFile = files[i];
239 return lastModifiedFile;
242 public static void deleteDirectory(String directoryPath) {
243 File dir = new File(directoryPath);
245 FileUtils.deleteDirectory(dir);
246 } catch (IOException e) {
247 System.out.println("Failed to delete " + dir);
248 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir);
252 public static void createDirectory(String directoryPath) {
253 File directory = new File(String.valueOf(directoryPath));
254 if (! directory.exists()){
261 * The method append data to existing file, if file not exists - create it
264 * @param leftSpaceCount
265 * @throws IOException
267 public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{
269 BufferedWriter bw = null;
270 FileWriter fw = null;
271 if(!pathToFile.exists()){
272 createEmptyFile(pathToFile);
275 fw = new FileWriter(pathToFile, true);
276 bw = new BufferedWriter(fw);
277 StringBuilder sb = new StringBuilder();
278 if(leftSpaceCount > 0 ){
279 for(int i = 0; i < leftSpaceCount; i++){
283 bw.write(sb.toString() + text);
287 } catch (Exception e) {
288 SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile);
293 public static void cleanCurrentDownloadDir() throws IOException {
295 ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory());
297 FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory()));
304 public static boolean isFileDownloaded(String downloadPath, String fileName) {
305 boolean flag = false;
306 File dir = new File(downloadPath);
307 File[] dir_contents = dir.listFiles();
308 for (int i = 0; i < dir_contents.length; i++) {
309 if (dir_contents[i].getName().equals(fileName))
315 public static String getMD5OfFile(File file) throws IOException {
316 String content = FileUtils.readFileToString(file);
317 String md5 = GeneralUtility.calculateMD5ByString(content);
321 public static File createEmptyFile(String fileToCreate) {
322 File file= new File(fileToCreate);
327 file.createNewFile();
328 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
329 } catch (IOException e) {
330 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
336 public static File createEmptyFile(File fileToCreate) {
338 if(fileToCreate.exists()){
339 deleteFile(fileToCreate);
341 fileToCreate.createNewFile();
342 SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate);
343 } catch (IOException e) {
344 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate);
350 public static void deleteFile(File file){
355 SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted");
357 SetupCDTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName());
367 * get file list from directory by extension array
369 * @param okFileExtensions
372 public static List<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){
374 List<File> fileList = new ArrayList<>();
375 File[] files = directory.listFiles();
377 for (String extension : okFileExtensions){
378 for(File file : files){
379 if (file.getName().toLowerCase().endsWith(extension)){
387 private static final int BUFFER_SIZE = 4096;
388 public static void unzip(String zipFilePath, String destDirectory) throws IOException {
389 File destDir = new File(destDirectory);
390 if (!destDir.exists()) {
393 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
394 ZipEntry entry = zipIn.getNextEntry();
395 // iterates over entries in the zip file
396 while (entry != null) {
398 if(System.getProperty("os.name").contains("Windows")){
399 entryName = entry.getName().replaceAll("/", "\\"+File.separator);
401 entryName = entry.getName();
403 String filePath = destDirectory + entryName;
404 String currPath = destDirectory;
405 String[] dirs = entryName.split("\\"+File.separator);
407 for(int i = 0; i<dirs.length;++i){
409 if(!entry.isDirectory() && i==dirs.length-1){
410 extractFile(zipIn, filePath);
412 if(currPath.endsWith(File.separator)){
413 currPath = currPath + currToken;
415 currPath = currPath + File.separator + currToken;
417 // if the entry is a directory, make the directory
418 File dir = new File(currPath);
423 entry = zipIn.getNextEntry();
428 private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
429 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
430 byte[] bytesIn = new byte[BUFFER_SIZE];
432 while ((read = zipIn.read(bytesIn)) != -1) {
433 bos.write(bytesIn, 0, read);
438 public static int getFileCountFromDefaulDownloadDirectory(){
439 return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length;
443 public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) {
444 Properties prop = new Properties();
445 InputStream input = null;
448 input = new FileInputStream(fullPath);
450 value = (prop.getProperty(key));
452 } catch (IOException ex) {
453 ex.printStackTrace();
458 } catch (IOException e) {
464 return value.replaceAll("\"","");
467 public static String getExecutionHostAddress() {
469 String computerName = null;
471 computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·");
472 System.out.println(computerName);
473 if (computerName.indexOf(".") > -1)
474 computerName = computerName.substring(0,
475 computerName.indexOf(".")).toUpperCase();
476 } catch (UnknownHostException e) {
477 System.out.println("Uknown hostAddress");
479 return computerName != null ? computerName : "Uknown hostAddress";
482 public static Map<?, ?> loadCredentialsFile(String path, String filename) throws Exception {
483 File credentialsFileRemote = new File(path + filename);
484 Map<?, ?> yamlFile = FileHandling.parseYamlFile(credentialsFileRemote.getAbsolutePath());