KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > cofax > FilesTemplateLoader


1 /*
2  * FilesTemplateLoader is part of the Cofax content management system library.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * Please see http://www.cofax.org for contact information and other related informaion.
19  *
20  * $Header: /cvsroot/cofax/cofax/src/org/cofax/FilesTemplateLoader.java,v 1.14.2.1 2006/12/11 16:28:44 fxrobin Exp $
21  */

22
23 package org.cofax;
24
25 import java.io.*;
26 import javax.servlet.http.*;
27
28 /**
29  * Locates and loads templates from the file system. A subclass of
30  * <code>TemplateLoader</code>. This is not tied to the
31  * <code>TemplateProcessor</code> being used by Cofax. Any Cofax compatible
32  * <code>TemplateProcessor</code> like <code>WysiwygTemplate</code> can use
33  * this to load templates.
34  * <p>
35  *
36  * There is no mention of the <code>FilesTemplateLoader</code> class in
37  * <code>CofaxServlet</code> . <code>TemplateLoader</code> classes are
38  * listed in the configuration.
39  * </p>
40  *
41  * @author Rajiv Pant
42  * @author Karl Martino
43  * @author Hung Dao
44  * @author Lee Bolding
45  */

46 public class FilesTemplateLoader extends TemplateLoader {
47
48     /**
49      * Walks up the path sent to find the first matching file and returns that
50      * file. It returns an empty string on failure. The templateRoot field must
51      * be set prior to running.
52      *
53      * @param path
54      * Description of the Parameter
55      * @param fileName
56      * Description of the Parameter
57      * @return Description of the Return Value
58      */

59     private String JavaDoc find(String JavaDoc path, String JavaDoc fileName) {
60
61         String JavaDoc templateRoot = getTemplateRoot();
62         int templateMode = getTemplateMode();
63         int templateSearchLimit = getTemplateSearchLimit();
64
65         if (templateSearchLimit > 0) {
66             // Get the path to the *right* of the templateRoot
67
String JavaDoc calcPath = CofaxUtil.replace(path, templateRoot, "") + "/";
68             // Cut path down to simply the templateRoot
69
path = templateRoot;
70             // If the templateSearchLimit is higher then 1....
71
// Note that if it *is* 1, then we are only looking at templateRoot
72
if (templateSearchLimit > 1) {
73                 String JavaDoc newPath = "";
74                 int slashLoc = 0;
75                 for (int x = 0; x < templateSearchLimit - 1; x++) {
76                     slashLoc = calcPath.indexOf("/", slashLoc + 1);
77                     if (slashLoc > -1) {
78                         newPath = calcPath.substring(0, slashLoc);
79                     } else {
80                         break;
81                     }
82                 }
83                 path = path + newPath;
84             }
85         }
86
87         String JavaDoc jspFileName = "";
88         if (templateMode == 0 || templateMode == 2) {
89             int dotLoc = fileName.lastIndexOf('.');
90             if (dotLoc > -1) {
91                 jspFileName = fileName.substring(0, dotLoc);
92                 jspFileName = jspFileName + ".jsp";
93             }
94         }
95
96         String JavaDoc theTemplate;
97         while (true) {
98
99             if (templateMode == 0 || templateMode == 2) {
100                 theTemplate = path + "/" + jspFileName;
101                 if (new File(theTemplate).exists()) {
102                     return theTemplate;
103                 }
104             }
105
106             if (templateMode == 0 || templateMode == 1) {
107                 theTemplate = path + "/" + fileName;
108                 if (new File(theTemplate).exists()) {
109                     return theTemplate;
110                 }
111             }
112
113             if (templateRoot.equals(path)) {
114                 return "";
115             }
116
117             int positionOfLastSlash = path.lastIndexOf('/');
118             if (positionOfLastSlash < 0) {
119                 return "";
120             } else {
121                 path = path.substring(0, positionOfLastSlash);
122             }
123         }
124     }
125
126     // end find(String path, String fileName)
127

128     /**
129      * Gets the template from the file set in templateFileName, from the file
130      * system.
131      *
132      * @param templateFileName
133      * Description of the Parameter
134      * @return Description of the Return Value
135      */

136     public final CofaxPage load(String JavaDoc templateFileName) {
137
138         CofaxPage template = new CofaxPage();
139
140         String JavaDoc line;
141         try {
142             template.reset();
143
144             BufferedReader in = new BufferedReader(new FileReader(templateFileName));
145             while ((line = in.readLine()) != null) {
146                 int incLoc = line.indexOf("<!-- #include file=\"");
147                 if (incLoc > -1) {
148                     int firstQuote = line.indexOf("\"");
149                     int lastQuote = line.indexOf("\"", ++firstQuote);
150                     String JavaDoc fileName = line.substring(firstQuote, lastQuote);
151                     if ((fileName != null) && (!fileName.equals(""))) {
152                         String JavaDoc includeFoundAt = "";
153                         if (fileName.startsWith("/")) {
154                             includeFoundAt = getTemplateRoot() + fileName;
155                         } else {
156                             includeFoundAt = find(getTemplateSearch(), fileName);
157                         }
158                         // remove all the '..' to get the true path to the
159
// template
160
while (includeFoundAt.indexOf("..") > -1) {
161                             int i = includeFoundAt.indexOf("..");
162                             String JavaDoc sub1 = includeFoundAt.substring(0, i - 1);
163                             String JavaDoc sub2 = includeFoundAt.substring(i + 3);
164                             int j = sub1.lastIndexOf("/");
165                             String JavaDoc sub3 = sub1.substring(0, j + 1);
166                             includeFoundAt = sub3 + sub2;
167                         }
168
169                         // test to check if the template is in the template root
170
if (includeFoundAt.indexOf(getTemplateRoot()) > -1) {
171                             if ((includeFoundAt != null) && (!includeFoundAt.equals(""))) {
172                                 try {
173                                     BufferedReader in2 = new BufferedReader(new FileReader(includeFoundAt));
174                                     String JavaDoc line2;
175                                     while ((line2 = in2.readLine()) != null) {
176                                         template.append(line2);
177                                         template.append(CofaxUtil.NEW_LINE);
178                                     }
179                                 } catch (Exception JavaDoc e) {
180                                     System.err.println("FilesTemplateLoader.load(): include file: erreur: " + e);
181                                 }
182                             }
183                         } else {
184                             System.out.println("Access to a forbidden template out of the template root.");
185                         }
186                     }
187                 } else {
188                     template.append(line);
189                 }
190                 template.append(CofaxUtil.NEW_LINE);
191             }
192             in.close();
193
194         } catch (IOException e) {
195             template.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
196             template.setErrorMsg(e.toString());
197         }
198
199         return template;
200     }
201
202     // end load(String templateFileName)
203

204     /**
205      * Chooses a template based on its arguments. Then calls find(...) to locate
206      * it. The templateRoot, defaultIndex, defaultObject, and templateSearch
207      * fields must be set prior to running.
208      *
209      * @param templateFile
210      * Either an empty string, or a specific file to use as a
211      * template.
212      * @param overrideTemplate
213      * Usually an empty string, this is to be used instead of the
214      * templateFile if sent a value.
215      * @return Description of the Return Value
216      */

217     public final String JavaDoc choose(String JavaDoc templateFile, String JavaDoc overrideTemplate, String JavaDoc fileNameExtension) {
218
219         // if fileNameExtension is null (eg if its a section)
220
// then we default to .htm
221
if (fileNameExtension.equals("")) {
222             fileNameExtension = ".htm";
223         }
224
225         String JavaDoc defaultIndex = getDefaultIndex() + fileNameExtension;
226         String JavaDoc alternateIndex = "";
227         String JavaDoc defaultFile = getDefaultObject() + fileNameExtension;
228         String JavaDoc alternateFile = "";
229         String JavaDoc templateSearch = getTemplateSearch();
230         String JavaDoc templateFoundAt;
231
232         // If no file is specified, then we use a list template.
233
// A list template may also be referred to as a section/package digest
234
// template.
235
if ((templateFile.equals("")) && (overrideTemplate.equals(""))) {
236
237             templateFoundAt = find(templateSearch, defaultIndex);
238
239             // Else if a file is specified, then we use a single article
240
// template.
241
} else {
242
243             // For SECURITY, all consecutive periods (..) have been removed from
244
// the overriding template path.
245

246             // If we are told to override the template (for e.g. a
247
// printer-friendly version),
248
// then we select the overriding template.
249
if (!overrideTemplate.equals("")) {
250
251                 // If the overriding template path starts with a /, then it is
252
// considered
253
// to be an absolute path to be appened to the base templatePath
254
// read from
255
// the configuration file.
256

257                 if (overrideTemplate.startsWith("/")) {
258
259                     // Getting a folder and filename part from override template
260
int positionOfLastSlash = overrideTemplate.lastIndexOf('/');
261                     String JavaDoc folderPart = overrideTemplate.substring(0, positionOfLastSlash);
262                     String JavaDoc filePart = overrideTemplate.substring(positionOfLastSlash);
263
264                     templateFoundAt = find(templateSearch + folderPart, filePart);
265
266                     // Otherwise, it is considered relative to the current
267
// "folder".
268
} else {
269
270                     templateFoundAt = find(templateSearch, overrideTemplate);
271                 }
272
273             } else {
274
275                 /*
276                  * Looking for a template specific to this article. TO DO:
277                  * Consider eliminating/adding the pubDate to it. Since this is
278                  * likely to be rare, consider using an overriding template for
279                  * this functionality instead. TO DO: Alternatively, if we want
280                  * to keep article-specific templates, then they should be
281                  * linked to the article based on the "unique article criteria".
282                  * i.e. It should be linked to the pubDate as well. (It is
283                  * already linked to the pubName and section since it is in that
284                  * folder.) Should templates be stored in the database?
285                  */

286
287                 templateFoundAt = find(templateSearch, templateFile);
288
289                 // get the default file
290
if (templateFoundAt.equals("")) {
291                     templateFoundAt = find(templateSearch, defaultFile);
292                 }
293             }
294         }
295
296         return templateFoundAt;
297     }
298
299     // end choose(...)
300

301     /**
302      * Translates a templateId (path) returned by choose() into a resource URI
303      * for inclusion.
304      *
305      * @param templateId
306      * Description of the Parameter
307      * @param applicationPath
308      * Description of the Parameter
309      * @return The resource value
310      */

311     public String JavaDoc getResource(String JavaDoc templateId, String JavaDoc applicationPath) {
312
313         String JavaDoc resourceId = CofaxUtil.replace(templateId, applicationPath, "/");
314
315         return resourceId;
316     }
317
318 }
319
Popular Tags