KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > freemarker > cache > FileTemplateLoader


1 /*
2  * Copyright (c) 2003 The Visigoth Software Society. All rights
3  * reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  * notice, this list of conditions and the following disclaimer in
14  * the documentation and/or other materials provided with the
15  * distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowledgement:
19  * "This product includes software developed by the
20  * Visigoth Software Society (http://www.visigoths.org/)."
21  * Alternately, this acknowledgement may appear in the software itself,
22  * if and wherever such third-party acknowledgements normally appear.
23  *
24  * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
25  * project contributors may be used to endorse or promote products derived
26  * from this software without prior written permission. For written
27  * permission, please contact visigoths@visigoths.org.
28  *
29  * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
30  * nor may "FreeMarker" or "Visigoth" appear in their names
31  * without prior written permission of the Visigoth Software Society.
32  *
33  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
34  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36  * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR
37  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
40  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
41  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
42  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
43  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44  * SUCH DAMAGE.
45  * ====================================================================
46  *
47  * This software consists of voluntary contributions made by many
48  * individuals on behalf of the Visigoth Software Society. For more
49  * information on the Visigoth Software Society, please see
50  * http://www.visigoths.org/
51  */

52
53 package freemarker.cache;
54
55 import java.io.File JavaDoc;
56 import java.io.FileInputStream JavaDoc;
57 import java.io.FileNotFoundException JavaDoc;
58 import java.io.IOException JavaDoc;
59 import java.io.InputStreamReader JavaDoc;
60 import java.io.Reader JavaDoc;
61 import java.security.AccessController JavaDoc;
62 import java.security.PrivilegedAction JavaDoc;
63 import java.security.PrivilegedActionException JavaDoc;
64 import java.security.PrivilegedExceptionAction JavaDoc;
65
66 import freemarker.template.utility.SecurityUtilities;
67
68 /**
69  * A {@link TemplateLoader} that uses files in a specified directory as the
70  * source of templates. If contains security checks that will prevent it
71  * serving templates outside the template directory (like <code>&lt;include /etc/passwd></code>.
72  * It compares canonical paths for this, so templates that are symbolically
73  * linked into the template directory from outside of it won't work either.
74  * @author Attila Szegedi, szegedia at freemail dot hu
75  * @version $Id: FileTemplateLoader.java,v 1.26 2004/03/29 08:06:22 szegedia Exp $
76  */

77 public class FileTemplateLoader implements TemplateLoader
78 {
79     private static final boolean SEP_IS_SLASH = File.separatorChar == '/';
80     public final File JavaDoc baseDir;
81     private final String JavaDoc canonicalPath;
82
83     /**
84      * Creates a new file template cache that will use the current directory
85      * (the value of the system property <code>user.dir</code> as the base
86      * directory for loading templates.
87      */

88     public FileTemplateLoader()
89     throws
90         IOException JavaDoc
91     {
92         this(new File JavaDoc(SecurityUtilities.getSystemProperty("user.dir")));
93     }
94
95     /**
96      * Creates a new file template loader that will use the specified directory
97      * as the base directory for loading templates.
98      * @param baseDir the base directory for loading templates
99      */

100     public FileTemplateLoader(final File JavaDoc baseDir)
101     throws
102         IOException JavaDoc
103     {
104         try
105         {
106             Object JavaDoc[] retval = (Object JavaDoc[]) AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc()
107             {
108                 public Object JavaDoc run()
109                 throws
110                     IOException JavaDoc
111                 {
112                     if (!baseDir.exists())
113                     {
114                         throw new FileNotFoundException JavaDoc(baseDir + " does not exist.");
115                     }
116                     if (!baseDir.isDirectory())
117                     {
118                         throw new IOException JavaDoc(baseDir + " is not a directory.");
119                     }
120                     Object JavaDoc[] retval = new Object JavaDoc[2];
121                     retval[0] = baseDir.getCanonicalFile();
122                     retval[1] = ((File JavaDoc) retval[0]).getPath() + File.separatorChar;
123                     return retval;
124                 }
125             });
126             this.baseDir = (File JavaDoc) retval[0];
127             this.canonicalPath = (String JavaDoc) retval[1];
128         }
129         catch(PrivilegedActionException JavaDoc e)
130         {
131             throw (IOException JavaDoc)e.getException();
132         }
133     }
134     
135     public Object JavaDoc findTemplateSource(final String JavaDoc name)
136     throws
137         IOException JavaDoc
138     {
139         try
140         {
141             return AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc()
142             {
143                 public Object JavaDoc run()
144                 throws
145                     IOException JavaDoc
146                 {
147                     File JavaDoc source = new File JavaDoc(baseDir, SEP_IS_SLASH ? name : name.replace('/', File.separatorChar));
148                     if(!source.isFile()) {
149                         return null;
150                     }
151                     // Security check for inadvertently returning something outside the
152
// template directory.
153
String JavaDoc normalized = source.getCanonicalPath();
154                     if (normalized.startsWith(canonicalPath)) {
155                         return source;
156                     }
157                     throw new SecurityException JavaDoc(normalized + " doesn't start with " + canonicalPath);
158                 }
159             });
160         }
161         catch(PrivilegedActionException JavaDoc e)
162         {
163             throw (IOException JavaDoc)e.getException();
164         }
165     }
166     
167     public long getLastModified(final Object JavaDoc templateSource)
168     {
169         return ((Long JavaDoc)(AccessController.doPrivileged(new PrivilegedAction JavaDoc()
170         {
171             public Object JavaDoc run()
172             {
173                 return new Long JavaDoc(((File JavaDoc)templateSource).lastModified());
174             }
175         }))).longValue();
176         
177         
178     }
179     
180     public Reader JavaDoc getReader(final Object JavaDoc templateSource, final String JavaDoc encoding)
181     throws
182         IOException JavaDoc
183     {
184         try
185         {
186             return (Reader JavaDoc)AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc()
187             {
188                 public Object JavaDoc run()
189                 throws
190                     IOException JavaDoc
191                 {
192                     if (!(templateSource instanceof File JavaDoc)) {
193                         throw new IllegalArgumentException JavaDoc(
194                                 "templateSource is a: " + templateSource.getClass().getName());
195                     }
196                     return new InputStreamReader JavaDoc(new FileInputStream JavaDoc((File JavaDoc) templateSource), encoding);
197                 }
198             });
199         }
200         catch(PrivilegedActionException JavaDoc e)
201         {
202             throw (IOException JavaDoc)e.getException();
203         }
204     }
205     
206     public void closeTemplateSource(Object JavaDoc templateSource)
207     {
208         // Do nothing.
209
}
210 }
Popular Tags