KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.io.File JavaDoc;
40 import java.io.IOException JavaDoc;
41 import java.io.StringWriter JavaDoc;
42 import java.io.Writer JavaDoc;
43 import java.util.List JavaDoc;
44
45 import javax.servlet.ServletConfig JavaDoc;
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.ServletContext JavaDoc;
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49 import javax.servlet.http.HttpServletResponse JavaDoc;
50
51 import junit.framework.TestCase;
52 import net.sourceforge.cruisecontrol.mock.MockServletConfig;
53 import net.sourceforge.cruisecontrol.mock.MockServletContext;
54 import net.sourceforge.cruisecontrol.mock.MockServletRequest;
55 import net.sourceforge.cruisecontrol.mock.MockServletResponse;
56
57 /**
58  * @author jfredrick
59  */

60 public class FileServletTest extends TestCase {
61
62     private FileServlet servlet;
63
64     public FileServletTest(String JavaDoc testName) {
65         super(testName);
66     }
67
68     protected void setUp() {
69         servlet = new FileServlet();
70     }
71
72     protected void tearDown() {
73         servlet = null;
74     }
75
76     public void testGetRootDir() {
77         MockServletConfig config = new MockServletConfig();
78         MockServletContext context = new MockServletContext();
79         config.setServletContext(context);
80         
81         try {
82             servlet.getRootDir(config);
83             fail("should have exception when required attributes not set");
84         } catch (ServletException JavaDoc e) {
85         }
86
87         config.setInitParameter("rootDir", ".");
88         try {
89             servlet.getRootDir(config);
90         } catch (ServletException JavaDoc e) {
91             fail("shouldn't throw exception when valid rootDir parameter set");
92         }
93         
94         context.setInitParameter("logDir", "this directory does not exist");
95         try {
96             servlet.getRootDir(config);
97         } catch (ServletException JavaDoc e) {
98             fail("good rootDir but bad logDir should work");
99         }
100         
101         config = new MockServletConfig();
102         context = new MockServletContext();
103         config.setServletContext(context);
104
105         context.setInitParameter("logDir", ".");
106         try {
107             servlet.getRootDir(config);
108         } catch (ServletException JavaDoc e) {
109             fail("shouldn't throw exception when valid logDir parameter set");
110         }
111         
112         config.setInitParameter("rootDir", "this directory does not exist");
113         try {
114             servlet.getRootDir(config);
115         } catch (ServletException JavaDoc e) {
116             fail("bad rootDir but good logDir should work");
117         }
118     }
119
120     /*
121      * Test for void service(HttpServletRequest, HttpServletResponse)
122      */

123     public void testServiceInvalidFile() throws ServletException JavaDoc, IOException JavaDoc {
124         MockServletRequest request = new MockServletRequest();
125         MockServletResponse response = new MockServletResponse();
126
127         final String JavaDoc fileName = "tmp12345.html";
128         request.setPathInfo(fileName);
129
130         servlet.service(request, response);
131         String JavaDoc actual = response.getWritten();
132         String JavaDoc expected = "<html><body><h1>" + fileName + "</h1><h1>Invalid File or Directory</h1></body></html>";
133         assertEquals(expected, actual);
134         String JavaDoc actualMimeType = response.getContentType();
135         assertEquals("text/html", actualMimeType);
136         assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
137     }
138
139     /*
140      * Test for void service(HttpServletRequest, HttpServletResponse)
141      */

142     public void testServiceFile() throws ServletException JavaDoc, IOException JavaDoc {
143         MockServletRequest request = new MockServletRequest();
144         MockServletResponse response = new MockServletResponse();
145         File JavaDoc file = File.createTempFile("tmp", ".html");
146         file.deleteOnExit();
147         final File JavaDoc dir = file.getParentFile();
148
149         request.setPathInfo(file.getName());
150         servlet = new FileServlet() {
151             protected File JavaDoc getRootDir(ServletConfig JavaDoc servletconfig) {
152                 return dir;
153             }
154
155             protected String JavaDoc getMimeType(String JavaDoc filename) {
156                 if (filename.endsWith(".html")) {
157                     return "text/html";
158                 }
159                 return null;
160             }
161         };
162         final MockServletConfig servletconfig = new MockServletConfig();
163         servletconfig.setServletContext(new MockServletContext());
164         servlet.init(servletconfig);
165         servlet.service(request, response);
166         String JavaDoc actual = response.getWritten();
167         String JavaDoc expected = "";
168         assertEquals(expected, actual);
169         String JavaDoc actualMimeType = response.getContentType();
170         assertEquals("text/html", actualMimeType);
171     }
172
173     /*
174      * Test for void service(HttpServletRequest, HttpServletResponse)
175      */

176     public void testServiceParametrizedMimeType() throws ServletException JavaDoc, IOException JavaDoc {
177         MockServletRequest request = new MockServletRequest();
178         MockServletResponse response = new MockServletResponse();
179         File JavaDoc file = File.createTempFile("tmp", ".html");
180         file.deleteOnExit();
181         final File JavaDoc dir = file.getParentFile();
182
183         request.setPathInfo(file.getName());
184         request.addParameter("mimetype", "text/plain");
185         servlet = new FileServlet() {
186             protected File JavaDoc getRootDir(ServletConfig JavaDoc servletconfig) {
187                 return dir;
188             }
189
190             protected String JavaDoc getMimeType(String JavaDoc filename) {
191                 if (filename.endsWith(".html")) {
192                     return "text/html";
193                 }
194                 return null;
195             }
196         };
197         final MockServletConfig servletconfig = new MockServletConfig();
198         servletconfig.setServletContext(new MockServletContext());
199         servlet.init(servletconfig);
200         servlet.service(request, response);
201         String JavaDoc actual = response.getWritten();
202         String JavaDoc expected = "";
203         assertEquals(expected, actual);
204         String JavaDoc actualMimeType = response.getContentType();
205         assertEquals("text/plain", actualMimeType);
206
207         request.setPathInfo(file.getName());
208
209     }
210
211     public void testGetIndexes() throws ServletException JavaDoc, IOException JavaDoc {
212         MockServletConfig config = new MockServletConfig();
213         MockServletContext context = new MockServletContext();
214         config.setServletContext(context);
215
216         List JavaDoc indexes;
217
218         // 1- no index defined
219
indexes = servlet.getIndexFiles(config);
220         assertNotNull(indexes);
221         assertEquals(0, indexes.size());
222
223         // 2-
224
context.setInitParameter("fileServlet.welcomeFiles", null);
225         indexes = servlet.getIndexFiles(config);
226         assertNotNull(indexes);
227         assertEquals(0, indexes.size());
228
229         // 3-
230
context.setInitParameter("fileServlet.welcomeFiles", "");
231         indexes = servlet.getIndexFiles(config);
232         assertNotNull(indexes);
233         assertEquals(0, indexes.size());
234
235         // 4- some indexes defined
236
context.setInitParameter("fileServlet.welcomeFiles", "index.htm index.html");
237         indexes = servlet.getIndexFiles(config);
238         assertNotNull(indexes);
239         assertEquals(2, indexes.size());
240         assertEquals("index.htm", indexes.get(0));
241         assertEquals("index.html", indexes.get(1));
242
243         // 5- resistant to strange spacing
244
context.setInitParameter("fileServlet.welcomeFiles", " index.html index.htm ");
245         indexes = servlet.getIndexFiles(config);
246         assertNotNull(indexes);
247         assertEquals(2, indexes.size());
248         assertEquals("index.html", indexes.get(0));
249         assertEquals("index.htm", indexes.get(1));
250     }
251
252     /** a mock that allows to specify the names of the files returned by {@link #list()}**/
253     static class MockWebFile extends WebFile {
254         private String JavaDoc[] subFiles;
255
256         public MockWebFile(File JavaDoc root, String JavaDoc path, String JavaDoc[] subFiles) {
257             super(root, path);
258             this.subFiles = subFiles;
259         }
260
261         public String JavaDoc[] list() {
262             return subFiles;
263         }
264     }
265
266     /**
267      * Simulates both a request with or without a sessionid attached.
268      * @throws IOException
269      */

270     public void testPrintDirs() throws IOException JavaDoc {
271         FileServlet fileServlet = new FileServlet() {
272             protected WebFile getSubWebFile(final String JavaDoc subFilePath) {
273                 return new WebFile(getRootDir(), subFilePath) {
274                     public boolean isDir() {
275                         String JavaDoc lastPathElt = subFilePath.substring(subFilePath.lastIndexOf('/') + 1);
276                         final boolean b = lastPathElt.indexOf(".") == -1;
277                         return b;
278                     }
279                 };
280             }
281         };
282
283         String JavaDoc[] files =
284             {
285                 new String JavaDoc("log1.txt"),
286                 new String JavaDoc("log2")
287             };
288
289         final StringWriter JavaDoc writer1 = new StringWriter JavaDoc();
290
291         final MockServletRequest request1 = new MockServletRequest() {
292             public String JavaDoc getRequestURI() {
293                 return "/artifacts/abc";
294             }
295         };
296         fileServlet.printDirs(request1, new MockWebFile(new File JavaDoc("notimportant"), "notimportant", files), writer1);
297
298         final String JavaDoc expectedOutput1 =
299             "<ul>"
300             + "<li><a HREF=\"/artifacts/abc/log1.txt\">log1.txt</a></li>"
301             + "<li><a HREF=\"/artifacts/abc/log2\">log2/</a></li>"
302             + "</ul>";
303
304         assertEquals(expectedOutput1, writer1.getBuffer().toString());
305
306
307         final StringWriter JavaDoc writer2 = new StringWriter JavaDoc();
308         final MockServletRequest request2 = new MockServletRequest() {
309             public String JavaDoc getRequestURI() {
310                 return "/artifacts/abc;jsessionid=012456789ABCDEF";
311             }
312         };
313         fileServlet.printDirs(request2, new MockWebFile(new File JavaDoc("/tmp"), "test", files), writer2);
314
315         final String JavaDoc expectedOutput2 =
316             "<ul>"
317             + "<li><a HREF=\"/artifacts/abc/log1.txt;jsessionid=012456789ABCDEF\">log1.txt</a></li>"
318             + "<li><a HREF=\"/artifacts/abc/log2;jsessionid=012456789ABCDEF\">log2/</a></li>"
319             + "</ul>";
320
321         assertEquals(expectedOutput2, writer2.getBuffer().toString());
322     }
323
324     public void testServiceIndexFile() throws ServletException JavaDoc, IOException JavaDoc {
325         MockServletRequest request = new MockServletRequest() {
326           public String JavaDoc getRequestURI() {
327             return "";
328           }
329         };
330         MyMockServletResponse response1 = new MyMockServletResponse();
331         final File JavaDoc dir = new File JavaDoc(System.getProperty("java.io.tmpdir"));
332
333         MyMockFileServlet myServlet = new MyMockFileServlet();
334         myServlet.setRootDir(dir);
335
336         MockServletConfig config = new MockServletConfig();
337         MockServletContext context = new MockServletContext() {
338             public String JavaDoc getMimeType(String JavaDoc s) {
339                 return "text/html";
340             }
341         };
342         config.setServletContext(context);
343         myServlet.init(config);
344
345         File JavaDoc indexFile = new File JavaDoc(dir, "index.html");
346         indexFile.deleteOnExit();
347         assertFalse("cannot test service index if index.html already exists", indexFile.exists());
348         boolean created = indexFile.createNewFile();
349         assertTrue(created);
350
351         // redirect when no trailing path, even if no index defined.
352
request.setPathInfo("");
353         myServlet.service(request, response1);
354         response1.ensureRedirect("/");
355         assertEquals(0, myServlet.printDirCalls);
356
357         // do not display index if none configured
358
myServlet.init();
359         MyMockServletResponse response2 = new MyMockServletResponse();
360         request.setPathInfo("/");
361         myServlet.service(request, response2);
362         String JavaDoc actual = response2.getWritten();
363         assertTrue(actual.startsWith("<html><body><h1>"));
364         assertTrue(myServlet.printDirCalls > 0);
365         String JavaDoc actualMimeType = response2.getContentType();
366         assertEquals("text/html", actualMimeType);
367
368         // use index if one exists when asking for trailing path and fileServlet.indexFiles configured
369
myServlet.init();
370         MyMockServletResponse response3 = new MyMockServletResponse();
371         context.setInitParameter("fileServlet.welcomeFiles", "index.html");
372         config.setServletContext(context);
373         myServlet.init(config);
374
375         request.setPathInfo("/");
376         myServlet.service(request, response3);
377         actual = response3.getWritten();
378         String JavaDoc expected = "";
379         assertEquals(expected, actual);
380         actualMimeType = response3.getContentType();
381         assertEquals("text/html", actualMimeType);
382         assertEquals(0, myServlet.printDirCalls);
383     }
384
385     public void testGetMimeType() {
386         MockServletContext context = new MockServletContext() {
387             public String JavaDoc getMimeType(String JavaDoc s) {
388                 return "text/html";
389             }
390         };
391         servlet = new TestFileServlet(context);
392         assertEquals("text/html", servlet.getMimeType(""));
393
394         context = new MockServletContext() {
395             public String JavaDoc getMimeType(String JavaDoc s) {
396                 return null;
397             }
398         };
399         servlet = new TestFileServlet(context);
400         assertEquals("text/plain", servlet.getMimeType(""));
401     }
402
403     private final class TestFileServlet extends FileServlet {
404         private MockServletContext context;
405
406         private TestFileServlet(MockServletContext msc) {
407             super();
408             context = msc;
409         }
410
411         public ServletContext JavaDoc getServletContext() {
412             return context;
413         }
414     }
415
416     static class MyMockServletResponse extends MockServletResponse {
417         private String JavaDoc redirected;
418         public void sendRedirect(String JavaDoc arg0) throws IOException JavaDoc {
419             redirected = arg0;
420         }
421
422         public void ensureRedirect(String JavaDoc expectedRedirect) {
423             assertEquals(expectedRedirect, redirected);
424         }
425
426         public String JavaDoc encodeRedirectURL(String JavaDoc arg0) {
427           return arg0;
428         }
429     }
430
431     static class MyMockFileServlet extends FileServlet {
432         private File JavaDoc rootDir;
433         private int printDirCalls;
434
435         public void init() {
436             printDirCalls = 0;
437         }
438
439         public void setRootDir(File JavaDoc rootDir) {
440             this.rootDir = rootDir;
441         }
442
443         protected File JavaDoc getRootDir(ServletConfig JavaDoc servletconfig) {
444             return rootDir;
445         }
446
447         void printDirs(HttpServletRequest JavaDoc request, WebFile file, Writer JavaDoc writer) throws IOException JavaDoc {
448             super.printDirs(request, file, writer);
449             printDirCalls++;
450         }
451     }
452 }
453
Popular Tags