1 13 package info.magnolia.cms.filters; 14 15 import info.magnolia.cms.beans.config.VirtualURIManager; 16 import info.magnolia.cms.core.Path; 17 18 import java.io.IOException ; 19 20 import javax.servlet.Filter ; 21 import javax.servlet.FilterChain ; 22 import javax.servlet.FilterConfig ; 23 import javax.servlet.ServletException ; 24 import javax.servlet.ServletRequest ; 25 import javax.servlet.ServletResponse ; 26 import javax.servlet.http.HttpServletRequest ; 27 import javax.servlet.http.HttpServletResponse ; 28 29 import org.apache.commons.lang.ClassUtils; 30 import org.apache.commons.lang.StringUtils; 31 import org.slf4j.Logger; 32 import org.slf4j.LoggerFactory; 33 34 35 40 public class MgnlVirtualUriFilter implements Filter { 41 42 45 private static Logger log = LoggerFactory.getLogger(MgnlVirtualUriFilter.class); 46 47 private static final int REDIRECT = 1; 48 49 private static final int INCLUDE = 2; 50 51 private static final int NO_ACTION = 3; 52 53 56 public void init(FilterConfig filterConfig) throws ServletException { 57 } 59 60 63 public void destroy() { 64 } 66 67 71 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException , 72 ServletException { 73 74 HttpServletRequest request = (HttpServletRequest ) req; 75 HttpServletResponse response = (HttpServletResponse ) resp; 76 77 int result = redirect(request, response); 78 if (result == REDIRECT) { 79 return; 80 } else if (result == INCLUDE) { 81 ((MagnoliaManagedFilter.CustomFilterChain)filterChain).reset(); 82 } 83 filterChain.doFilter(req, resp); 84 } 85 86 92 private int redirect(HttpServletRequest request, HttpServletResponse response) { 93 String uri = this.getURIMap(request); 94 if (StringUtils.isNotEmpty(uri)) { 95 if (!response.isCommitted()) { 96 97 if (uri.startsWith("redirect:")) { 98 try { 99 response.sendRedirect(request.getContextPath() + StringUtils.substringAfter(uri, "redirect:")); 100 return REDIRECT; 101 } 102 catch (IOException e) { 103 log.error("Failed to redirect to {}:{}", new Object []{uri, e.getMessage()}); 105 } 106 } else if (uri.startsWith("forward:")) { 107 uri = StringUtils.substringAfter(uri, "forward:"); 108 try { 109 request.getRequestDispatcher(uri).forward(request, response); 110 return REDIRECT; 111 } catch (Exception e) { 112 log.error("Failed to forward to {} - {}:{}", new Object []{uri, ClassUtils.getShortClassName(e.getClass()), e.getMessage()}); 114 } 115 } else { 116 Path.setURI(uri, request); 117 return INCLUDE; 118 } 119 } 120 else { 121 log.warn("Response is already committed, cannot forward to {} (original URI was {})", uri, 123 request.getRequestURI()); 124 } 125 126 } 128 return NO_ACTION; 129 } 130 131 135 private String getURIMap(HttpServletRequest request) { 136 return VirtualURIManager.getInstance().getURIMapping(Path.getURI(request)); 137 } 138 139 } | Popular Tags |