KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > module > sitemesh > mapper > FileDecoratorMapper


1 /*
2  * Title: FileDecoratorMapper
3  * Description:
4  *
5  * This software is published under the terms of the OpenSymphony Software
6  * License version 1.1, of which a copy has been included with this
7  * distribution in the LICENSE.txt file.
8  */

9
10 package com.opensymphony.module.sitemesh.mapper;
11
12 import com.opensymphony.module.sitemesh.Decorator;
13
14 import java.io.File JavaDoc;
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.URL JavaDoc;
17 import javax.servlet.http.HttpServletRequest JavaDoc;
18
19 /**
20  * The FileDecoratorMapper will treat the name of the decorator as a file-name to use
21  * (in the context of the web-app).
22  *
23  * @author <a HREF="joe@truemesh.com">Joe Walnes</a>
24  * @author <a HREF="mike@atlassian.com">Mike Cannon-Brookes</a>
25  * @version $Revision: 1.1 $
26  *
27  * @see com.opensymphony.module.sitemesh.DecoratorMapper
28  * @see com.opensymphony.module.sitemesh.mapper.DefaultDecorator
29  */

30 public class FileDecoratorMapper extends AbstractDecoratorMapper {
31     private static boolean pathNotAvailable = false;
32
33     public Decorator getNamedDecorator(HttpServletRequest JavaDoc req, String JavaDoc name) {
34         if (pathNotAvailable || name == null) {
35             return super.getNamedDecorator(req, name);
36         }
37
38         URL JavaDoc resourcePath = null;
39
40         // try to locate the resource (might be an unexpanded WAR)
41
try {
42             resourcePath = config.getServletContext().getResource('/' + name);
43         }
44         catch (MalformedURLException JavaDoc e) {
45             e.printStackTrace();
46             return super.getNamedDecorator(req, name);
47         }
48
49         String JavaDoc filePath = config.getServletContext().getRealPath(name);
50
51         if (filePath == null && resourcePath == null) {
52             pathNotAvailable = true;
53             return super.getNamedDecorator(req, name);
54         }
55         else if (filePath != null) { // do we really need this disk file check?!
56
File JavaDoc file = new File JavaDoc(filePath);
57
58             if (file.exists() && file.canRead()) {
59                 // if filename exists with name of supplied decorator, return Decorator
60
return new DefaultDecorator(name, name, null);
61             }
62             else {
63                 // otherwise delegate to parent mapper.
64
return super.getNamedDecorator(req, name);
65             }
66         }
67         else {
68             // file path is null and resource path is not null - can't check file on disk
69
return new DefaultDecorator(name, name, null);
70         }
71     }
72 }
Popular Tags