01: package org.acm.seguin.pmd.util;
02:
03: import org.acm.seguin.pmd.RuleSetNotFoundException;
04: import org.acm.seguin.util.FileSettings;
05: import java.io.File;
06: import java.io.FileInputStream;
07: import java.io.FileNotFoundException;
08: import java.io.InputStream;
09: import java.net.URL;
10:
11: public class ResourceLoader {
12:
13: // Single static method, so we shouldn't allow an instance to be created
14: private ResourceLoader() {
15: }
16:
17: /**
18: *
19: * Method to find a file, first by finding it as a file
20: * (either by the absolute or relative path), then as
21: * a URL, and then finally seeing if it is on the classpath.
22: *
23: */
24: public static InputStream loadResourceAsStream(String name)
25: throws RuleSetNotFoundException {
26: InputStream stream = ResourceLoader.loadResourceAsStream(name,
27: new ResourceLoader().getClass().getClassLoader());
28: if (stream == null) {
29: throw new RuleSetNotFoundException(
30: "Can't find resource "
31: + name
32: + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
33: }
34: return stream;
35: }
36:
37: /**
38: *
39: * Uses the ClassLoader passed in to attempt to load the
40: * resource if it's not a File or a URL
41: *
42: */
43: public static InputStream loadResourceAsStream(String name,
44: ClassLoader loader) throws RuleSetNotFoundException {
45: File file = new File(name);
46: if (file.exists()) {
47: try {
48: return new FileInputStream(file);
49: } catch (FileNotFoundException e) {
50: System.out
51: .println("ResourceLoader: can't load from file="
52: + file);
53: // if the file didn't exist, we wouldn't be here
54: }
55: } else {
56:
57: file = new File(FileSettings.getRefactorySettingsRoot(),
58: name);
59: if (file.exists()) {
60: try {
61: return new FileInputStream(file);
62: } catch (FileNotFoundException e) {
63: System.out
64: .println("ResourceLoader: can't load from file="
65: + file);
66: // if the file didn't exist, we wouldn't be here
67: }
68: }
69:
70: try {
71: return new URL(name).openConnection().getInputStream();
72: } catch (Exception e) {
73: return loader.getResourceAsStream(name);
74: }
75: }
76: throw new RuleSetNotFoundException(
77: "Can't find resource "
78: + name
79: + ". Make sure the resource is a valid file or URL or is on the CLASSPATH");
80: }
81: }
|