KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > filter > PageFilter


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.filter;
32
33 import org.blojsom.util.BlojsomConstants;
34 import org.blojsom.util.BlojsomUtils;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37
38 import javax.servlet.*;
39 import javax.servlet.http.HttpServletRequest JavaDoc;
40 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
41 import java.io.IOException JavaDoc;
42 import java.util.regex.Pattern JavaDoc;
43 import java.util.regex.Matcher JavaDoc;
44 import java.util.*;
45
46 /**
47  * Page filter supports URLs of the form <code>/[blojsom context]/[blojsom servlet mapping]/[blog ID]/[page name]/page/</code>. For example,
48  * <code>/blojsom/blog/default/about/page/</code> would try and pull the <code>about.vm</code> template from the <code>default</code> blog's
49  * <code>templates</code> directory.
50  * <p></p>
51  * Usage:<br/>
52  * <pre>
53  * <filter>
54  * <filter-name>PageFilter</filter-name>
55  * <filter-class>org.blojsom.filter.PageFilter</filter-class>
56  * <init-param>
57  * <param-name>use-root-blog-compatability</param-name>
58  * <param-value>false</param-value>
59  * </init-param>
60  * </filter>
61  *
62  * <filter-mapping>
63  * <filter-name>PageFilter</filter-name></pre>
64  * <servlet-name>blojsom</servlet-name>
65  * </filter-mapping>
66  * </pre>
67  *
68  * For the page filter to be used, it must be mapped before the permalink filter.
69  *
70  * @author David Czarnecki
71  * @since blojsom 3.0
72  * @version PageFilter.java,v 1.1 2005/12/19 20:04:29 czarneckid Exp
73  */

74 public class PageFilter implements Filter {
75
76     private static final Log _logger = LogFactory.getLog(PageFilter.class);
77     private static final String JavaDoc PAGE_PATHINFO = "/page/";
78     private static final String JavaDoc PAGE_REGEX = PAGE_PATHINFO + "$";
79     private static final Pattern JavaDoc PAGE_PATTERN = Pattern.compile(PAGE_REGEX, Pattern.UNICODE_CASE);
80     private static final String JavaDoc USE_ROOT_BLOG_COMPATABILITY_IP = "use-root-blog-compatability";
81     private static final boolean USE_ROOT_BLOG_COMPATABILITY_DEFAULT = false;
82
83     private boolean _useRootBlogCompatability = USE_ROOT_BLOG_COMPATABILITY_DEFAULT;
84
85     /**
86      * Construct a new instance of the Feed filter
87      */

88     public PageFilter() {
89     }
90
91     /**
92      * Initialize the filter
93      *
94      * @param filterConfig {@link FilterConfig}
95      * @throws ServletException If there is an error initializing the filter
96      */

97     public void init(FilterConfig filterConfig) throws ServletException {
98         _useRootBlogCompatability = Boolean.valueOf(filterConfig.getInitParameter(USE_ROOT_BLOG_COMPATABILITY_IP)).booleanValue();
99
100         _logger.debug("Initialized page filter (Root blog compatability: " + _useRootBlogCompatability + ")");
101     }
102
103     /**
104      * Remove the filter from service
105      */

106     public void destroy() {
107     }
108
109     /**
110      * Process the request.
111      * <p/>
112      * Processes requests of the form
113      * <ul>
114      * </ul>
115      *
116      * @param request {@link ServletRequest}
117      * @param response {@link ServletResponse}
118      * @param chain {@link FilterChain} to execute
119      * @throws IOException If there is an error executing the filter
120      * @throws ServletException If there is an error executing the filter
121      */

122     public void doFilter(ServletRequest JavaDoc request, ServletResponse response, FilterChain chain) throws IOException JavaDoc, ServletException {
123         request.setCharacterEncoding(BlojsomConstants.UTF8);
124
125         HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc) request;
126         String JavaDoc uri = hreq.getRequestURI();
127         StringBuffer JavaDoc url = hreq.getRequestURL();
128         String JavaDoc pathInfo = hreq.getPathInfo();
129         if (BlojsomUtils.checkNullOrBlank(pathInfo)) {
130             pathInfo = "/";
131         }
132
133         _logger.debug("Handling page filter request: " + pathInfo);
134
135         Matcher JavaDoc pageMatcher = PAGE_PATTERN.matcher(pathInfo);
136         Map extraParameters;
137
138         if (pageMatcher.find()) {
139             int pageMatchIndex = pageMatcher.start();
140             String JavaDoc blogIDPathInfo = null;
141
142             if (!_useRootBlogCompatability) {
143                 int firstSlashAfterBlogID = pathInfo.substring(1).indexOf("/");
144                 blogIDPathInfo = pathInfo.substring(0, firstSlashAfterBlogID + 1) + "/";
145                 pathInfo = pathInfo.substring(firstSlashAfterBlogID + 1, pageMatchIndex);
146             } else {
147                 pathInfo = pathInfo.substring(0, pageMatchIndex);
148             }
149
150             pageMatchIndex = uri.lastIndexOf(PAGE_PATHINFO);
151             String JavaDoc URI = uri.substring(0, pageMatchIndex) + "/";
152             pageMatchIndex = url.lastIndexOf(PAGE_PATHINFO);
153             String JavaDoc URL = url.substring(0, pageMatchIndex) + "/";
154
155             extraParameters = new HashMap();
156             extraParameters.put("page", new String JavaDoc[]{pathInfo});
157             pathInfo = "/";
158
159             if (!_useRootBlogCompatability) {
160                 pathInfo = blogIDPathInfo;
161             }
162
163             hreq = new PagePermalinkRequst(hreq, extraParameters, URI, URL, pathInfo);
164             _logger.debug("Handling pathinfo: " + pathInfo + " uri: " + URI + " url: " + URL);
165         }
166
167         chain.doFilter(hreq, response);
168     }
169
170     /**
171      * Page request
172      */

173     public class PagePermalinkRequst extends HttpServletRequestWrapper JavaDoc {
174
175         private Map params;
176         private String JavaDoc uri;
177         private String JavaDoc url;
178         private String JavaDoc pathInfo;
179
180         /**
181          * @param httpServletRequest
182          * @param params
183          * @param uri
184          * @param url
185          * @param pathInfo
186          */

187         public PagePermalinkRequst(HttpServletRequest JavaDoc httpServletRequest, Map params, String JavaDoc uri, String JavaDoc url, String JavaDoc pathInfo) {
188             super(httpServletRequest);
189
190             Map updatedParams = new HashMap(httpServletRequest.getParameterMap());
191             Iterator keys = params.keySet().iterator();
192             while (keys.hasNext()) {
193                 Object JavaDoc o = keys.next();
194                 updatedParams.put(o, params.get(o));
195             }
196
197             this.params = Collections.unmodifiableMap(updatedParams);
198             this.uri = uri;
199             this.url = url;
200             this.pathInfo = pathInfo;
201         }
202
203         /**
204          * Return the request URI
205          *
206          * @return Request URI
207          */

208         public String JavaDoc getRequestURI() {
209             return uri;
210         }
211
212         /**
213          * Return the request URL
214          *
215          * @return Request URL
216          */

217         public StringBuffer JavaDoc getRequestURL() {
218             return new StringBuffer JavaDoc(url);
219         }
220
221         /**
222          * Return the path information
223          *
224          * @return Path information
225          */

226         public String JavaDoc getPathInfo() {
227             return pathInfo;
228         }
229
230         /**
231          * Retrieve a named parameter
232          *
233          * @param name Parameter to retrieve
234          * @return Parameter value or <code>null</code> if the parameter is not found
235          */

236         public String JavaDoc getParameter(String JavaDoc name) {
237             String JavaDoc[] values = getParameterValues(name);
238             return (values != null) ? values[0] : null;
239         }
240
241         /**
242          * Retrieve the map of parameters
243          *
244          * @return Parameter map
245          */

246         public Map getParameterMap() {
247             return params;
248         }
249
250         /**
251          * Retrieve the parameter names
252          *
253          * @return {@link java.util.Enumeration} of parameter names
254          */

255         public Enumeration getParameterNames() {
256             return Collections.enumeration(params.keySet());
257         }
258
259         /**
260          * Retrieve a parameter value as a <code>String[]</code>
261          *
262          * @param name Parameter name
263          * @return Parameter value as <code>String[]</code> or <code>null</code> if the parameter is not found
264          */

265         public String JavaDoc[] getParameterValues(String JavaDoc name) {
266             return (String JavaDoc[]) params.get(name);
267         }
268
269         /**
270          * Set the path information for the request
271          *
272          * @param pathInfo New path information
273          */

274         public void setPathInfo(String JavaDoc pathInfo) {
275             this.pathInfo = pathInfo;
276         }
277     }
278 }
279
Popular Tags