1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.rat.test.utils;
20
21 import java.io.BufferedReader;
22 import java.io.File;
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.Reader;
28 import java.net.URISyntaxException;
29 import java.net.URL;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Paths;
33 import java.util.Objects;
34
35
36
37
38 public class Resources {
39
40
41
42 private Resources() {
43
44 }
45
46 public static final String SRC_TEST_RESOURCES = "src/test/resources";
47 public static final String SRC_MAIN_RESOURCES = "src/main/resources";
48 private static final File TEST_RESOURCE_BASE_PATH = new File(SRC_TEST_RESOURCES);
49 private static final File RESOURCE_BASE_PATH = new File(SRC_MAIN_RESOURCES);
50
51
52
53
54 public static File getResourceFile(String pResource) throws IOException {
55 File f = getResourceFromBase(TEST_RESOURCE_BASE_PATH, pResource);
56 if (!f.isFile()) {
57 throw new FileNotFoundException("Unable to locate resource file: " + pResource);
58 }
59 return f;
60 }
61
62
63
64
65 public static File getResourceDirectory(String pResource) throws IOException {
66 File f = getResourceFromBase(TEST_RESOURCE_BASE_PATH, pResource);
67 if (!f.isDirectory()) {
68 throw new FileNotFoundException("Unable to locate resource directory: " + pResource);
69 }
70 return f;
71 }
72
73
74
75
76
77
78
79 public static File getExampleResource(String pResource) throws URISyntaxException {
80 URL url = Resources.class.getResource("/examples/" + pResource);
81 Objects.requireNonNull(url, "/examples/" + pResource + " not found");
82 return Paths.get(url.toURI()).toFile();
83 }
84
85
86
87
88
89 private static File getResourceFromBase(File baseDir, String pResource) throws IOException {
90 File f = new File(baseDir, pResource);
91 return f.getCanonicalFile();
92 }
93
94
95
96
97
98 public static File[] getResourceFiles(String pResource) throws IOException {
99 File f = new File(TEST_RESOURCE_BASE_PATH, pResource).getCanonicalFile();
100 if (!f.isDirectory()) {
101 throw new FileNotFoundException("Unable to locate resource directory: " + pResource);
102 }
103
104 return f.listFiles(File::isFile);
105 }
106
107
108
109
110 public static InputStream getResourceStream(String pResource) throws IOException {
111 return Files.newInputStream(getResourceFile(pResource).toPath());
112 }
113
114
115
116
117 public static Reader getResourceReader(String pResource) throws IOException {
118 return new InputStreamReader(getResourceStream(pResource), StandardCharsets.UTF_8);
119 }
120
121
122
123
124
125 public static BufferedReader getBufferedReader(File file) throws IOException {
126 return new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8));
127 }
128 }