vid-automation selenium tests
[vid.git] / vid-automation / src / main / java / vid / automation / test / utils / ReadFile.java
1 package vid.automation.test.utils;
2
3 import com.fasterxml.jackson.databind.ObjectMapper;
4 import org.apache.commons.io.FilenameUtils;
5 import org.apache.commons.io.IOUtils;
6 import org.openecomp.sdc.ci.tests.utilities.FileHandling;
7 import vid.automation.test.infra.Input;
8
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.net.URL;
12 import java.nio.file.Path;
13 import java.nio.file.StandardCopyOption;
14
15 import static java.nio.file.Files.copy;
16 import static java.nio.file.Files.createTempDirectory;
17
18 public class ReadFile {
19
20     private static Path tempDirectory;
21
22     public static <T> T getJsonFile(String fileName, Class<T> clazz) {
23         ObjectMapper mapper = new ObjectMapper();
24         T list;
25         try {
26             java.io.File testCaseFile = FileHandling.getConfigFile(fileName);
27             if(!testCaseFile.exists()) {
28                 String basePath = System.getProperty("BASE_PATH");
29                 testCaseFile = new java.io.File( basePath + java.io.File.separator + "conf" + java.io.File.separator + fileName);
30             }
31             list = (T) mapper.readValue(testCaseFile, clazz);
32             return list;
33         } catch (Exception e) {
34             e.printStackTrace();
35             throw new RuntimeException("cannot read file '" + fileName + "' file as '" + clazz.getCanonicalName() + "'", e);
36         }
37     }
38
39     public static String copyOfFileFromResources(String pathInResources) {
40
41         // takes a file from resources, copies it to a temp folder, then
42         // returns the newly created path file
43
44         URL resource = Input.class.getClassLoader().getResource(pathInResources);
45         if (resource == null) {
46             throw new RuntimeException("file not found in resources: " + pathInResources);
47         }
48
49         Path target;
50         try {
51             tempDirectory = (tempDirectory != null) ? tempDirectory : createTempDirectory("resources-");
52             target = tempDirectory.resolve(FilenameUtils.getName(resource.getPath()));
53             copy(resource.openStream(), target, StandardCopyOption.REPLACE_EXISTING);
54         } catch (IOException e) {
55             throw new RuntimeException(e);
56         }
57
58         return target.toString();
59     }
60
61     public static String loadResourceAsString(String relativePath){
62         final InputStream resource = ReadFile.class.getClassLoader().getResourceAsStream(relativePath);
63         if (resource == null) throw new RuntimeException("template file not found: " + relativePath);
64         try {
65             return IOUtils.toString(resource, "UTF-8");
66         } catch (IOException e) {
67             throw new RuntimeException(e);
68         }
69     }
70 }