FilterChainInvocation.java revision f8537eaaaf67e36af7469b392a4941e425459991
1/**
2 * Copyright (C) 2008 Google Inc.
3 *
4 * Licensed under the Apache 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.apache.org/licenses/LICENSE-2.0
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 */
16package com.google.inject.servlet;
17
18import java.io.IOException;
19import javax.servlet.FilterChain;
20import javax.servlet.ServletException;
21import javax.servlet.ServletRequest;
22import javax.servlet.ServletResponse;
23
24/**
25 * A Filter chain impl which basically passes itself to the "current" filter and iterates the chain
26 * on {@code doFilter()}. Modeled on something similar in Apache Tomcat.
27 *
28 * Following this, it attempts to dispatch to guice-servlet's registered servlets using the
29 * ManagedServletPipeline.
30 *
31 * And the end, it proceeds to the web.xml (default) servlet filter chain, if needed.
32 *
33 * @author Dhanji R. Prasanna
34 * @since 1.0
35 */
36class FilterChainInvocation implements FilterChain {
37  private final FilterDefinition[] filterDefinitions;
38  private final FilterChain proceedingChain;
39  private final ManagedServletPipeline servletPipeline;
40
41  //state variable tracks current link in filterchain
42  private int index = -1;
43
44  public FilterChainInvocation(FilterDefinition[] filterDefinitions,
45      ManagedServletPipeline servletPipeline, FilterChain proceedingChain) {
46
47    this.filterDefinitions = filterDefinitions;
48    this.servletPipeline = servletPipeline;
49    this.proceedingChain = proceedingChain;
50  }
51
52  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
53      throws IOException, ServletException {
54    index++;
55
56    //dispatch down the chain while there are more filters
57    if (index < filterDefinitions.length) {
58      filterDefinitions[index].doFilter(servletRequest, servletResponse, this);
59    } else {
60
61      //we've reached the end of the filterchain, let's try to dispatch to a servlet
62      final boolean serviced = servletPipeline.service(servletRequest, servletResponse);
63
64      //dispatch to the normal filter chain only if one of our servlets did not match
65      if (!serviced) {
66        proceedingChain.doFilter(servletRequest, servletResponse);
67      }
68    }
69  }
70}
71