1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.cms.util;
35
36 import info.magnolia.cms.core.SystemProperty;
37 import info.magnolia.init.MagnoliaInitPaths;
38 import info.magnolia.objectfactory.Components;
39
40 import java.io.File;
41 import java.io.FilenameFilter;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.UnsupportedEncodingException;
45 import java.net.URL;
46 import java.net.URLClassLoader;
47 import java.net.URLDecoder;
48 import java.util.Collection;
49 import java.util.Enumeration;
50 import java.util.HashSet;
51 import java.util.Set;
52 import java.util.jar.JarEntry;
53 import java.util.jar.JarFile;
54 import java.util.regex.Pattern;
55
56 import org.apache.commons.beanutils.BeanUtils;
57 import org.apache.commons.io.FileUtils;
58 import org.apache.commons.io.filefilter.TrueFileFilter;
59 import org.apache.commons.lang3.StringUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63
64
65
66 public class ClasspathResourcesUtil {
67 private static final Logger log = LoggerFactory.getLogger(ClasspathResourcesUtil.class);
68
69
70
71
72 public static interface Filter {
73 public boolean accept(String name);
74 }
75
76
77
78
79 public static class PatternFilter implements Filter {
80 private final Pattern pattern;
81
82 public PatternFilter(String pattern) {
83 this.pattern = Pattern.compile(pattern);
84 }
85
86 @Override
87 public boolean accept(String name) {
88 return pattern.matcher(name).matches();
89 }
90 }
91
92 private static boolean isCache() {
93 final String devMode = SystemProperty.getProperty("magnolia.develop");
94 return !"true".equalsIgnoreCase(devMode);
95 }
96
97
98
99
100
101
102 public static String[] findResources(String regex) {
103 return findResources(new PatternFilter(regex));
104 }
105
106
107
108
109
110
111 public static String[] findResources(Filter filter) {
112 final Set<String> resources = new HashSet<String>();
113 final ClassLoader cl = getCurrentClassLoader();
114
115
116
117 if (cl instanceof URLClassLoader) {
118 final URLClassLoader urlClassLoader = (URLClassLoader) cl;
119 final URL[] urls = urlClassLoader.getURLs();
120 log.debug("Loading resources from: {}", urls);
121 if (urls.length == 1 && urls[0].getPath().endsWith("WEB-INF/classes/")) {
122
123 log.warn("Looks like we're in a JBoss 5 expanded war directory, will attempt to load resources from the file system instead; see MAGNOLIA-2577.");
124 } else {
125 collectFromURLs(resources, urls, filter);
126 return resources.toArray(new String[resources.size()]);
127 }
128 }
129
130 try {
131
132
133
134
135
136 String classpath = BeanUtils.getProperty(cl, "classPath");
137
138 if (StringUtils.isNotEmpty(classpath)) {
139 collectFromClasspathString(resources, classpath, filter);
140 return resources.toArray(new String[resources.size()]);
141 }
142 } catch (Throwable e) {
143
144 }
145
146
147
148 collectFromFileSystem(filter, resources);
149 return resources.toArray(new String[resources.size()]);
150 }
151
152 protected static void collectFromURLs(Collection<String> resources, URL[] urls, Filter filter) {
153
154 for (int j = 0; j < urls.length; j++) {
155 final File tofile = sanitizeToFile(urls[j]);
156 if (tofile != null) {
157 collectFiles(resources, tofile, filter);
158 }
159 }
160 }
161
162 protected static void collectFromClasspathString(Collection<String> resources, String classpath, Filter filter) {
163 String[] paths = classpath.split(File.pathSeparator);
164 for (int j = 0; j < paths.length; j++) {
165 final File tofile = new File(paths[j]);
166
167 if (tofile.exists()) {
168 collectFiles(resources, tofile, filter);
169 }
170 }
171 }
172
173 protected static void collectFromFileSystem(Filter filter, Collection<String> resources) {
174
175 String rootDire = Components.getComponent(MagnoliaInitPaths.class).getRootPath();
176 String libString = new File(new File(rootDire), "WEB-INF/lib").getAbsolutePath();
177
178 File dir = new File(libString);
179 if (dir.exists()) {
180 File[] files = dir.listFiles(new FilenameFilter() {
181 @Override
182 public boolean accept(File file, String name) {
183 return name.endsWith(".jar");
184 }
185 });
186
187 for (int i = 0; i < files.length; i++) {
188 collectFiles(resources, files[i], filter);
189 }
190 }
191
192
193 String classString = new File(new File(rootDire), "WEB-INF/classes").getAbsolutePath();
194 File classFileDir = new File(classString);
195
196 if (classFileDir.exists()) {
197 collectFiles(resources, classFileDir, filter);
198 }
199 }
200
201 public static File sanitizeToFile(URL url) {
202 if (!"file".equals(url.getProtocol()) && !StringUtils.startsWith(url.toString(), "jar:file:")) {
203 log.warn("Cannot load resources '{}' from '{}' protocol. Only 'file' and 'jar-file' protocols are supported.", url, url.getProtocol());
204 return null;
205 }
206 try {
207 String fileUrl = url.getFile();
208
209 fileUrl = URLDecoder.decode(fileUrl, "UTF-8");
210
211
212 fileUrl = StringUtils.removeStart(fileUrl, "file:");
213 fileUrl = StringUtils.removeEnd(fileUrl, "!/");
214 return new File(fileUrl);
215 } catch (UnsupportedEncodingException e) {
216 throw new RuntimeException(e);
217 }
218 }
219
220
221
222
223
224
225
226
227 private static void collectFiles(Collection<String> resources, File jarOrDir, Filter filter) {
228
229 if (!jarOrDir.exists()) {
230 log.warn("missing file: {}", jarOrDir.getAbsolutePath());
231 return;
232 }
233
234 if (jarOrDir.isDirectory()) {
235 log.debug("looking in dir {}", jarOrDir.getAbsolutePath());
236
237 Collection<File> files = FileUtils.listFiles(jarOrDir, TrueFileFilter.TRUE, TrueFileFilter.TRUE);
238 for (File file : files) {
239 String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());
240
241
242 name = StringUtils.replace(name, "\\", "/");
243 if (!name.startsWith("/")) {
244 name = "/" + name;
245 }
246
247 if (filter.accept(name)) {
248 resources.add(name);
249 }
250 }
251 }
252 else if (jarOrDir.getName().endsWith(".jar")) {
253 log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
254 JarFile jar;
255 try {
256 jar = new JarFile(jarOrDir);
257 } catch (IOException e) {
258 log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
259 return;
260 }
261 for (Enumeration<JarEntry> em = jar.entries(); em.hasMoreElements();) {
262 JarEntry entry = em.nextElement();
263 if (!entry.isDirectory()) {
264 if (filter.accept("/" + entry.getName())) {
265 resources.add("/" + entry.getName());
266 }
267 }
268 }
269 try {
270 jar.close();
271 } catch (IOException e) {
272 log.error("Failed to close jar file : {}", e.getMessage());
273 log.debug("Failed to close jar file", e);
274 }
275 }
276 else {
277 log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
278 }
279
280 }
281
282 public static InputStream getStream(String name) throws IOException {
283 return getStream(name, isCache());
284 }
285
286
287
288
289
290
291 public static InputStream getStream(String name, boolean cache) throws IOException {
292 if (cache) {
293 return getCurrentClassLoader().getResourceAsStream(StringUtils.removeStart(name, "/"));
294 }
295
296
297 URL url = getResource(name);
298 if (url != null) {
299 return url.openStream();
300 }
301
302 log.debug("Can't find {}", name);
303 return null;
304 }
305
306
307
308
309
310
311
312
313
314
315 public static ClassLoader getCurrentClassLoader() {
316 return Thread.currentThread().getContextClassLoader();
317 }
318
319
320
321
322
323
324
325 public static URL getResource(String name) {
326 return getCurrentClassLoader().getResource(StringUtils.removeStart(name, "/"));
327 }
328
329 }