Coverage Report - org.kuali.rice.kew.web.BootstrapFilter
 
Classes in this File Line Coverage Branch Coverage Complexity
BootstrapFilter
0%
0/103
0%
0/74
2.929
BootstrapFilterChain
0%
0/16
0%
0/4
2.929
BootstrapFilterConfig
0%
0/17
N/A
2.929
FilterMapping
0%
0/10
N/A
2.929
 
 1  
 /**
 2  
  * Copyright 2005-2011 The Kuali Foundation
 3  
  *
 4  
  * Licensed under the Educational Community License, Version 2.0 (the "License");
 5  
  * you may not use this file except in compliance with the License.
 6  
  * You may obtain a copy of the License at
 7  
  *
 8  
  * http://www.opensource.org/licenses/ecl2.php
 9  
  *
 10  
  * Unless required by applicable law or agreed to in writing, software
 11  
  * distributed under the License is distributed on an "AS IS" BASIS,
 12  
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  
  * See the License for the specific language governing permissions and
 14  
  * limitations under the License.
 15  
  */
 16  
 package org.kuali.rice.kew.web;
 17  
 
 18  
 import org.apache.log4j.Logger;
 19  
 import org.kuali.rice.core.api.config.property.Config;
 20  
 import org.kuali.rice.core.api.config.property.ConfigContext;
 21  
 import org.kuali.rice.core.api.reflect.ObjectDefinition;
 22  
 import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
 23  
 import org.kuali.rice.core.api.util.ClassLoaderUtils;
 24  
 
 25  
 import javax.servlet.Filter;
 26  
 import javax.servlet.FilterChain;
 27  
 import javax.servlet.FilterConfig;
 28  
 import javax.servlet.ServletContext;
 29  
 import javax.servlet.ServletException;
 30  
 import javax.servlet.ServletRequest;
 31  
 import javax.servlet.ServletResponse;
 32  
 import javax.servlet.http.HttpServletRequest;
 33  
 import java.io.IOException;
 34  
 import java.util.Collections;
 35  
 import java.util.Enumeration;
 36  
 import java.util.HashMap;
 37  
 import java.util.Iterator;
 38  
 import java.util.LinkedList;
 39  
 import java.util.List;
 40  
 import java.util.Map;
 41  
 import java.util.SortedSet;
 42  
 import java.util.TreeSet;
 43  
 
 44  
 /**
 45  
  * A filter which at runtime reads a series of filter configurations, constructs
 46  
  * and initializes those filters, and invokes them when it is invoked. This
 47  
  * allows runtime user configuration of arbitrary filters in the webapp context.
 48  
  *
 49  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 50  
  */
 51  0
 public class BootstrapFilter implements Filter {
 52  0
         private static final Logger LOG = Logger.getLogger(BootstrapFilter.class);
 53  
 
 54  
         private static final String FILTER_PREFIX = "filter.";
 55  
 
 56  
         private static final String CLASS_SUFFIX = ".class";
 57  
 
 58  
         private static final String FILTER_MAPPING_PREFIX = "filtermapping.";
 59  
 
 60  
         private FilterConfig config;
 61  
 
 62  0
         private final Map<String, Filter> filters = new HashMap<String, Filter>();
 63  
 
 64  0
         private final SortedSet<FilterMapping> filterMappings = new TreeSet<FilterMapping>();
 65  
 
 66  0
         private boolean initted = false;
 67  
 
 68  
         public void init(FilterConfig cfg) throws ServletException {
 69  0
                 this.config = cfg;
 70  0
         }
 71  
 
 72  
         private void addFilter(String name, String classname, Map<String, String> props) throws ServletException {
 73  0
                 LOG.debug("Adding filter: " + name + "=" + classname);
 74  0
                 Object filterObject = GlobalResourceLoader.getResourceLoader().getObject(new ObjectDefinition(classname));
 75  0
                 if (filterObject == null) {
 76  0
                         throw new ServletException("Filter '" + name + "' class not found: " + classname);
 77  
 
 78  
                 }
 79  0
                 if (!(filterObject instanceof Filter)) {
 80  0
                         LOG.error("Class '" + filterObject.getClass() + "' does not implement servlet javax.servlet.Filter");
 81  0
                         return;
 82  
                 }
 83  0
                 Filter filter = (Filter) filterObject;
 84  0
                 BootstrapFilterConfig fc = new BootstrapFilterConfig(config.getServletContext(), name);
 85  0
                 for (Map.Entry<String, String> entry : props.entrySet()) {
 86  0
                         String key = entry.getKey().toString();
 87  0
                         final String prefix = FILTER_PREFIX + name + ".";
 88  0
                         if (!key.startsWith(prefix) || key.equals(FILTER_PREFIX + name + CLASS_SUFFIX)) {
 89  0
                                 continue;
 90  
                         }
 91  0
                         String paramName = key.substring(prefix.length());
 92  0
                         fc.addInitParameter(paramName, entry.getValue());
 93  0
                 }
 94  
                 try {
 95  0
                         filter.init(fc);
 96  0
                         filters.put(name, filter);
 97  0
                 } catch (ServletException se) {
 98  0
                         LOG.error("Error initializing filter: " + name + " [" + classname + "]", se);
 99  0
                 }
 100  0
         }
 101  
 
 102  
         private void addFilterMapping(String filterName, String orderNumber, String value) {
 103  0
                 filterMappings.add(new FilterMapping(filterName, orderNumber, value));
 104  0
         }
 105  
 
 106  
         private synchronized void init() throws ServletException {
 107  0
                 if (initted) {
 108  0
                         return;
 109  
                 }
 110  0
                 LOG.debug("initializing...");
 111  0
                 Config cfg = ConfigContext.getCurrentContextConfig();
 112  
                 
 113  
                 @SuppressWarnings({ "unchecked", "rawtypes" })
 114  0
                 final Map<String, String> p = new HashMap<String, String>((Map) cfg.getProperties());
 115  
                 
 116  0
                 for (Map.Entry<String, String> entry : p.entrySet()) {
 117  0
                         String key = entry.getKey().toString();
 118  0
                         if (key.startsWith(FILTER_MAPPING_PREFIX)) {
 119  0
                                 String[] values = key.split("\\.");
 120  0
                                 if (values.length != 2 && values.length != 3) {
 121  0
                                         throw new ServletException("Invalid filter mapping defined.  Should contain 2 or 3 pieces in the form of filtermapping.<<filter name>>.<<order number>> with the last piece optional.");
 122  
                                 }
 123  0
                                 String filterName = values[1];
 124  0
                                 String orderNumber = (values.length == 2 ? "0" : values[2]);
 125  0
                                 String value = entry.getValue();
 126  0
                                 addFilterMapping(filterName, orderNumber, value);
 127  0
                         } else if (key.startsWith(FILTER_PREFIX) && key.endsWith(CLASS_SUFFIX)) {
 128  0
                                 String name = key.substring(FILTER_PREFIX.length(), key.length() - CLASS_SUFFIX.length());
 129  0
                                 String value = entry.getValue();
 130  
                                 // ClassLoader cl =
 131  
                                 // SpringServiceLocator.getPluginRegistry().getInstitutionPlugin().getClassLoader();
 132  
                                 // addFilter(name, value, cl, p);
 133  0
                                 addFilter(name, value, p);
 134  
                         }
 135  0
                 }
 136  
                 // do a diff log a warn if any filter has no mappings
 137  0
                 for (String filterName : filters.keySet()) {
 138  0
                         if (!hasFilterMapping(filterName)) {
 139  0
                                 LOG.warn("NO FILTER MAPPING DETECTED.  Filter " + filterName + " has no mapping and will not be called.");
 140  
                         }
 141  
                 }
 142  0
                 initted = true;
 143  0
         }
 144  
 
 145  
         private boolean hasFilterMapping(String filterName) {
 146  0
                 for (FilterMapping filterMapping : filterMappings) {
 147  0
                         if (filterMapping.getFilterName().equals(filterName)) {
 148  0
                                 return true;
 149  
                         }
 150  
                 }
 151  0
                 return false;
 152  
         }
 153  
 
 154  
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 155  0
             LOG.debug("Begin BootstrapFilter...");
 156  0
                 init();
 157  
                 // build the filter chain and execute it
 158  0
                 if (!filterMappings.isEmpty() && request instanceof HttpServletRequest) {
 159  0
                         chain = buildChain((HttpServletRequest) request, chain);
 160  
                 }
 161  0
                 LOG.debug("...ending BootstrapFilter preperation, executing BootstrapFilter Chain.");
 162  0
                 chain.doFilter(request, response);
 163  
 
 164  0
         }
 165  
 
 166  
         private FilterChain buildChain(HttpServletRequest request, FilterChain targetChain) {
 167  0
                 BootstrapFilterChain chain = new BootstrapFilterChain(targetChain, ClassLoaderUtils.getDefaultClassLoader());
 168  0
                 String requestPath = request.getServletPath();
 169  0
                 for (FilterMapping mapping : filterMappings) {
 170  0
                         Filter filter = filters.get(mapping.getFilterName());
 171  0
                         if (!chain.containsFilter(filter) && matchFiltersURL(mapping.getUrlPattern(), requestPath)) {
 172  0
                                 chain.addFilter(filter);
 173  
                         }
 174  0
                 }
 175  0
                 return chain;
 176  
         }
 177  
 
 178  
         public void destroy() {
 179  0
                 for (Filter filter : filters.values()) {
 180  
                         try {
 181  0
                                 filter.destroy();
 182  0
                         } catch (Exception e) {
 183  0
                                 LOG.error("Error destroying filter: " + filter, e);
 184  0
                         }
 185  
                 }
 186  0
         }
 187  
 
 188  
         /**
 189  
          * This method was borrowed from the Tomcat codebase.
 190  
          */
 191  
         private boolean matchFiltersURL(String urlPattern, String requestPath) {
 192  
 
 193  0
                 if (requestPath == null) {
 194  0
                         return (false);
 195  
                 }
 196  
 
 197  
                 // Match on context relative request path
 198  0
                 if (urlPattern == null) {
 199  0
                         return (false);
 200  
                 }
 201  
 
 202  
                 // Case 1 - Exact Match
 203  0
                 if (urlPattern.equals(requestPath)) {
 204  0
                         return (true);
 205  
                 }
 206  
 
 207  
                 // Case 2 - Path Match ("/.../*")
 208  0
                 if (urlPattern.equals("/*") || urlPattern.equals("*")) {
 209  0
                         return (true);
 210  
                 }
 211  0
                 if (urlPattern.endsWith("/*")) {
 212  0
                         if (urlPattern.regionMatches(0, requestPath, 0, urlPattern.length() - 2)) {
 213  0
                                 if (requestPath.length() == (urlPattern.length() - 2)) {
 214  0
                                         return (true);
 215  0
                                 } else if ('/' == requestPath.charAt(urlPattern.length() - 2)) {
 216  0
                                         return (true);
 217  
                                 }
 218  
                         }
 219  0
                         return (false);
 220  
                 }
 221  
 
 222  
                 // Case 3 - Extension Match
 223  0
                 if (urlPattern.startsWith("*.")) {
 224  0
                         int slash = requestPath.lastIndexOf('/');
 225  0
                         int period = requestPath.lastIndexOf('.');
 226  0
                         if ((slash >= 0) && (period > slash) && (period != requestPath.length() - 1) && ((requestPath.length() - period) == (urlPattern.length() - 1))) {
 227  0
                                 return (urlPattern.regionMatches(2, requestPath, period + 1, urlPattern.length() - 2));
 228  
                         }
 229  
                 }
 230  
 
 231  
                 // Case 4 - "Default" Match
 232  0
                 return (false); // NOTE - Not relevant for selecting filters
 233  
 
 234  
         }
 235  
 
 236  
 }
 237  
 
 238  
 /**
 239  
  * A filter chain that invokes a series of filters with which it was
 240  
  * initialized, and then delegates to a target filterchain.
 241  
  *
 242  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 243  
  */
 244  
 class BootstrapFilterChain implements FilterChain {
 245  
 
 246  0
         private final List<Filter> filters = new LinkedList<Filter>();
 247  
 
 248  
         private final FilterChain target;
 249  
 
 250  
         private Iterator<Filter> filterIterator;
 251  
 
 252  
         private ClassLoader originalClassLoader;
 253  
 
 254  0
         public BootstrapFilterChain(FilterChain target, ClassLoader originalClassLoader) {
 255  0
                 this.target = target;
 256  0
                 this.originalClassLoader = originalClassLoader;
 257  0
         }
 258  
 
 259  
         public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
 260  0
                 if (filterIterator == null) {
 261  0
                         filterIterator = filters.iterator();
 262  
                 }
 263  0
                 if (filterIterator.hasNext()) {
 264  0
                         (filterIterator.next()).doFilter(request, response, this);
 265  
                 } else {
 266  
                         // reset the CCL to the original classloader before calling the non
 267  
                         // workflow configured filter - this makes it so our
 268  
                         // CCL is the webapp classloader in workflow action classes and the
 269  
                         // code they call
 270  0
                         Thread.currentThread().setContextClassLoader(originalClassLoader);
 271  0
                         target.doFilter(request, response);
 272  
                 }
 273  0
         }
 274  
 
 275  
         public void addFilter(Filter filter) {
 276  0
                 filters.add(filter);
 277  0
         }
 278  
 
 279  
         public boolean containsFilter(Filter filter) {
 280  0
                 return filters.contains(filter);
 281  
         }
 282  
 
 283  
         public boolean isEmpty() {
 284  0
                 return filters.isEmpty();
 285  
         }
 286  
 
 287  
 }
 288  
 
 289  
 /**
 290  
  * Borrowed from spring-mock.
 291  
  *
 292  
  * @author Kuali Rice Team (rice.collab@kuali.org)
 293  
  */
 294  
 class BootstrapFilterConfig implements FilterConfig {
 295  
 
 296  
         private final ServletContext servletContext;
 297  
 
 298  
         private final String filterName;
 299  
 
 300  0
         private final Map<String, String> initParameters = new HashMap<String, String>();
 301  
 
 302  
         public BootstrapFilterConfig() {
 303  0
                 this(null, "");
 304  0
         }
 305  
 
 306  
         public BootstrapFilterConfig(String filterName) {
 307  0
                 this(null, filterName);
 308  0
         }
 309  
 
 310  
         public BootstrapFilterConfig(ServletContext servletContext) {
 311  0
                 this(servletContext, "");
 312  0
         }
 313  
 
 314  0
         public BootstrapFilterConfig(ServletContext servletContext, String filterName) {
 315  0
                 this.servletContext = servletContext;
 316  0
                 this.filterName = filterName;
 317  0
         }
 318  
 
 319  
         public String getFilterName() {
 320  0
                 return filterName;
 321  
         }
 322  
 
 323  
         public ServletContext getServletContext() {
 324  0
                 return servletContext;
 325  
         }
 326  
 
 327  
         public void addInitParameter(String name, String value) {
 328  0
                 this.initParameters.put(name, value);
 329  0
         }
 330  
 
 331  
         public String getInitParameter(String name) {
 332  0
                 return this.initParameters.get(name);
 333  
         }
 334  
 
 335  
         public Enumeration<String> getInitParameterNames() {
 336  0
                 return Collections.enumeration(this.initParameters.keySet());
 337  
         }
 338  
 
 339  
 }
 340  
 
 341  0
 class FilterMapping implements Comparable<FilterMapping> {
 342  
 
 343  
         private String filterName;
 344  
 
 345  
         private String orderValue;
 346  
 
 347  
         private String urlPattern;
 348  
 
 349  0
         public FilterMapping(String filterName, String orderValue, String urlPattern) {
 350  0
                 this.filterName = filterName;
 351  0
                 this.orderValue = orderValue;
 352  0
                 this.urlPattern = urlPattern;
 353  0
         }
 354  
 
 355  
         public int compareTo(FilterMapping object) {
 356  0
                 return orderValue.compareTo(object.orderValue);
 357  
         }
 358  
 
 359  
         public String getFilterName() {
 360  0
                 return filterName;
 361  
         }
 362  
 
 363  
         public String getOrderValue() {
 364  0
                 return orderValue;
 365  
         }
 366  
 
 367  
         public String getUrlPattern() {
 368  0
                 return urlPattern;
 369  
         }
 370  
 
 371  
 }