1 package org.restafarian.core.filters;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletContext;
9 import javax.servlet.ServletException;
10 import javax.servlet.ServletRequest;
11 import javax.servlet.ServletResponse;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 import org.apache.commons.configuration.Configuration;
16 import org.apache.commons.configuration.ConfigurationException;
17 import org.apache.commons.configuration.ConfigurationFactory;
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20
21 /***
22 * <p>This is the base class for all servlet filters.</p>
23 */
24 public abstract class FilterBase implements Filter {
25 protected ServletContext context = null;
26 protected Log log = LogFactory.getLog(getClass());
27
28 /***
29 * <p>Filter "do filter" method.</p>
30 *
31 * @param req the servlet request object
32 * @param res the servlet response object
33 * @param chain the filter chain object
34 * @throws ServletException
35 * @throws IOException
36 */
37 public abstract void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException;
38
39 /***
40 * <p>Sends the HTTP error code and message, and logs the code and message if enabled.</p>
41 *
42 * @param req the <code>HttpServletRequest</code> object
43 * @param res the <code>HttpServletResponse</code> object
44 * @param errorCode the error code to send
45 * @param errorMessage the error message to send
46 */
47 protected void sendError(HttpServletRequest req, HttpServletResponse res, int errorCode, String errorMessage) throws IOException {
48
49 if (log.isDebugEnabled()) {
50 log.debug("Sending error " + errorCode + "; message=" + errorMessage);
51 }
52
53
54 res.sendError(errorCode, errorMessage);
55 }
56
57 /***
58 * <p>Filter init method.</p>
59 *
60 * @param config the FilterConfig object
61 */
62 public void init(FilterConfig config) {
63 log.info("Initializing " + getClass().getName());
64
65
66 context = config.getServletContext();
67
68
69 String cfgsrc = config.getInitParameter("configFileName");
70 if (cfgsrc != null && cfgsrc.length() > 0) {
71
72 log.info("Configuration source file specified: " + cfgsrc);
73
74 ConfigurationFactory factory = new ConfigurationFactory(cfgsrc);
75 try {
76
77 Configuration configuration = factory.getConfiguration();
78
79 context.setAttribute("configuration", configuration);
80
81 log.info("Configuration loaded using bootstrap file " + cfgsrc);
82 } catch (ConfigurationException e) {
83
84 log.error("Exception encountered when attempting to obtain current configuration: " + e, e);
85 }
86 }
87 }
88
89 /***
90 * <p>Filter destroy method.</p>
91 */
92 public void destroy() {
93 }
94 }