1 16 package org.apache.webapp.balancer; 17 18 import java.io.IOException ; 19 import java.io.InputStream ; 20 21 import java.net.URL ; 22 23 import javax.servlet.Filter ; 24 import javax.servlet.FilterChain ; 25 import javax.servlet.FilterConfig ; 26 import javax.servlet.ServletContext ; 27 import javax.servlet.ServletException ; 28 import javax.servlet.ServletRequest ; 29 import javax.servlet.ServletResponse ; 30 import javax.servlet.http.HttpServletRequest ; 31 import javax.servlet.http.HttpServletResponse ; 32 33 34 42 public class BalancerFilter implements Filter { 43 46 private RuleChain ruleChain; 47 48 51 private ServletContext context; 52 53 58 protected RuleChain getRuleChain() { 59 return ruleChain; 60 } 61 62 68 public void init(FilterConfig filterConfig) throws ServletException { 69 context = filterConfig.getServletContext(); 70 71 String configUrlParam = filterConfig.getInitParameter("configUrl"); 72 73 if (configUrlParam == null) { 74 throw new ServletException ("configUrl is required."); 75 } 76 77 try { 78 InputStream input = context.getResourceAsStream(configUrlParam); 79 RulesParser parser = new RulesParser(input); 80 ruleChain = parser.getResult(); 81 context.log( 82 getClass().getName() + ": init(): ruleChain: " + ruleChain); 83 } catch (Exception e) { 84 throw new ServletException (e); 85 } 86 } 87 88 101 public void doFilter( 102 ServletRequest request, ServletResponse response, FilterChain chain) 103 throws IOException , ServletException { 104 if (response.isCommitted()) { 105 context.log( 106 getClass().getName() 107 + ": doFilter(): not inspecting committed response."); 108 chain.doFilter(request, response); 109 } else if (!(request instanceof HttpServletRequest )) { 110 context.log( 111 getClass().getName() 112 + ": doFilter(): not inspecting non-Http request."); 113 chain.doFilter(request, response); 114 } else { 115 HttpServletRequest hreq = (HttpServletRequest ) request; 116 HttpServletResponse hres = (HttpServletResponse ) response; 117 118 URL redirectUrl = getRuleChain().evaluate(hreq); 119 120 if (redirectUrl != null) { 121 String encoded = 122 hres.encodeRedirectURL(redirectUrl.toString()); 123 124 context.log( 125 getClass().getName() 126 + ": doFilter(): redirecting request for " 127 + hreq.getRequestURL().toString() + " to " + encoded); 128 129 hres.sendRedirect(encoded); 130 } else { 131 chain.doFilter(request, response); 132 } 133 } 134 } 135 136 139 public void destroy() { 140 context = null; 141 ruleChain = null; 142 } 143 } 144 145 146 | Popular Tags |