KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > cruisecontrol > servlet > FileServlet


1 /********************************************************************************
2  * CruiseControl, a Continuous Integration Toolkit
3  * Copyright (c) 2003, ThoughtWorks, Inc.
4  * 651 W Washington Ave. Suite 600
5  * Chicago, IL 60661 USA
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * + Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * + Redistributions in binary form must reproduce the above
16  * copyright notice, this list of conditions and the following
17  * disclaimer in the documentation and/or other materials provided
18  * with the distribution.
19  *
20  * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the
21  * names of its contributors may be used to endorse or promote
22  * products derived from this software without specific prior
23  * written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
29  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  ********************************************************************************/

37 package net.sourceforge.cruisecontrol.servlet;
38
39 import javax.servlet.ServletConfig JavaDoc;
40 import javax.servlet.ServletContext JavaDoc;
41 import javax.servlet.ServletException JavaDoc;
42 import javax.servlet.ServletOutputStream JavaDoc;
43 import javax.servlet.http.HttpServlet JavaDoc;
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.http.HttpServletResponse JavaDoc;
46 import java.io.BufferedInputStream JavaDoc;
47 import java.io.BufferedOutputStream JavaDoc;
48 import java.io.File JavaDoc;
49 import java.io.FileInputStream JavaDoc;
50 import java.io.InputStream JavaDoc;
51 import java.io.IOException JavaDoc;
52 import java.io.OutputStream JavaDoc;
53 import java.io.Writer JavaDoc;
54 import java.util.StringTokenizer JavaDoc;
55 import java.util.List JavaDoc;
56 import java.util.Collections JavaDoc;
57 import java.util.ArrayList JavaDoc;
58 import java.util.Arrays JavaDoc;
59 import java.util.Date JavaDoc;
60
61 public class FileServlet extends HttpServlet JavaDoc {
62
63     private File JavaDoc rootDir;
64     private List JavaDoc indexFiles;
65
66     public File JavaDoc getRootDir() {
67         return rootDir;
68     }
69
70     public void init(ServletConfig JavaDoc servletconfig) throws ServletException JavaDoc {
71         super.init(servletconfig);
72         rootDir = getRootDir(servletconfig);
73         indexFiles = getIndexFiles(servletconfig);
74     }
75
76     protected File JavaDoc getRootDir(ServletConfig JavaDoc servletconfig) throws ServletException JavaDoc {
77         String JavaDoc root = servletconfig.getInitParameter("rootDir");
78         File JavaDoc rootDirectory = getDirectoryFromName(root);
79         if (rootDirectory == null) {
80             rootDirectory = getLogDir(servletconfig);
81             if (rootDirectory == null) {
82                 String JavaDoc message = "ArtifactServlet not configured correctly in web.xml.\n"
83                      + "Either rootDir or logDir must point to existing directory.\n"
84                      + "rootDir is currently set to <" + root + "> "
85                      + "while logDir is <" + getLogDirParameter(servletconfig) + ">";
86                 throw new ServletException JavaDoc(message);
87             }
88         }
89
90         return rootDirectory;
91     }
92
93     protected String JavaDoc getLogDirParameter(ServletConfig JavaDoc servletconfig) throws ServletException JavaDoc {
94         ServletContext JavaDoc context = servletconfig.getServletContext();
95         return context.getInitParameter("logDir");
96     }
97     protected File JavaDoc getLogDir(ServletConfig JavaDoc servletconfig) throws ServletException JavaDoc {
98         String JavaDoc logDir = getLogDirParameter(servletconfig);
99         return getDirectoryFromName(logDir);
100     }
101
102
103     List JavaDoc getIndexFiles(ServletConfig JavaDoc servletconfig) {
104         ServletContext JavaDoc context = servletconfig.getServletContext();
105         String JavaDoc logDir = context.getInitParameter("fileServlet.welcomeFiles");
106         List JavaDoc indexes = Collections.EMPTY_LIST;
107         if (logDir != null) {
108             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(logDir);
109             indexes = new ArrayList JavaDoc();
110             while (tokenizer.hasMoreTokens()) {
111                 String JavaDoc indexFile = ((String JavaDoc) tokenizer.nextElement());
112                 // note: I am pretty sure there's a known issue with StringTokenizer returning "" (cf ant)
113
// but am offline right now and cannot check.
114
if (!"".equals(indexFile)) {
115                     indexes.add(indexFile);
116                 }
117             }
118         }
119         return indexes;
120     }
121
122     private static File JavaDoc getDirectoryFromName(String JavaDoc dir) {
123         File JavaDoc rootDirectory;
124         if (dir == null) {
125             return null;
126         }
127         rootDirectory = new File JavaDoc(dir);
128         if (!rootDirectory.exists() || rootDirectory.isFile()) {
129             return null;
130         }
131         return rootDirectory;
132     }
133
134     public void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
135         throws ServletException JavaDoc, IOException JavaDoc {
136         WebFile file = getSubWebFile(request.getPathInfo());
137
138         if (file.isDir()) {
139             // note we might want to append the queryString just in case...
140
if (!request.getPathInfo().endsWith("/")) {
141                 response.sendRedirect(response.encodeRedirectURL(request.getRequestURI() + '/'));
142                 return;
143             }
144             String JavaDoc index = getIndexFile(file);
145             if (index != null) {
146                 file = getSubWebFile(request.getPathInfo() + index);
147             }
148         }
149
150         if (file.isFile()) {
151             String JavaDoc filename = file.getName();
152             String JavaDoc mimeType;
153             if (request.getParameter("mimetype") != null) {
154                 mimeType = request.getParameter("mimetype");
155             } else {
156                 mimeType = getMimeType(filename);
157             }
158             Date JavaDoc date = new Date JavaDoc(file.getFile().lastModified());
159             response.addDateHeader("Last-Modified", date.getTime());
160             response.setContentType(mimeType);
161             file.write(response.getOutputStream());
162             return;
163         }
164
165         response.setContentType("text/html");
166         Writer JavaDoc writer = response.getWriter();
167         writer.write("<html>");
168         writer.write("<body>");
169         writer.write("<h1>" + file + "</h1>");
170         if (file.isDir()) {
171             printDirs(request, file, writer);
172         } else {
173             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
174             writer.write("<h1>Invalid File or Directory</h1>");
175         }
176         writer.write("</body>");
177         writer.write("</html>");
178     }
179
180     protected String JavaDoc getMimeType(String JavaDoc filename) {
181         String JavaDoc mimeType = getServletContext().getMimeType(filename);
182         if (mimeType == null) {
183             mimeType = getDefaultMimeType();
184         }
185         return mimeType;
186     }
187
188     protected String JavaDoc getDefaultMimeType() {
189         return "text/plain";
190     }
191
192     /**
193      * @return the name of the first found known index file under the
194      * specified directory or <code>null</code> if none found
195      * @throws IllegalArgumentException if the specified WebFile is not a directory
196      **/

197     private String JavaDoc getIndexFile(WebFile dir) {
198         if (!dir.isDir()) {
199             throw new IllegalArgumentException JavaDoc(dir + " is not a directory");
200         }
201         for (int i = 0; i < indexFiles.size(); i++) {
202             final File JavaDoc file = new File JavaDoc(dir.getFile(), (String JavaDoc) indexFiles.get(i));
203             // what about hidden files? let's display them...
204
if (file.exists() && file.isFile()) {
205                 return (String JavaDoc) indexFiles.get(i);
206             }
207         }
208         return null;
209     }
210
211     /**
212      * Returns an HTML snippet that allows the browsing of the directory's content.
213      * @param request
214      * @param file
215      * @param writer
216      * @throws IOException
217      */

218     void printDirs(HttpServletRequest JavaDoc request, WebFile file, Writer JavaDoc writer)
219         throws IOException JavaDoc {
220         String JavaDoc[] files = file.list();
221         writer.write("<ul>");
222         for (int i = 0; i < files.length; i++) {
223             final String JavaDoc requestURI = request.getRequestURI();
224             int jsessionidIdx = requestURI.indexOf(";jsessionid");
225             String JavaDoc shortRequestURI;
226             String JavaDoc jsessionid;
227             if (jsessionidIdx >= 0) {
228               shortRequestURI = requestURI.substring(0, jsessionidIdx);
229               jsessionid = requestURI.substring(jsessionidIdx);
230             } else {
231               shortRequestURI = requestURI;
232               jsessionid = "";
233             }
234
235             final String JavaDoc subFilePath = request.getPathInfo() + '/' + files[i];
236             WebFile sub = getSubWebFile(subFilePath);
237             writer.write(
238                 "<li><a HREF=\""
239                     + shortRequestURI
240                     + "/"
241                     + files[i]
242                     + jsessionid
243                     + "\">"
244                     + files[i]
245                     + (sub.isDir() ? "/" : "")
246                     + "</a></li>");
247         }
248         writer.write("</ul>");
249     }
250
251     protected WebFile getSubWebFile(final String JavaDoc subFilePath) {
252         return new WebFile(rootDir, subFilePath);
253     }
254
255 }
256
257 class WebFile {
258
259     private final File JavaDoc file;
260
261     public WebFile(File JavaDoc logfile) {
262         file = logfile;
263     }
264
265     public WebFile(File JavaDoc root, String JavaDoc path) {
266         file = WebFile.parsePath(root, path);
267     }
268
269     public String JavaDoc getName() {
270         return file.getName();
271     }
272
273     public boolean isDir() {
274         return file.isDirectory();
275     }
276
277     protected InputStream JavaDoc getInputStream() throws IOException JavaDoc {
278         return new FileInputStream JavaDoc(file);
279     }
280
281     public void write(ServletOutputStream JavaDoc stream) throws IOException JavaDoc {
282         InputStream JavaDoc input = new BufferedInputStream JavaDoc(getInputStream());
283         OutputStream JavaDoc output = new BufferedOutputStream JavaDoc(stream);
284         try {
285             int i;
286             while ((i = input.read()) != -1) {
287                 output.write(i);
288             }
289         } finally {
290             input.close();
291             output.flush();
292         }
293     }
294
295     public boolean isFile() {
296         return file.isFile();
297     }
298
299     private static File JavaDoc parsePath(File JavaDoc rootDir, String JavaDoc string) {
300         if (string == null || string.trim().length() == 0 || string.equals("/")) {
301             return rootDir;
302         }
303         String JavaDoc filename = string.replace('/', File.separatorChar);
304         filename = filename.replace('\\', File.separatorChar);
305         return new File JavaDoc(rootDir, filename);
306     }
307
308     public String JavaDoc[] list() {
309         String JavaDoc[] files = file.list();
310         if (files == null) {
311             files = new String JavaDoc[0];
312         } else {
313             Arrays.sort(files);
314         }
315         return files;
316     }
317
318     public String JavaDoc toString() {
319         return file.toString();
320     }
321
322     public File JavaDoc getFile() {
323         return file;
324     }
325 }
326
Popular Tags