1 24 package org.riotfamily.common.web.filter; 25 26 import java.io.IOException ; 27 import java.util.Arrays ; 28 29 import javax.servlet.FilterChain ; 30 import javax.servlet.ServletContext ; 31 import javax.servlet.ServletException ; 32 import javax.servlet.http.HttpServletRequest ; 33 import javax.servlet.http.HttpServletResponse ; 34 35 import org.springframework.core.OrderComparator; 36 import org.springframework.util.AntPathMatcher; 37 import org.springframework.web.filter.OncePerRequestFilter; 38 import org.springframework.web.util.UrlPathHelper; 39 40 55 public final class PluginFilter extends OncePerRequestFilter { 56 57 private static final String ATTRIBUTE_PREFIX = 58 PluginFilter.class.getName() + '.'; 59 60 private String [] exclude; 61 62 private UrlPathHelper urlPathHelper = new UrlPathHelper(); 63 64 private AntPathMatcher pathMatcher = new AntPathMatcher(); 65 66 private OrderComparator orderComparator = new OrderComparator(); 67 68 private FilterPlugin[] plugins = new FilterPlugin[0]; 69 70 73 public void setExclude(String [] exclude) { 74 this.exclude = exclude; 75 } 76 77 protected void initFilterBean() throws ServletException { 78 getServletContext().setAttribute( 79 ATTRIBUTE_PREFIX + getFilterName(), this); 80 } 81 82 synchronized void addPlugin(FilterPlugin plugin) { 83 int n = plugins.length; 84 FilterPlugin[] newPlugins = new FilterPlugin[n + 1]; 85 System.arraycopy(plugins, 0, newPlugins, 0, n); 86 newPlugins[n++] = plugin; 87 Arrays.sort(newPlugins, orderComparator); 88 plugins = newPlugins; 89 } 90 91 synchronized void removePlugin(FilterPlugin plugin) { 92 int n = plugins.length; 93 FilterPlugin[] newPlugins = new FilterPlugin[n - 1]; 94 int j = 0; 95 for (int i = 0; i < n; i++) { 96 if (plugins[i] != plugin) { 97 newPlugins[j++] = plugins[i]; 98 } 99 } 100 plugins = newPlugins; 101 } 102 103 107 protected boolean shouldNotFilter(HttpServletRequest request) { 108 if (exclude != null) { 109 String path = urlPathHelper.getPathWithinApplication(request); 110 for (int i = 0; i < exclude.length; i++) { 111 if (pathMatcher.match(exclude[i], path)) { 112 return true; 113 } 114 } 115 } 116 return false; 117 } 118 119 protected void doFilterInternal(HttpServletRequest request, 120 HttpServletResponse response, FilterChain filterChain) 121 throws ServletException , IOException { 122 123 new PluginChain(filterChain, plugins).doFilter(request, response); 124 } 125 126 static PluginFilter getInstance(ServletContext servletContext, 127 String filterName) { 128 129 return (PluginFilter) servletContext.getAttribute( 130 ATTRIBUTE_PREFIX + filterName); 131 } 132 133 } 134 | Popular Tags |