View Javadoc
1   /*
2    * Copyright (C) 2009-2010, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.http.server.glue;
45  
46  import java.io.IOException;
47  import java.util.Enumeration;
48  import java.util.NoSuchElementException;
49  import java.util.Set;
50  
51  import javax.servlet.Filter;
52  import javax.servlet.FilterChain;
53  import javax.servlet.ServletConfig;
54  import javax.servlet.ServletContext;
55  import javax.servlet.ServletException;
56  import javax.servlet.ServletRequest;
57  import javax.servlet.ServletResponse;
58  import javax.servlet.http.HttpServlet;
59  import javax.servlet.http.HttpServletRequest;
60  import javax.servlet.http.HttpServletResponse;
61  
62  /**
63   * Encapsulates the entire serving stack for a single URL.
64   * <p>
65   * Subclasses provide the implementation of {@link #match(HttpServletRequest)},
66   * which is called by {@link MetaServlet} in registration order to determine the
67   * pipeline that will be used to handle a request.
68   * <p>
69   * The very bottom of each pipeline is a single {@link HttpServlet} that will
70   * handle producing the response for this pipeline's URL. {@link Filter}s may
71   * also be registered and applied around the servlet's processing, to manage
72   * request attributes, set standard response headers, or completely override the
73   * response generation.
74   */
75  abstract class UrlPipeline {
76  	/** Filters to apply around {@link #servlet}; may be empty but never null. */
77  	private final Filter[] filters;
78  
79  	/** Instance that must generate the response; never null. */
80  	private final HttpServlet servlet;
81  
82  	UrlPipeline(final Filter[] filters, final HttpServlet servlet) {
83  		this.filters = filters;
84  		this.servlet = servlet;
85  	}
86  
87  	/**
88  	 * Initialize all contained filters and servlets.
89  	 *
90  	 * @param context
91  	 *            the servlet container context our {@link MetaServlet} is
92  	 *            running within.
93  	 * @param inited
94  	 *            <i>(input/output)</i> the set of filters and servlets which
95  	 *            have already been initialized within the container context. If
96  	 *            those same instances appear in this pipeline they are not
97  	 *            initialized a second time. Filters and servlets that are first
98  	 *            initialized by this pipeline will be added to this set.
99  	 * @throws ServletException
100 	 *             a filter or servlet is unable to initialize.
101 	 */
102 	void init(final ServletContext context, final Set<Object> inited)
103 			throws ServletException {
104 		for (Filter ref : filters)
105 			initFilter(ref, context, inited);
106 		initServlet(servlet, context, inited);
107 	}
108 
109 	private static void initFilter(final Filter ref,
110 			final ServletContext context, final Set<Object> inited)
111 			throws ServletException {
112 		if (!inited.contains(ref)) {
113 			ref.init(new NoParameterFilterConfig(ref.getClass().getName(),
114 					context));
115 			inited.add(ref);
116 		}
117 	}
118 
119 	private static void initServlet(final HttpServlet ref,
120 			final ServletContext context, final Set<Object> inited)
121 			throws ServletException {
122 		if (!inited.contains(ref)) {
123 			ref.init(new ServletConfig() {
124 				public String getInitParameter(String name) {
125 					return null;
126 				}
127 
128 				public Enumeration<String> getInitParameterNames() {
129 					return new Enumeration<String>() {
130 						public boolean hasMoreElements() {
131 							return false;
132 						}
133 
134 						public String nextElement() {
135 							throw new NoSuchElementException();
136 						}
137 					};
138 				}
139 
140 				public ServletContext getServletContext() {
141 					return context;
142 				}
143 
144 				public String getServletName() {
145 					return ref.getClass().getName();
146 				}
147 			});
148 			inited.add(ref);
149 		}
150 	}
151 
152 	/**
153 	 * Destroy all contained filters and servlets.
154 	 *
155 	 * @param destroyed
156 	 *            <i>(input/output)</i> the set of filters and servlets which
157 	 *            have already been destroyed within the container context. If
158 	 *            those same instances appear in this pipeline they are not
159 	 *            destroyed a second time. Filters and servlets that are first
160 	 *            destroyed by this pipeline will be added to this set.
161 	 */
162 	void destroy(final Set<Object> destroyed) {
163 		for (Filter ref : filters)
164 			destroyFilter(ref, destroyed);
165 		destroyServlet(servlet, destroyed);
166 	}
167 
168 	private static void destroyFilter(Filter ref, Set<Object> destroyed) {
169 		if (!destroyed.contains(ref)) {
170 			ref.destroy();
171 			destroyed.add(ref);
172 		}
173 	}
174 
175 	private static void destroyServlet(HttpServlet ref, Set<Object> destroyed) {
176 		if (!destroyed.contains(ref)) {
177 			ref.destroy();
178 			destroyed.add(ref);
179 		}
180 	}
181 
182 	/**
183 	 * Determine if this pipeline handles the request's URL.
184 	 * <p>
185 	 * This method should match on the request's {@code getPathInfo()} method,
186 	 * as {@link MetaServlet} passes the request along as-is to each pipeline's
187 	 * match method.
188 	 *
189 	 * @param req
190 	 *            current HTTP request being considered by {@link MetaServlet}.
191 	 * @return {@code true} if this pipeline is configured to handle the
192 	 *         request; {@code false} otherwise.
193 	 */
194 	abstract boolean match(HttpServletRequest req);
195 
196 	/**
197 	 * Execute the filters and the servlet on the request.
198 	 * <p>
199 	 * Invoked by {@link MetaServlet} once {@link #match(HttpServletRequest)}
200 	 * has determined this pipeline is the correct pipeline to handle the
201 	 * current request.
202 	 *
203 	 * @param req
204 	 *            current HTTP request.
205 	 * @param rsp
206 	 *            current HTTP response.
207 	 * @throws ServletException
208 	 *             request cannot be completed.
209 	 * @throws IOException
210 	 *             IO error prevents the request from being completed.
211 	 */
212 	void service(HttpServletRequest req, HttpServletResponse rsp)
213 			throws ServletException, IOException {
214 		if (0 < filters.length)
215 			new Chain(filters, servlet).doFilter(req, rsp);
216 		else
217 			servlet.service(req, rsp);
218 	}
219 
220 	private static class Chain implements FilterChain {
221 		private final Filter[] filters;
222 
223 		private final HttpServlet servlet;
224 
225 		private int filterIdx;
226 
227 		Chain(final Filter[] filters, final HttpServlet servlet) {
228 			this.filters = filters;
229 			this.servlet = servlet;
230 		}
231 
232 		public void doFilter(ServletRequest req, ServletResponse rsp)
233 				throws IOException, ServletException {
234 			if (filterIdx < filters.length)
235 				filters[filterIdx++].doFilter(req, rsp, this);
236 			else
237 				servlet.service(req, rsp);
238 		}
239 	}
240 }