1 package org.apache.fulcrum.yaafi.framework.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26
27 import org.apache.avalon.framework.logger.Logger;
28 import org.apache.avalon.framework.logger.NullLogger;
29
30
31
32
33
34
35
36 public class InputStreamLocator {
37
38
39 private File rootDir;
40
41
42 private Logger logger;
43
44
45
46
47 public InputStreamLocator() {
48 this.rootDir = new File(new File("").getAbsolutePath());
49 this.logger = new NullLogger();
50 }
51
52
53
54
55
56
57 public InputStreamLocator(File rootDir) {
58 this(rootDir, new NullLogger());
59 }
60
61
62
63
64
65
66
67 public InputStreamLocator(File rootDir, Logger logger) {
68 this.rootDir = rootDir;
69 this.logger = logger;
70 }
71
72
73
74
75
76
77
78
79 public InputStream locate(String location) throws IOException {
80 if (location == null || location.length() == 0) {
81 return null;
82 }
83
84 String baseName = null;
85 File file = null;
86 InputStream is = null;
87
88
89
90 if (is == null) {
91 file = new File(this.rootDir, location);
92
93 this.logger.debug("Looking for " + location + " in the root directory");
94
95 if (file.exists()) {
96 is = new FileInputStream(file);
97 this.logger.debug("Found " + location + " as " + file.getAbsolutePath());
98 }
99 }
100
101
102
103 if (is == null) {
104 file = new File(location);
105
106 this.logger.debug("Looking for " + location + " as absolute file location");
107
108 if (file.isAbsolute() && file.exists()) {
109 is = new FileInputStream(file);
110 this.logger.debug("Found " + location + " as " + file.getAbsolutePath());
111 }
112 }
113
114
115
116 if (is == null && location.startsWith("/") == true) {
117 this.logger.debug("Looking for " + location + " using the class loader");
118 is = getClass().getResourceAsStream(location);
119
120 if (is != null) {
121 this.logger.debug("Successfully located " + location);
122 }
123 }
124
125
126
127
128
129 if (is == null && location.startsWith("/") == false) {
130 baseName = '/' + new File(location).getName();
131 this.logger.debug("Looking for " + baseName + " using the class loader");
132 is = getClass().getResourceAsStream(baseName);
133 if (is != null) {
134 this.logger.debug("Successfully located " + baseName);
135 }
136 }
137
138 if (is == null) {
139 this.logger.debug("Unable to find any resource with the name '" + location + "'");
140 }
141
142 return is;
143 }
144
145
146
147
148 protected File getRootDir() {
149 return rootDir;
150 }
151
152 }