001/* 002 * Copyright 2012-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.devtools.remote.server; 018 019import java.io.IOException; 020 021import javax.servlet.Filter; 022import javax.servlet.FilterChain; 023import javax.servlet.FilterConfig; 024import javax.servlet.ServletException; 025import javax.servlet.ServletRequest; 026import javax.servlet.ServletResponse; 027import javax.servlet.http.HttpServletRequest; 028import javax.servlet.http.HttpServletResponse; 029 030import org.springframework.http.server.ServerHttpRequest; 031import org.springframework.http.server.ServerHttpResponse; 032import org.springframework.http.server.ServletServerHttpRequest; 033import org.springframework.http.server.ServletServerHttpResponse; 034import org.springframework.util.Assert; 035 036/** 037 * Servlet filter providing integration with the remote server {@link Dispatcher}. 038 * 039 * @author Phillip Webb 040 * @author Rob Winch 041 * @since 1.3.0 042 */ 043public class DispatcherFilter implements Filter { 044 045 private final Dispatcher dispatcher; 046 047 public DispatcherFilter(Dispatcher dispatcher) { 048 Assert.notNull(dispatcher, "Dispatcher must not be null"); 049 this.dispatcher = dispatcher; 050 } 051 052 @Override 053 public void init(FilterConfig filterConfig) throws ServletException { 054 } 055 056 @Override 057 public void doFilter(ServletRequest request, ServletResponse response, 058 FilterChain chain) throws IOException, ServletException { 059 if (request instanceof HttpServletRequest 060 && response instanceof HttpServletResponse) { 061 doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); 062 } 063 else { 064 chain.doFilter(request, response); 065 } 066 } 067 068 private void doFilter(HttpServletRequest request, HttpServletResponse response, 069 FilterChain chain) throws IOException, ServletException { 070 ServerHttpRequest serverRequest = new ServletServerHttpRequest(request); 071 ServerHttpResponse serverResponse = new ServletServerHttpResponse(response); 072 if (!this.dispatcher.handle(serverRequest, serverResponse)) { 073 chain.doFilter(request, response); 074 } 075 } 076 077 @Override 078 public void destroy() { 079 } 080 081}