KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > catalina > ssi > SSIMediator


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation. Licensed under the
3  * Apache License, Version 2.0 (the "License"); you may not use this file
4  * except in compliance with the License. You may obtain a copy of the License
5  * at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
6  * law or agreed to in writing, software distributed under the License is
7  * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8  * KIND, either express or implied. See the License for the specific language
9  * governing permissions and limitations under the License.
10  */

11 package org.apache.catalina.ssi;
12
13
14 import java.io.IOException JavaDoc;
15 import java.util.Collection JavaDoc;
16 import java.util.Date JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.Set JavaDoc;
20 import java.util.TimeZone JavaDoc;
21 import org.apache.catalina.util.DateTool;
22 import org.apache.catalina.util.Strftime;
23 import org.apache.catalina.util.URLEncoder;
24 /**
25  * Allows the different SSICommand implementations to share data/talk to each
26  * other
27  *
28  * @author Bip Thelin
29  * @author Amy Roh
30  * @author Paul Speed
31  * @author Dan Sandberg
32  * @author David Becker
33  * @version $Revision: 467222 $, $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
34  */

35 public class SSIMediator {
36     protected final static String JavaDoc DEFAULT_CONFIG_ERR_MSG = "[an error occurred while processing this directive]";
37     protected final static String JavaDoc DEFAULT_CONFIG_TIME_FMT = "%A, %d-%b-%Y %T %Z";
38     protected final static String JavaDoc DEFAULT_CONFIG_SIZE_FMT = "abbrev";
39     protected static URLEncoder urlEncoder;
40     protected String JavaDoc configErrMsg = DEFAULT_CONFIG_ERR_MSG;
41     protected String JavaDoc configTimeFmt = DEFAULT_CONFIG_TIME_FMT;
42     protected String JavaDoc configSizeFmt = DEFAULT_CONFIG_SIZE_FMT;
43     protected String JavaDoc className = getClass().getName();
44     protected SSIExternalResolver ssiExternalResolver;
45     protected long lastModifiedDate;
46     protected int debug;
47     protected Strftime strftime;
48     protected SSIConditionalState conditionalState = new SSIConditionalState();
49     static {
50         //We try to encode only the same characters that apache does
51
urlEncoder = new URLEncoder();
52         urlEncoder.addSafeCharacter(',');
53         urlEncoder.addSafeCharacter(':');
54         urlEncoder.addSafeCharacter('-');
55         urlEncoder.addSafeCharacter('_');
56         urlEncoder.addSafeCharacter('.');
57         urlEncoder.addSafeCharacter('*');
58         urlEncoder.addSafeCharacter('/');
59         urlEncoder.addSafeCharacter('!');
60         urlEncoder.addSafeCharacter('~');
61         urlEncoder.addSafeCharacter('\'');
62         urlEncoder.addSafeCharacter('(');
63         urlEncoder.addSafeCharacter(')');
64     }
65
66
67     public SSIMediator(SSIExternalResolver ssiExternalResolver,
68             long lastModifiedDate, int debug) {
69         this.ssiExternalResolver = ssiExternalResolver;
70         this.lastModifiedDate = lastModifiedDate;
71         this.debug = debug;
72         setConfigTimeFmt(DEFAULT_CONFIG_TIME_FMT, true);
73     }
74
75
76     public void setConfigErrMsg(String JavaDoc configErrMsg) {
77         this.configErrMsg = configErrMsg;
78     }
79
80
81     public void setConfigTimeFmt(String JavaDoc configTimeFmt) {
82         setConfigTimeFmt(configTimeFmt, false);
83     }
84
85
86     public void setConfigTimeFmt(String JavaDoc configTimeFmt, boolean fromConstructor) {
87         this.configTimeFmt = configTimeFmt;
88         //What's the story here with DateTool.LOCALE_US?? Why??
89
this.strftime = new Strftime(configTimeFmt, DateTool.LOCALE_US);
90         //Variables like DATE_LOCAL, DATE_GMT, and LAST_MODIFIED need to be
91
// updated when
92
//the timefmt changes. This is what Apache SSI does.
93
setDateVariables(fromConstructor);
94     }
95
96
97     public void setConfigSizeFmt(String JavaDoc configSizeFmt) {
98         this.configSizeFmt = configSizeFmt;
99     }
100
101
102     public String JavaDoc getConfigErrMsg() {
103         return configErrMsg;
104     }
105
106
107     public String JavaDoc getConfigTimeFmt() {
108         return configTimeFmt;
109     }
110
111
112     public String JavaDoc getConfigSizeFmt() {
113         return configSizeFmt;
114     }
115
116
117     public SSIConditionalState getConditionalState() {
118         return conditionalState;
119     }
120
121
122     public Collection JavaDoc getVariableNames() {
123         Set JavaDoc variableNames = new HashSet JavaDoc();
124         //These built-in variables are supplied by the mediator ( if not
125
// over-written by
126
// the user ) and always exist
127
variableNames.add("DATE_GMT");
128         variableNames.add("DATE_LOCAL");
129         variableNames.add("LAST_MODIFIED");
130         ssiExternalResolver.addVariableNames(variableNames);
131         //Remove any variables that are reserved by this class
132
Iterator JavaDoc iter = variableNames.iterator();
133         while (iter.hasNext()) {
134             String JavaDoc name = (String JavaDoc)iter.next();
135             if (isNameReserved(name)) {
136                 iter.remove();
137             }
138         }
139         return variableNames;
140     }
141
142
143     public long getFileSize(String JavaDoc path, boolean virtual) throws IOException JavaDoc {
144         return ssiExternalResolver.getFileSize(path, virtual);
145     }
146
147
148     public long getFileLastModified(String JavaDoc path, boolean virtual)
149             throws IOException JavaDoc {
150         return ssiExternalResolver.getFileLastModified(path, virtual);
151     }
152
153
154     public String JavaDoc getFileText(String JavaDoc path, boolean virtual) throws IOException JavaDoc {
155         return ssiExternalResolver.getFileText(path, virtual);
156     }
157
158
159     protected boolean isNameReserved(String JavaDoc name) {
160         return name.startsWith(className + ".");
161     }
162
163
164     public String JavaDoc getVariableValue(String JavaDoc variableName) {
165         return getVariableValue(variableName, "none");
166     }
167
168
169     public void setVariableValue(String JavaDoc variableName, String JavaDoc variableValue) {
170         if (!isNameReserved(variableName)) {
171             ssiExternalResolver.setVariableValue(variableName, variableValue);
172         }
173     }
174
175
176     public String JavaDoc getVariableValue(String JavaDoc variableName, String JavaDoc encoding) {
177         String JavaDoc lowerCaseVariableName = variableName.toLowerCase();
178         String JavaDoc variableValue = null;
179         if (!isNameReserved(lowerCaseVariableName)) {
180             //Try getting it externally first, if it fails, try getting the
181
// 'built-in'
182
// value
183
variableValue = ssiExternalResolver.getVariableValue(variableName);
184             if (variableValue == null) {
185                 variableName = variableName.toUpperCase();
186                 variableValue = (String JavaDoc)ssiExternalResolver
187                         .getVariableValue(className + "." + variableName);
188             }
189             if (variableValue != null) {
190                 variableValue = encode(variableValue, encoding);
191             }
192         }
193         return variableValue;
194     }
195
196
197     /**
198      * Applies variable substitution to the specified String and returns the
199      * new resolved string.
200      */

201     public String JavaDoc substituteVariables(String JavaDoc val) {
202         // If it has no variable references then no work
203
// need to be done
204
if (val.indexOf('$') < 0) return val;
205         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(val);
206         for (int i = 0; i < sb.length();) {
207             // Find the next $
208
for (; i < sb.length(); i++) {
209                 if (sb.charAt(i) == '$') {
210                     i++;
211                     break;
212                 }
213             }
214             if (i == sb.length()) break;
215             // Check to see if the $ is escaped
216
if (i > 1 && sb.charAt(i - 2) == '\\') {
217                 sb.deleteCharAt(i - 2);
218                 i--;
219                 continue;
220             }
221             int nameStart = i;
222             int start = i - 1;
223             int end = -1;
224             int nameEnd = -1;
225             char endChar = ' ';
226             // Check for {} wrapped var
227
if (sb.charAt(i) == '{') {
228                 nameStart++;
229                 endChar = '}';
230             }
231             // Find the end of the var reference
232
for (; i < sb.length(); i++) {
233                 if (sb.charAt(i) == endChar) break;
234             }
235             end = i;
236             nameEnd = end;
237             if (endChar == '}') end++;
238             // We should now have enough to extract the var name
239
String JavaDoc varName = sb.substring(nameStart, nameEnd);
240             String JavaDoc value = getVariableValue(varName);
241             if (value == null) value = "";
242             // Replace the var name with its value
243
sb.replace(start, end, value);
244             // Start searching for the next $ after the value
245
// that was just substituted.
246
i = start + value.length();
247         }
248         return sb.toString();
249     }
250
251
252     protected String JavaDoc formatDate(Date JavaDoc date, TimeZone JavaDoc timeZone) {
253         String JavaDoc retVal;
254         if (timeZone != null) {
255             //we temporarily change strftime. Since SSIMediator is inherently
256
// single-threaded, this
257
//isn't a problem
258
TimeZone JavaDoc oldTimeZone = strftime.getTimeZone();
259             strftime.setTimeZone(timeZone);
260             retVal = strftime.format(date);
261             strftime.setTimeZone(oldTimeZone);
262         } else {
263             retVal = strftime.format(date);
264         }
265         return retVal;
266     }
267
268
269     protected String JavaDoc encode(String JavaDoc value, String JavaDoc encoding) {
270         String JavaDoc retVal = null;
271         if (encoding.equalsIgnoreCase("url")) {
272             retVal = urlEncoder.encode(value);
273         } else if (encoding.equalsIgnoreCase("none")) {
274             retVal = value;
275         } else if (encoding.equalsIgnoreCase("entity")) {
276             //Not sure how this is really different than none
277
retVal = value;
278         } else {
279             //This shouldn't be possible
280
throw new IllegalArgumentException JavaDoc("Unknown encoding: " + encoding);
281         }
282         return retVal;
283     }
284
285
286     public void log(String JavaDoc message) {
287         ssiExternalResolver.log(message, null);
288     }
289
290
291     public void log(String JavaDoc message, Throwable JavaDoc throwable) {
292         ssiExternalResolver.log(message, throwable);
293     }
294
295
296     protected void setDateVariables(boolean fromConstructor) {
297         boolean alreadySet = ssiExternalResolver.getVariableValue(className
298                 + ".alreadyset") != null;
299         //skip this if we are being called from the constructor, and this has
300
// already
301
// been set
302
if (!(fromConstructor && alreadySet)) {
303             ssiExternalResolver.setVariableValue(className + ".alreadyset",
304                     "true");
305             Date JavaDoc date = new Date JavaDoc();
306             TimeZone JavaDoc timeZone = TimeZone.getTimeZone("GMT");
307             String JavaDoc retVal = formatDate(date, timeZone);
308             //If we are setting on of the date variables, we want to remove
309
// them from the
310
// user
311
//defined list of variables, because this is what Apache does
312
setVariableValue("DATE_GMT", null);
313             ssiExternalResolver.setVariableValue(className + ".DATE_GMT",
314                     retVal);
315             retVal = formatDate(date, null);
316             setVariableValue("DATE_LOCAL", null);
317             ssiExternalResolver.setVariableValue(className + ".DATE_LOCAL",
318                     retVal);
319             retVal = formatDate(new Date JavaDoc(lastModifiedDate), null);
320             setVariableValue("LAST_MODIFIED", null);
321             ssiExternalResolver.setVariableValue(className + ".LAST_MODIFIED",
322                     retVal);
323         }
324     }
325 }
Popular Tags