KickJava   Java API By Example, From Geeks To Geeks.

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


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  * FeedFilter
48  *
49  * @author David Czarnecki
50  * @since blojsom 3.0
51  * @version $Id: FeedFilter.java,v 1.1 2006/03/20 21:31:15 czarneckid Exp $
52  */

53 public class FeedFilter implements Filter {
54
55     private static final Log _logger = LogFactory.getLog(FeedFilter.class);
56
57     private static final String JavaDoc FEED_WITH_TYPE_REGEX = "/feed/(.+)/$";
58     private static final Pattern JavaDoc FEED_WITH_TYPE_PATTERN = Pattern.compile(FEED_WITH_TYPE_REGEX, Pattern.UNICODE_CASE);
59     private static final String JavaDoc FEED_NO_TYPE_REGEX = "/feed/$";
60     private static final Pattern JavaDoc FEED_NO_TYPE_PATTERN = Pattern.compile(FEED_NO_TYPE_REGEX, Pattern.UNICODE_CASE);
61     private static final String JavaDoc DEFAULT_FEED_TYPE = "rss2";
62     private static final String JavaDoc DEFAULT_FEED_TYPE_IP = "default-feed-type";
63     private static final String JavaDoc PERMALINK_EXTENSIONS_IP = "permalink-extensions";
64     private static final String JavaDoc[] DEFAULT_PERMALINK_EXTENSIONS = {".html", ".txt"};
65
66     private String JavaDoc _defaultFeedType = DEFAULT_FEED_TYPE;
67     private String JavaDoc[] _permalinkExtensions;
68
69     /**
70      * Construct a new instance of the Feed filter
71      */

72     public FeedFilter() {
73     }
74
75     /**
76      * Initialize the filter
77      *
78      * @param filterConfig {@link FilterConfig}
79      * @throws ServletException If there is an error initializing the filter
80      */

81     public void init(FilterConfig filterConfig) throws ServletException {
82         String JavaDoc defaultFeedType = filterConfig.getInitParameter(DEFAULT_FEED_TYPE_IP);
83         if (!BlojsomUtils.checkNullOrBlank(defaultFeedType)) {
84             _defaultFeedType = defaultFeedType;
85         }
86
87         _permalinkExtensions = DEFAULT_PERMALINK_EXTENSIONS;
88         String JavaDoc permalinkExtensions = filterConfig.getInitParameter(PERMALINK_EXTENSIONS_IP);
89         if (!BlojsomUtils.checkNullOrBlank(permalinkExtensions)) {
90             _permalinkExtensions = BlojsomUtils.parseOnlyCommaList(permalinkExtensions, true);
91         }
92
93         _logger.debug("Initialized feed filter using default feed type: " + _defaultFeedType);
94     }
95
96     /**
97      * Remove the filter from service
98      */

99     public void destroy() {
100     }
101
102     /**
103      * Process the request.
104      * <p/>
105      * Processes requests of the form
106      * <ul>
107      * </ul>
108      *
109      * @param request {@link ServletRequest}
110      * @param response {@link ServletResponse}
111      * @param chain {@link FilterChain} to execute
112      * @throws IOException If there is an error executing the filter
113      * @throws ServletException If there is an error executing the filter
114      */

115     public void doFilter(ServletRequest JavaDoc request, ServletResponse response, FilterChain chain) throws IOException JavaDoc, ServletException {
116         request.setCharacterEncoding(BlojsomConstants.UTF8);
117
118         HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc) request;
119         String JavaDoc uri = hreq.getRequestURI();
120         StringBuffer JavaDoc url = hreq.getRequestURL();
121         String JavaDoc pathInfo = hreq.getPathInfo();
122         if (BlojsomUtils.checkNullOrBlank(pathInfo)) {
123             pathInfo = "/";
124         }
125
126         _logger.debug("Handling feed filter request: " + pathInfo);
127
128         Matcher JavaDoc feedWithTypeMatcher = FEED_WITH_TYPE_PATTERN.matcher(pathInfo);
129         Matcher JavaDoc feedNoTypeMatcher = FEED_NO_TYPE_PATTERN.matcher(pathInfo);
130         Map extraParameters;
131
132         if (feedWithTypeMatcher.find()) {
133             String JavaDoc feedType = feedWithTypeMatcher.group(1);
134
135             extraParameters = new HashMap();
136             extraParameters.put("flavor", new String JavaDoc[] {feedType});
137
138             String JavaDoc feedTypeSubstring = "/feed/" + feedType + "/";
139             int feedTypeIndex = pathInfo.lastIndexOf(feedTypeSubstring) + 1;
140             String JavaDoc pathinfo = pathInfo.substring(0, feedTypeIndex);
141             boolean matchedPermalink = false;
142             for (int i = 0; i < _permalinkExtensions.length; i++) {
143                 String JavaDoc defaultPermalinkExtension = _permalinkExtensions[i];
144
145                 if (pathinfo.endsWith(defaultPermalinkExtension + "/")) {
146                     matchedPermalink = true;
147                     break;
148                 }
149             }
150
151             feedTypeIndex = uri.lastIndexOf(feedTypeSubstring);
152             String JavaDoc URI = uri.substring(0, feedTypeIndex);
153             feedTypeIndex = url.lastIndexOf(feedTypeSubstring);
154             String JavaDoc URL = url.substring(0, feedTypeIndex);
155
156             if (matchedPermalink) {
157                 pathinfo = pathinfo.substring(0, pathinfo.length() - 1);
158             } else {
159                 URI += "/";
160                 URL += "/";
161             }
162
163             _logger.debug("Handling feed type: " + feedType + " with path info: " + pathinfo + " URI: " + URI + " URL: " + URL);
164             hreq = new FeedPermalinkRequst(hreq, extraParameters, URI, URL, pathinfo);
165         } else if (feedNoTypeMatcher.find()) {
166             extraParameters = new HashMap();
167             extraParameters.put("flavor", new String JavaDoc[]{_defaultFeedType});
168
169             String JavaDoc feedTypeSubstring = "/feed/";
170             int feedTypeIndex = pathInfo.lastIndexOf(feedTypeSubstring) + 1;
171             String JavaDoc pathinfo = pathInfo.substring(0, feedTypeIndex);
172             boolean matchedPermalink = false;
173             for (int i = 0; i < DEFAULT_PERMALINK_EXTENSIONS.length; i++) {
174                 String JavaDoc defaultPermalinkExtension = DEFAULT_PERMALINK_EXTENSIONS[i];
175
176                 if (pathinfo.endsWith(defaultPermalinkExtension + "/")) {
177                     matchedPermalink = true;
178                     break;
179                 }
180             }
181
182             feedTypeIndex = uri.lastIndexOf(feedTypeSubstring);
183             String JavaDoc URI = uri.substring(0, feedTypeIndex);
184             feedTypeIndex = url.lastIndexOf(feedTypeSubstring);
185             String JavaDoc URL = url.substring(0, feedTypeIndex);
186
187             if (matchedPermalink) {
188                 pathinfo = pathinfo.substring(0, pathinfo.length() - 1);
189             } else {
190                 URI += "/";
191                 URL += "/";
192             }
193
194             _logger.debug("Handling default feed type: " + _defaultFeedType + " with path info: " + pathinfo + " URI: " + URI + " URL: " + URL);
195             hreq = new FeedPermalinkRequst(hreq, extraParameters, URI, URL, pathinfo);
196         }
197
198         chain.doFilter(hreq, response);
199     }
200
201     /**
202      * Feed request
203      */

204     public class FeedPermalinkRequst extends HttpServletRequestWrapper JavaDoc {
205
206         private Map params;
207         private String JavaDoc uri;
208         private String JavaDoc url;
209         private String JavaDoc pathInfo;
210
211         /**
212          *
213          * @param httpServletRequest
214          * @param params
215          * @param uri
216          * @param url
217          * @param pathInfo
218          */

219         public FeedPermalinkRequst(HttpServletRequest JavaDoc httpServletRequest, Map params, String JavaDoc uri, String JavaDoc url, String JavaDoc pathInfo) {
220             super(httpServletRequest);
221
222             Map updatedParams = new HashMap(httpServletRequest.getParameterMap());
223             Iterator keys = params.keySet().iterator();
224             while (keys.hasNext())
225
226             {
227                 Object JavaDoc o = keys.next();
228                 updatedParams.put(o, params.get(o));
229             }
230
231             this.params = Collections.unmodifiableMap(updatedParams);
232             this.uri = uri;
233             this.url = url;
234             this.pathInfo = pathInfo;
235         }
236
237         /**
238          * Return the request URI
239          *
240          * @return Request URI
241          */

242         public String JavaDoc getRequestURI() {
243             return uri;
244         }
245
246         /**
247          * Return the request URL
248          *
249          * @return Request URL
250          */

251         public StringBuffer JavaDoc getRequestURL() {
252             return new StringBuffer JavaDoc(url);
253         }
254
255         /**
256          * Return the path information
257          *
258          * @return Path information
259          */

260         public String JavaDoc getPathInfo() {
261             return pathInfo;
262         }
263
264         /**
265          * Retrieve a named parameter
266          *
267          * @param name Parameter to retrieve
268          * @return Parameter value or <code>null</code> if the parameter is not found
269          */

270         public String JavaDoc getParameter(String JavaDoc name) {
271             String JavaDoc[] values = getParameterValues(name);
272             return (values != null) ? values[0] : null;
273         }
274
275         /**
276          * Retrieve the map of parameters
277          *
278          * @return Parameter map
279          */

280         public Map getParameterMap() {
281             return params;
282         }
283
284         /**
285          * Retrieve the parameter names
286          *
287          * @return {@link java.util.Enumeration} of parameter names
288          */

289         public Enumeration getParameterNames() {
290             return Collections.enumeration(params.keySet());
291         }
292
293         /**
294          * Retrieve a parameter value as a <code>String[]</code>
295          *
296          * @param name Parameter name
297          * @return Parameter value as <code>String[]</code> or <code>null</code> if the parameter is not found
298          */

299         public String JavaDoc[] getParameterValues(String JavaDoc name) {
300             return (String JavaDoc[]) params.get(name);
301         }
302
303         /**
304          * Set the path information for the request
305          *
306          * @param pathInfo New path information
307          */

308         public void setPathInfo(String JavaDoc pathInfo) {
309             this.pathInfo = pathInfo;
310         }
311     }
312 }
313
Popular Tags