KickJava   Java API By Example, From Geeks To Geeks.

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


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.ByteArrayInputStream JavaDoc;
15 import java.io.ByteArrayOutputStream JavaDoc;
16 import java.io.IOException JavaDoc;
17 import java.io.InputStreamReader JavaDoc;
18 import java.io.OutputStream JavaDoc;
19 import java.io.OutputStreamWriter JavaDoc;
20 import java.io.PrintWriter JavaDoc;
21 import java.io.Reader JavaDoc;
22 import java.io.Writer JavaDoc;
23 import java.util.regex.Matcher JavaDoc;
24 import java.util.regex.Pattern JavaDoc;
25
26 import javax.servlet.Filter JavaDoc;
27 import javax.servlet.FilterChain JavaDoc;
28 import javax.servlet.FilterConfig JavaDoc;
29 import javax.servlet.ServletException JavaDoc;
30 import javax.servlet.ServletRequest JavaDoc;
31 import javax.servlet.ServletResponse JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34
35 import org.apache.catalina.Globals;
36 /**
37  * Filter to process SSI requests within a webpage. Mapped to a content types
38  * from within web.xml.
39  *
40  * @author David Becker
41  * @version $Revision: 467222 $, $Date: 2006-10-24 05:17:11 +0200 (mar., 24 oct. 2006) $
42  * @see org.apache.catalina.ssi.SSIServlet
43  */

44 public class SSIFilter implements Filter JavaDoc {
45     protected FilterConfig JavaDoc config = null;
46     /** Debug level for this servlet. */
47     protected int debug = 0;
48     /** Expiration time in seconds for the doc. */
49     protected Long JavaDoc expires = null;
50     /** virtual path can be webapp-relative */
51     protected boolean isVirtualWebappRelative = false;
52     /** regex pattern to match when evaluating content types */
53     protected Pattern JavaDoc contentTypeRegEx = null;
54     /** default pattern for ssi filter content type matching */
55     protected Pattern JavaDoc shtmlRegEx =
56         Pattern.compile("text/x-server-parsed-html(;.*)?");
57
58
59     //----------------- Public methods.
60
/**
61      * Initialize this servlet.
62      *
63      * @exception ServletException
64      * if an error occurs
65      */

66     public void init(FilterConfig JavaDoc config) throws ServletException JavaDoc {
67         this.config = config;
68         
69         if (config.getInitParameter("debug") != null) {
70             debug = Integer.parseInt(config.getInitParameter("debug"));
71         }
72
73         if (config.getInitParameter("contentType") != null) {
74             contentTypeRegEx = Pattern.compile(config.getInitParameter("contentType"));
75         } else {
76             contentTypeRegEx = shtmlRegEx;
77         }
78
79         isVirtualWebappRelative =
80             Boolean.parseBoolean(config.getInitParameter("isVirtualWebappRelative"));
81
82         if (config.getInitParameter("expires") != null)
83             expires = Long.valueOf(config.getInitParameter("expires"));
84
85         if (debug > 0)
86             config.getServletContext().log(
87                     "SSIFilter.init() SSI invoker started with 'debug'=" + debug);
88     }
89
90     public void doFilter(ServletRequest JavaDoc request, ServletResponse JavaDoc response,
91             FilterChain JavaDoc chain) throws IOException JavaDoc, ServletException JavaDoc {
92         // cast once
93
HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc)request;
94         HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc)response;
95         
96         // indicate that we're in SSI processing
97
req.setAttribute(Globals.SSI_FLAG_ATTR, "true");
98
99         // setup to capture output
100
ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
101         ResponseIncludeWrapper responseIncludeWrapper =
102             new ResponseIncludeWrapper(config.getServletContext(),req, res, basos);
103
104         // process remainder of filter chain
105
chain.doFilter(req, responseIncludeWrapper);
106
107         // we can't assume the chain flushed its output
108
responseIncludeWrapper.flushOutputStreamOrWriter();
109         byte[] bytes = basos.toByteArray();
110
111         // get content type
112
String JavaDoc contentType = responseIncludeWrapper.getContentType();
113
114         // is this an allowed type for SSI processing?
115
if (contentTypeRegEx.matcher(contentType).matches()) {
116             String JavaDoc encoding = res.getCharacterEncoding();
117
118             // set up SSI processing
119
SSIExternalResolver ssiExternalResolver =
120                 new SSIServletExternalResolver(config.getServletContext(), req,
121                         res, isVirtualWebappRelative, debug, encoding);
122             SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver,
123                     debug);
124             
125             // prepare readers/writers
126
Reader JavaDoc reader =
127                 new InputStreamReader JavaDoc(new ByteArrayInputStream JavaDoc(bytes), encoding);
128             ByteArrayOutputStream JavaDoc ssiout = new ByteArrayOutputStream JavaDoc();
129             PrintWriter JavaDoc writer =
130                 new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(ssiout, encoding));
131             
132             // do SSI processing
133
long lastModified = ssiProcessor.process(reader,
134                     responseIncludeWrapper.getLastModified(), writer);
135             
136             // set output bytes
137
writer.flush();
138             bytes = ssiout.toByteArray();
139             
140             // override headers
141
if (expires != null) {
142                 res.setDateHeader("expires", (new java.util.Date JavaDoc()).getTime()
143                         + expires.longValue() * 1000);
144             }
145             if (lastModified > 0) {
146                 res.setDateHeader("last-modified", lastModified);
147             }
148             res.setContentLength(bytes.length);
149             
150             Matcher JavaDoc shtmlMatcher =
151                 shtmlRegEx.matcher(responseIncludeWrapper.getContentType());
152             if (shtmlMatcher.matches()) {
153                 // Convert shtml mime type to ordinary html mime type but preserve
154
// encoding, if any.
155
String JavaDoc enc = shtmlMatcher.group(1);
156                 res.setContentType("text/html" + ((enc != null) ? enc : ""));
157             }
158         }
159
160         // write output
161
OutputStream JavaDoc out = null;
162         try {
163             out = res.getOutputStream();
164         } catch (IllegalStateException JavaDoc e) {
165             // Ignore, will try to use a writer
166
}
167         if (out == null) {
168             res.getWriter().write(new String JavaDoc(bytes));
169         } else {
170             out.write(bytes);
171         }
172     }
173
174     public void destroy() {
175     }
176 }
177
Popular Tags