KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jzonic > jlo > reader > ResourceLocator


1 /*
2  * ResourceLocator.java
3  *
4  * Created on 21. Januar 2003, 21:33
5  */

6
7 package org.jzonic.jlo.reader;
8 import java.io.*;
9 import java.net.URL JavaDoc;
10 import java.util.StringTokenizer JavaDoc;
11 import java.util.Vector JavaDoc;
12 /**
13  * Adopted from <a HREF="http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index1.html?page=3">Servlet Best Practices, Part 1</a>
14  *
15  * A class to locate resources, retrieve their contents, and determine their
16  * last modified time. To find the resource the class searches the CLASSPATH
17  * first, then Resource.class.getResource("/" + name). If the Resource finds
18  * a "file:" URL, the file path will be treated as a file. Otherwise, the
19  * path is treated as a URL and has limited last modified info.
20  *
21  * @author Andreas Mecky <andreas.mecky@jzonic.org>
22  * @author Terry Dye <terry.dye@jzonic.org>
23  */

24 public class ResourceLocator implements Serializable {
25
26     private String JavaDoc myName;
27     private File myFile;
28     private URL JavaDoc myUrl;
29
30     /** Creates a new instance of ResourceLocator */
31     public ResourceLocator() {
32     }
33
34
35     public ResourceLocator(String JavaDoc name) throws IOException {
36         myName = name;
37         SecurityException JavaDoc exception = null;
38
39         try {
40             // Search using the CLASSPATH. If found, "file" is set and the call
41
// returns true. A SecurityException might bubble up.
42
if (tryClasspath(name)) {
43                 return;
44             }
45         } catch (SecurityException JavaDoc e) {
46             exception = e; // Save for later.
47
}
48
49         try {
50             // Search using the classloader getResource( ). If found as a file,
51
// "file" is set; if found as a URL, "url" is set.
52
if (tryLoader(name)) {
53                 return;
54             }
55         } catch (SecurityException JavaDoc e) {
56             exception = e; // Save for later.
57
}
58
59         // If you get here, something went wrong. Report the exception.
60
String JavaDoc msg = "";
61         if (exception != null) {
62             msg = ": " + exception;
63         }
64
65         throw new IOException(
66             "Resource <"
67                 + name
68                 + "> could not be found in "
69                 + "the CLASSPATH ("
70                 + System.getProperty("java.class.path")
71                 + "), nor could it be located by the classloader responsible for the "
72                 + "web application (WEB-INF/classes)"
73                 + msg);
74     }
75
76     /**
77      * Method findResource.
78      * @param fileName
79      * @return InputStream
80      */

81     public InputStream findResource(String JavaDoc fileName) {
82         if ( fileName == null ) {
83             return null;
84         }
85         return getClass().getClassLoader().getResourceAsStream(fileName);
86     }
87
88     /**
89      * Returns the resource name, as passed to the constructor
90      */

91     public String JavaDoc getName() {
92         return myName;
93     }
94
95     /**
96      * Returns an input stream to read the resource contents
97      */

98     public InputStream getInputStream() throws IOException {
99         if (myFile != null) {
100             return new BufferedInputStream(new FileInputStream(myFile));
101         } else if (myUrl != null) {
102             return new BufferedInputStream(myUrl.openStream());
103         }
104         return null;
105     }
106
107     /**
108      * Returns when the resource was last modified. If the resource
109      * was found using a URL, this method will work only if the URL
110      * connection supports last modified information. If there's no
111      * support, Long.MAX_VALUE is returned. Perhaps this should return
112      * -1, but you should return MAX_VALUE on the assumption that if
113      * you can't determine the time, it's maximally new.
114      */

115     public long lastModified() {
116         if (myFile != null) {
117             return myFile.lastModified();
118         } else if (myUrl != null) {
119             try {
120                 return myUrl.openConnection().getLastModified(); // Hail Mary
121
} catch (IOException e) {
122                 return Long.MAX_VALUE;
123             }
124         }
125         return 0; // can't happen
126
}
127
128     /**
129      * Returns the directory containing the resource, or null if the
130      * resource isn't directly available on the filesystem.
131      * This value can be used to locate the configuration file on disk,
132      * or to write files in the same directory.
133      */

134     public String JavaDoc getDirectory() {
135         if (myFile != null) {
136             return myFile.getParent();
137         } else if (myUrl != null) {
138             return null;
139         }
140         return null;
141     }
142
143     // Returns true if found
144
private boolean tryClasspath(String JavaDoc filename) {
145         if(filename == null) return false;
146         String JavaDoc classpath = System.getProperty("java.class.path");
147         String JavaDoc[] paths = split(classpath, File.pathSeparator);
148         myFile = searchDirectories(paths, filename);
149         return (myFile != null);
150     }
151
152     private static File searchDirectories(String JavaDoc[] paths, String JavaDoc filename) {
153         SecurityException JavaDoc exception = null;
154         for (int i = 0; i < paths.length; i++) {
155             try {
156                 File file = new File(paths[i], filename);
157                 if (file.exists() && !file.isDirectory()) {
158                     return file;
159                 }
160             } catch (SecurityException JavaDoc e) {
161                 // Security exceptions can usually be ignored, but if all attempts
162
// to find the file fail, report the (last) security exception.
163
exception = e;
164             }
165         }
166         // Couldn't find any match
167
if (exception != null) {
168             throw exception;
169         } else {
170             return null;
171         }
172     }
173
174     // Splits a String into pieces according to a delimiter.
175
// Uses JDK 1.1 classes for backward compatibility.
176
// JDK 1.4 actually has a split( ) method now.
177
private static String JavaDoc[] split(String JavaDoc str, String JavaDoc delim) {
178         // Use a Vector to hold the split strings.
179
Vector JavaDoc v = new Vector JavaDoc();
180
181         // Use a StringTokenizer to do the splitting.
182
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(str, delim);
183         while (tokenizer.hasMoreTokens()) {
184             v.addElement(tokenizer.nextToken());
185         }
186
187         String JavaDoc[] ret = new String JavaDoc[v.size()];
188         v.copyInto(ret);
189         return ret;
190     }
191
192     // Returns true if found
193
private boolean tryLoader(String JavaDoc name) {
194         name = "/" + name;
195         URL JavaDoc res = ResourceLocator.class.getResource(name);
196         if (res == null) {
197             return false;
198         }
199
200         // Try converting from a URL to a File.
201
File resFile = urlToFile(res);
202         if (resFile != null) {
203             myFile = resFile;
204         } else {
205             myUrl = res;
206         }
207         return true;
208     }
209
210     private static File urlToFile(URL JavaDoc res) {
211         String JavaDoc externalForm = res.toExternalForm();
212         if (externalForm.startsWith("file:")) {
213             return new File(externalForm.substring(5));
214         }
215         return null;
216     }
217
218     public String JavaDoc toString() {
219         return "[Resource: File: " + myFile + " URL: " + myUrl + "]";
220     }
221
222 }
223
Popular Tags