141 | * Any call to this method must occur prior to calls to {@link #register(Class...)}
142 | * and/or {@link #scan(String...)}.
143 | * @param beanNameGenerator the bean name generator
144 | * @see AnnotatedBeanDefinitionReader#setBeanNameGenerator
145 | * @see ClassPathBeanDefinitionScanner#setBeanNameGenerator
146 | */
147 | public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
148 | this.reader.setBeanNameGenerator(beanNameGenerator);
149 | this.scanner.setBeanNameGenerator(beanNameGenerator);
150 | this.getBeanFactory().registerSingleton(
151 | AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR,
152 | beanNameGenerator);
153 | }
154 |
155 | /**
156 | * Set the {@link ScopeMetadataResolver} to use for detected bean classes.
157 | *
158 | * The default is an {@link AnnotationScopeMetadataResolver}.
159 | *
160 | * Any call to this method must occur prior to calls to {@link #register(Class...)}
161 | * and/or {@link #scan(String...)}.
162 | * @param scopeMetadataResolver the scope metadata resolver
163 | */
164 | public void setScopeMetadataResolver(ScopeMetadataResolver scopeMetadataResolver) {
165 | this.reader.setScopeMetadataResolver(scopeMetadataResolver);
166 | this.scanner.setScopeMetadataResolver(scopeMetadataResolver);
167 | }
168 |
169 | /**
170 | * Register one or more annotated classes to be processed. Note that
171 | * {@link #refresh()} must be called in order for the context to fully process the new
172 | * class.
173 | *
174 | * Calls to {@code #register} are idempotent; adding the same annotated class more
175 | * than once has no additional effect.
176 | * @param annotatedClasses one or more annotated classes, e.g. {@code @Configuration}
177 | * classes
178 | * @see #scan(String...)
179 | * @see #refresh()
180 | */
181 | @Override
182 | public final void register(Class>... annotatedClasses) {
183 | Assert.notEmpty(annotatedClasses,
184 | "At least one annotated class must be specified");
185 | this.annotatedClasses.addAll(Arrays.asList(annotatedClasses));
186 | }
187 |
188 | /**
189 | * Perform a scan within the specified base packages. Note that {@link #refresh()}
190 | * must be called in order for the context to fully process the new class.
191 | * @param basePackages the packages to check for annotated classes
192 | * @see #register(Class...)
193 | * @see #refresh()
194 | */
195 | @Override
196 | public final void scan(String... basePackages) {
197 | Assert.notEmpty(basePackages, "At least one base package must be specified");
198 | this.basePackages = basePackages;
199 | }
200 |
201 | @Override
202 | protected void prepareRefresh() {
203 | this.scanner.clearCache();
204 | super.prepareRefresh();
205 | }
206 |
207 | @Override
208 | protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
209 | super.postProcessBeanFactory(beanFactory);
210 | if (this.basePackages != null && this.basePackages.length > 0) {
211 | this.scanner.scan(this.basePackages);
212 | }
213 | if (!this.annotatedClasses.isEmpty()) {
214 | this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
215 | }
216 | }
217 |
218 | }
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/legacy/context/web/MetricFilterAutoConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2018 the original author or authors.
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 | */
16 |
17 | package org.springframework.boot.legacy.context.web;
18 |
19 | import java.io.IOException;
20 |
21 | import javax.servlet.Filter;
22 | import javax.servlet.FilterChain;
23 | import javax.servlet.Servlet;
24 | import javax.servlet.ServletException;
25 | import javax.servlet.http.HttpServletRequest;
26 | import javax.servlet.http.HttpServletResponse;
27 | import javax.servlet.http.HttpServletResponseWrapper;
28 |
29 | import io.micrometer.core.instrument.MeterRegistry;
30 |
31 | import org.springframework.beans.factory.annotation.Autowired;
32 | import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
33 | import org.springframework.boot.autoconfigure.AutoConfigureAfter;
34 | import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
35 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
36 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
37 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
38 | import org.springframework.context.annotation.Bean;
39 | import org.springframework.context.annotation.Configuration;
40 | import org.springframework.core.Ordered;
41 | import org.springframework.core.annotation.Order;
42 | import org.springframework.http.HttpStatus;
43 | import org.springframework.util.StopWatch;
44 | import org.springframework.web.filter.OncePerRequestFilter;
45 | import org.springframework.web.servlet.HandlerMapping;
46 | import org.springframework.web.util.UrlPathHelper;
47 |
48 | /**
49 | * {@link EnableAutoConfiguration Auto-configuration} that records Servlet interactions
50 | * with a {@link MeterRegistry}.
51 | *
52 | * @author Dave Syer
53 | * @author Phillip Webb
54 | * @author Daniel Cruver
55 | */
56 | @Configuration
57 | @ConditionalOnBean({MeterRegistry.class})
58 | @ConditionalOnClass({Servlet.class, MetricsAutoConfiguration.class})
59 | @ConditionalOnMissingClass("javax.servlet.ServletRegistration")
60 | @AutoConfigureAfter({
61 | MetricsAutoConfiguration.class})
62 | public class MetricFilterAutoConfiguration {
63 |
64 | private static final int UNDEFINED_HTTP_STATUS = 999;
65 |
66 | private static final String UNKNOWN_PATH_SUFFIX = "/unmapped";
67 |
68 | @Autowired
69 | private MeterRegistry meterRegistry;
70 |
71 | @Bean
72 | public Filter metricFilter() {
73 | return new MetricsFilter();
74 | }
75 |
76 | /**
77 | * Filter that counts requests and measures processing times.
78 | */
79 | @Order(Ordered.HIGHEST_PRECEDENCE)
80 | private final class MetricsFilter extends OncePerRequestFilter {
81 |
82 | @Override
83 | protected void doFilterInternal(HttpServletRequest request,
84 | HttpServletResponse response, FilterChain chain) throws ServletException,
85 | IOException {
86 | UrlPathHelper helper = new UrlPathHelper();
87 | String suffix = helper.getPathWithinApplication(request);
88 | StopWatch stopWatch = new StopWatch();
89 | stopWatch.start();
90 | MetricsFilterResponseWrapper wrapper = new MetricsFilterResponseWrapper(
91 | response);
92 | try {
93 | chain.doFilter(request, wrapper);
94 | }
95 | finally {
96 | stopWatch.stop();
97 | int status = getStatus(wrapper);
98 | Object bestMatchingPattern = request
99 | .getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
100 | if (bestMatchingPattern != null) {
101 | suffix = bestMatchingPattern.toString().replaceAll("[{}]", "-");
102 | }
103 | else if (HttpStatus.valueOf(status).is4xxClientError()) {
104 | suffix = UNKNOWN_PATH_SUFFIX;
105 | }
106 | String gaugeKey = getKey("response" + suffix);
107 | meterRegistry.gauge(gaugeKey,
108 | stopWatch.getTotalTimeMillis());
109 | String counterKey = getKey("status." + getStatus(wrapper) + suffix);
110 | meterRegistry.counter(counterKey);
111 | }
112 | }
113 |
114 | private int getStatus(MetricsFilterResponseWrapper response) {
115 | try {
116 | return response.getStatus();
117 | }
118 | catch (Exception ex) {
119 | return UNDEFINED_HTTP_STATUS;
120 | }
121 | }
122 |
123 | private String getKey(String string) {
124 | // graphite compatible metric names
125 | String value = string.replace("/", ".");
126 | value = value.replace("..", ".");
127 | if (value.endsWith(".")) {
128 | value = value + "root";
129 | }
130 | if (value.startsWith("_")) {
131 | value = value.substring(1);
132 | }
133 | return value;
134 | }
135 | }
136 |
137 | private class MetricsFilterResponseWrapper extends HttpServletResponseWrapper {
138 |
139 | private int status;
140 |
141 | public MetricsFilterResponseWrapper(HttpServletResponse response) {
142 | super(response);
143 | }
144 |
145 | public int getStatus() {
146 | return status;
147 | }
148 |
149 | @Override
150 | public void setStatus(int sc) {
151 | setStatus(sc, null);
152 | }
153 |
154 | @Override
155 | public void setStatus(int status, String sm) {
156 | this.status = status;
157 | super.setStatus(status, sm);
158 | }
159 | }
160 |
161 | }
162 |
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/legacy/context/web/NonEmbeddedWebApplicationContext.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2018 the original author or authors.
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 | */
16 |
17 | package org.springframework.boot.legacy.context.web;
18 |
19 | import java.util.Collection;
20 | import java.util.EventListener;
21 |
22 | import javax.servlet.Filter;
23 | import javax.servlet.Servlet;
24 | import javax.servlet.ServletConfig;
25 | import javax.servlet.ServletContext;
26 | import javax.servlet.ServletException;
27 |
28 | import org.apache.commons.logging.Log;
29 | import org.apache.commons.logging.LogFactory;
30 |
31 | import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
32 | import org.springframework.beans.factory.support.DefaultListableBeanFactory;
33 | import org.springframework.boot.web.servlet.LegacyServletContextInitializerBeans;
34 | import org.springframework.boot.web.servlet.ServletContextInitializer;
35 | import org.springframework.boot.web.servlet.ServletContextInitializerBeans;
36 | import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
37 | import org.springframework.context.ApplicationContextException;
38 | import org.springframework.core.io.Resource;
39 | import org.springframework.web.context.ContextLoader;
40 | import org.springframework.web.context.ContextLoaderListener;
41 | import org.springframework.web.context.WebApplicationContext;
42 | import org.springframework.web.context.support.GenericWebApplicationContext;
43 | import org.springframework.web.context.support.ServletContextResource;
44 | import org.springframework.web.context.support.WebApplicationContextUtils;
45 |
46 | /**
47 | * A version of the {@link ServletWebServerApplicationContext} that can be used with a
48 | * SpringApplication in a web (i.e. servlet) context but does not require an embedded
49 | * servlet container.
50 | *
51 | * @author Daniel Cruver
52 | */
53 | public class NonEmbeddedWebApplicationContext extends GenericWebApplicationContext {
54 | private ServletConfig servletConfig;
55 |
56 | private String namespace;
57 |
58 | /**
59 | * Create a new {@link NonEmbeddedWebApplicationContext}.
60 | */
61 | public NonEmbeddedWebApplicationContext() {
62 | }
63 |
64 | /**
65 | * Create a new {@link ServletWebServerApplicationContext} with the given
66 | * {@code DefaultListableBeanFactory}.
67 | * @param beanFactory the DefaultListableBeanFactory instance to use for this context
68 | */
69 | public NonEmbeddedWebApplicationContext(DefaultListableBeanFactory beanFactory) {
70 | super(beanFactory);
71 | }
72 |
73 | @Override
74 | protected void onRefresh() {
75 | super.onRefresh();
76 | try {
77 | init();
78 | }
79 | catch (Throwable ex) {
80 | throw new ApplicationContextException("Unable to start application context",
81 | ex);
82 | }
83 | }
84 |
85 | public void init() {
86 | ServletContext servletContext = getServletContext();
87 | if (servletContext != null) {
88 | try {
89 | getSelfInitializer().onStartup(servletContext);
90 | }
91 | catch (ServletException ex) {
92 | throw new ApplicationContextException("Cannot initialize servlet context",
93 | ex);
94 | }
95 | }
96 | initPropertySources();
97 | }
98 |
99 | @Override
100 | public void setServletContext(ServletContext servletContext) {
101 | super.setServletContext(servletContext);
102 | // prepareWebApplicationContext(servletContext);
103 | }
104 |
105 | /**
106 | * Returns the {@link ServletContextInitializer} that will be used to complete the
107 | * setup of this {@link WebApplicationContext}.
108 | * @return the self initializer
109 | * @see #prepareWebApplicationContext(ServletContext)
110 | */
111 | private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {
112 | return this::selfInitialize;
113 | }
114 |
115 | private void selfInitialize(ServletContext servletContext) throws ServletException {
116 | prepareWebApplicationContext(servletContext);
117 | ConfigurableListableBeanFactory beanFactory = getBeanFactory();
118 |
119 | ServletWebServerApplicationContext.ExistingWebApplicationScopes existingScopes =
120 | new ServletWebServerApplicationContext.ExistingWebApplicationScopes(beanFactory);
121 |
122 | WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, getServletContext());
123 | existingScopes.restore();
124 |
125 | WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, getServletContext());
126 |
127 | Collection servletContextInitializerBeans;
128 |
129 | if (servletContext.getMajorVersion() >= 3) {
130 | servletContextInitializerBeans = getServletContextInitializerBeans();
131 | }
132 | else {
133 | servletContextInitializerBeans = getLegacyServletContextInitializerBeans();
134 | }
135 |
136 | for (ServletContextInitializer beans : servletContextInitializerBeans) {
137 | beans.onStartup(servletContext);
138 | }
139 |
140 | }
141 |
142 | /**
143 | * Returns {@link ServletContextInitializer}s that should be used with the embedded
144 | * web server. By default this method will first attempt to find
145 | * {@link ServletContextInitializer}, {@link Servlet}, {@link Filter} and certain
146 | * {@link EventListener} beans.
147 | * @return the servlet initializer beans
148 | */
149 | protected Collection getServletContextInitializerBeans() {
150 | return new ServletContextInitializerBeans(getBeanFactory());
151 | }
152 |
153 | /**
154 | * Returns {@link ServletContextInitializer}s that should be used in 2.5 Servlet.
155 | * {@link ServletContextInitializer}, {@link Servlet}, {@link Filter} and certain
156 | * {@link EventListener} beans.
157 | * @return the servlet initializer beans
158 | */
159 | protected Collection getLegacyServletContextInitializerBeans() {
160 | return new LegacyServletContextInitializerBeans(getBeanFactory());
161 | }
162 |
163 | /**
164 | * Prepare the {@link WebApplicationContext} with the given fully loaded
165 | * {@link ServletContext}. This method is usually called from
166 | * {@link ServletContextInitializer#onStartup(ServletContext)} and is similar to the
167 | * functionality usually provided by a {@link ContextLoaderListener}.
168 | * @param servletContext the operational servlet context
169 | */
170 | protected void prepareWebApplicationContext(ServletContext servletContext) {
171 | Object rootContext = servletContext
172 | .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
173 | if (rootContext != null) {
174 | if (rootContext == this) {
175 | throw new IllegalStateException(
176 | "Cannot initialize context because there is already a root application context present - "
177 | + "check whether you have multiple ServletContextInitializers!");
178 | }
179 | else {
180 | return;
181 | }
182 | }
183 | Log logger = LogFactory.getLog(ContextLoader.class);
184 | servletContext.log("Initializing Spring Boot Legacy WebApplicationContext");
185 | WebApplicationContextUtils.registerWebApplicationScopes(getBeanFactory(),
186 | getServletContext());
187 | WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(),
188 | getServletContext());
189 | try {
190 | servletContext.setAttribute(
191 | WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this);
192 | if (logger.isDebugEnabled()) {
193 | logger.debug("Published root WebApplicationContext as ServletContext attribute with name ["
194 | + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
195 | + "]");
196 | }
197 | setServletContext(servletContext);
198 | if (logger.isInfoEnabled()) {
199 | long elapsedTime = System.currentTimeMillis() - getStartupDate();
200 | logger.info("Root WebApplicationContext: initialization completed in "
201 | + elapsedTime + " ms");
202 | }
203 | }
204 | catch (RuntimeException ex) {
205 | logger.error("Context initialization failed", ex);
206 | servletContext.setAttribute(
207 | WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
208 | throw ex;
209 | }
210 | catch (Error ex) {
211 | logger.error("Context initialization failed", ex);
212 | servletContext.setAttribute(
213 | WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
214 | throw ex;
215 | }
216 | }
217 |
218 | @Override
219 | protected Resource getResourceByPath(String path) {
220 | if (getServletContext() == null) {
221 | return new ClassPathContextResource(path, getClassLoader());
222 | }
223 | return new ServletContextResource(getServletContext(), path);
224 | }
225 |
226 | @Override
227 | public String getNamespace() {
228 | return this.namespace;
229 | }
230 |
231 | @Override
232 | public void setNamespace(String namespace) {
233 | this.namespace = namespace;
234 | }
235 |
236 | @Override
237 | public ServletConfig getServletConfig() {
238 | return this.servletConfig;
239 | }
240 |
241 | @Override
242 | public void setServletConfig(ServletConfig servletConfig) {
243 | this.servletConfig = servletConfig;
244 | }
245 |
246 | }
247 |
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/legacy/context/web/SecurityFilterAutoConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014-2018 the original author or authors.
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 | */
16 | package org.springframework.boot.legacy.context.web;
17 |
18 | import org.springframework.boot.autoconfigure.AutoConfigureAfter;
19 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
20 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
21 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
22 | import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
23 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
24 | import org.springframework.context.annotation.Bean;
25 | import org.springframework.context.annotation.Configuration;
26 | import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
27 |
28 | @Configuration
29 | @ConditionalOnWebApplication
30 | @EnableConfigurationProperties
31 | @ConditionalOnClass(AbstractSecurityWebApplicationInitializer.class)
32 | @ConditionalOnMissingClass("javax.servlet.AsyncContext")
33 | @AutoConfigureAfter(name = "org.springframework.boot.autoconfigure.security.servlet.SpringBootWebSecurityConfiguration")
34 | public class SecurityFilterAutoConfiguration {
35 |
36 | private static final String DEFAULT_FILTER_NAME = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME;
37 |
38 | @Bean
39 | @ConditionalOnBean(name = DEFAULT_FILTER_NAME)
40 | public Object securityFilterChainRegistration() {
41 | return new Object();
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/legacy/context/web/SpringBootContextLoaderListener.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2012-2018 the original author or authors.
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 | */
16 |
17 | package org.springframework.boot.legacy.context.web;
18 |
19 | import java.util.Arrays;
20 | import java.util.Collections;
21 |
22 | import javax.servlet.ServletContext;
23 |
24 | import org.apache.commons.logging.Log;
25 | import org.apache.commons.logging.LogFactory;
26 | import org.springframework.beans.BeanUtils;
27 | import org.springframework.boot.SpringApplication;
28 | import org.springframework.boot.builder.ParentContextApplicationContextInitializer;
29 | import org.springframework.boot.builder.SpringApplicationBuilder;
30 | import org.springframework.boot.legacy.context.web.servlet.support.ErrorPageFilterConfiguration;
31 | import org.springframework.boot.web.servlet.support.ErrorPageFilter;
32 | import org.springframework.context.ApplicationContext;
33 | import org.springframework.context.ApplicationContextException;
34 | import org.springframework.context.ApplicationContextInitializer;
35 | import org.springframework.context.ConfigurableApplicationContext;
36 | import org.springframework.context.annotation.Configuration;
37 | import org.springframework.core.annotation.AnnotationUtils;
38 | import org.springframework.util.Assert;
39 | import org.springframework.util.ClassUtils;
40 | import org.springframework.util.StringUtils;
41 | import org.springframework.web.context.ContextLoaderListener;
42 | import org.springframework.web.context.ConfigurableWebApplicationContext;
43 | import org.springframework.web.context.WebApplicationContext;
44 | import org.springframework.web.context.support.StandardServletEnvironment;
45 |
46 | /**
47 | * A {@link ContextLoaderListener} that uses {@link SpringApplication} to initialize an
48 | * application context. Allows Servlet 2.5 applications (with web.xml) to take advantage
49 | * of all the initialization extras in Spring Boot even if they don't use an embedded
50 | * container.
51 | *
52 | * @author Daniel Cruver
53 | * @author Dave Syer
54 | */
55 | public class SpringBootContextLoaderListener extends ContextLoaderListener {
56 |
57 | /**
58 | * Name of servlet context parameter (i.e., {@value}) that can specify to
59 | * disable registration of error page filter.
60 | *
61 | * @see org.springframework.boot.web.servlet.support.SpringBootServletInitializer#setRegisterErrorPageFilter(boolean)
62 | */
63 | public static final String SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM = "springBootLegacyRegisterErrorPageFilter";
64 |
65 | private static final String INIT_PARAM_DELIMITERS = ",; \t\n";
66 |
67 | protected Log logger; // Don't initialize early
68 |
69 | private boolean registerErrorPageFilter = true;
70 |
71 | /**
72 | * Set if the {@link ErrorPageFilter} should be registered. Set to {@code false} if
73 | * error page mappings should be handled via the server and not Spring Boot.
74 | *
75 | * This method is a clone from {@link org.springframework.boot.web.servlet.support.SpringBootServletInitializer} but since
76 | * we are initializing it differently, we can not call this method on the {@link ContextLoaderListener} a servlet context
77 | * param {@link #SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM} has been provided for setting this value.
78 | *
79 | * @param registerErrorPageFilter if the {@link ErrorPageFilter} should be registered.
80 | */
81 | protected final void setRegisterErrorPageFilter(boolean registerErrorPageFilter) {
82 | this.registerErrorPageFilter = registerErrorPageFilter;
83 | }
84 |
85 | @Override
86 | public WebApplicationContext initWebApplicationContext(
87 | final ServletContext servletContext) {
88 | this.logger = LogFactory.getLog(getClass());
89 | this.logger.debug("Initializing WebApplicationContext");
90 | String configLocationParam = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
91 | String[] classNames = StringUtils.tokenizeToStringArray(configLocationParam, INIT_PARAM_DELIMITERS);
92 |
93 | setRegisterErrorPageFilterFromContextParam(servletContext);
94 |
95 | SpringApplicationBuilder builder = createSpringApplicationBuilder(classNames);
96 |
97 | StandardServletEnvironment environment = new StandardServletEnvironment();
98 | environment.initPropertySources(servletContext, null);
99 | builder.environment(environment);
100 |
101 | setMainClass(builder, classNames);
102 |
103 | @SuppressWarnings("unchecked")
104 | Class extends ConfigurableApplicationContext> contextClass = (Class extends ConfigurableApplicationContext>) determineContextClass(servletContext);
105 | builder.contextFactory((type) -> (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass));
106 |
107 | ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
108 |
109 | if (parent != null) {
110 | this.logger.info("Root context already created (using as parent).");
111 | servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
112 | builder.initializers(new ParentContextApplicationContextInitializer(parent));
113 | }
114 |
115 | builder.initializers((ApplicationContextInitializer) applicationContext -> applicationContext.setServletContext(servletContext));
116 |
117 | // Ensure error pages are registered
118 | if (this.registerErrorPageFilter) {
119 | builder.sources(ErrorPageFilterConfiguration.class);
120 | }
121 |
122 | SpringApplication application = builder.build();
123 |
124 | if (application.getAllSources().isEmpty() && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
125 | application.addPrimarySources(Collections.singleton(getClass()));
126 | }
127 |
128 | Assert.state(!application.getAllSources().isEmpty(),
129 | "No SpringApplication sources have been defined. Either override the "
130 | + "configure method or add an @Configuration annotation");
131 |
132 | WebApplicationContext context = (WebApplicationContext) application.run();
133 | servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
134 | return context;
135 | }
136 |
137 | private void setMainClass(SpringApplicationBuilder builder, String[] classNames) {
138 | try {
139 | builder.main(Class.forName(classNames[0]));
140 | }
141 | catch (ClassNotFoundException e) {
142 | this.logger.warn("Could create instance of class " + classNames[0] + " provided by " + CONFIG_LOCATION_PARAM, e);
143 | }
144 | }
145 |
146 | private void setRegisterErrorPageFilterFromContextParam(ServletContext servletContext) {
147 | String contextParamValue = servletContext.getInitParameter(SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM);
148 |
149 | if (contextParamValue == null) {
150 | this.logger.debug("No context init parameter found for " + SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM + "; leaving it at default value: " + this.registerErrorPageFilter);
151 | }
152 | else if (StringUtils.hasText(contextParamValue)) {
153 | boolean booleanValue = Boolean.parseBoolean(contextParamValue);
154 | setRegisterErrorPageFilter(booleanValue);
155 | this.logger.debug("Found context init parameter found for " + SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM + "; updating registerErrorPageFilter to " + this.registerErrorPageFilter);
156 | }
157 | else {
158 | this.logger.warn("Context init parameter found for " + SPRING_BOOT_LEGACY_REGISTER_ERROR_PAGE_FILTER_PARAM + " but it is empty; leaving it at default value: " + this.registerErrorPageFilter);
159 | }
160 | }
161 |
162 | protected SpringApplicationBuilder createSpringApplicationBuilder(String[] classNames) {
163 |
164 | if (this.logger.isDebugEnabled()) {
165 | this.logger.debug("Creating SpringApplicationBuilder ( with classes: " + Arrays.toString(classNames) + ")");
166 | }
167 |
168 | Class[] classes = new Class[classNames.length];
169 | for (int i = 0; i < classes.length; i++) {
170 | try {
171 | classes[i] = ClassUtils.forName(classNames[i], null);
172 | }
173 | catch (ClassNotFoundException e) {
174 | throw new ApplicationContextException(
175 | "Failed to load custom context class [" + classNames[i] + "]", e);
176 | }
177 | }
178 |
179 | return new SpringApplicationBuilder(classes);
180 | }
181 |
182 | private ApplicationContext getExistingRootWebApplicationContext(ServletContext servletContext) {
183 | Object context = servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
184 | if (context instanceof ApplicationContext) {
185 | return (ApplicationContext) context;
186 | }
187 | return null;
188 | }
189 |
190 | @Override
191 | protected Class> determineContextClass(ServletContext servletContext) {
192 | this.logger = LogFactory.getLog(getClass());
193 | String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
194 |
195 | if (contextClassName != null) {
196 | this.logger.info("Using context class: " + contextClassName);
197 | try {
198 | return ClassUtils.forName(contextClassName, null);
199 | }
200 | catch (Exception e) {
201 | throw new ApplicationContextException(
202 | "Failed to load custom context class [" + contextClassName + "]",
203 | e);
204 | }
205 | }
206 |
207 | logger.debug("Using default context class: " + AnnotationConfigNonEmbeddedWebApplicationContext.class.getCanonicalName() + "");
208 | return AnnotationConfigNonEmbeddedWebApplicationContext.class;
209 | }
210 |
211 | }
212 |
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/legacy/context/web/servlet/support/ErrorPageFilterConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2018 CUBRC, Inc. - Unpublished Work - All rights reserved under the copyright laws of the United States.
3 | * CUBRC, Inc. does not grant permission to any party outside the United States Government to use, disclose, copy, or make derivative works of this software.
4 | */
5 |
6 | package org.springframework.boot.legacy.context.web.servlet.support;
7 |
8 | import org.springframework.boot.web.servlet.support.ErrorPageFilter;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.Configuration;
11 |
12 | /**
13 | * Configuration for {@link ErrorPageFilter}.
14 | *
15 | * NOTE: Original class {@link ErrorPageFilterConfiguration} is not accessible.
16 | *
17 | * @author Daniel Cruver
18 | * @author Andy Wilkinson
19 | */
20 | @Configuration
21 | public class ErrorPageFilterConfiguration {
22 |
23 | @Bean
24 | public ErrorPageFilter errorPageFilter() {
25 | return new ErrorPageFilter();
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/spring-boot-legacy/src/main/java/org/springframework/boot/web/servlet/LegacyServletContextInitializerBeans.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2018 the original author or authors.
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 | */
16 |
17 | package org.springframework.boot.web.servlet;
18 |
19 | import java.util.AbstractCollection;
20 | import java.util.ArrayList;
21 | import java.util.Collections;
22 | import java.util.Comparator;
23 | import java.util.EventListener;
24 | import java.util.HashSet;
25 | import java.util.Iterator;
26 | import java.util.LinkedHashMap;
27 | import java.util.List;
28 | import java.util.Map;
29 | import java.util.Map.Entry;
30 | import java.util.Set;
31 |
32 | import javax.servlet.Filter;
33 | import javax.servlet.Servlet;
34 |
35 | import org.apache.commons.logging.Log;
36 | import org.apache.commons.logging.LogFactory;
37 |
38 | import org.springframework.aop.scope.ScopedProxyUtils;
39 | import org.springframework.beans.factory.ListableBeanFactory;
40 | import org.springframework.beans.factory.support.BeanDefinitionRegistry;
41 | import org.springframework.core.annotation.AnnotationAwareOrderComparator;
42 | import org.springframework.util.LinkedMultiValueMap;
43 | import org.springframework.util.MultiValueMap;
44 |
45 | /**
46 | * A copy of org.springframework.boot.web.servlet.ServletContextInitializerBeans without Servlet 3.0 API calls.
47 | *
48 | * A collection {@link ServletContextInitializer}s obtained from a
49 | * {@link ListableBeanFactory}. Includes all {@link ServletContextInitializer} beans and
50 | * also adapts {@link Servlet}, {@link Filter} and certain {@link EventListener} beans.
51 | *
52 | * Items are sorted so that adapted beans are top ({@link Servlet}, {@link Filter} then
53 | * {@link EventListener}) and direct {@link ServletContextInitializer} beans are at the
54 | * end. Further sorting is applied within these groups using the
55 | * {@link AnnotationAwareOrderComparator}.
56 | *
57 | * @author Dave Syer
58 | * @author Phillip Webb
59 | * @author Daniel Cruver
60 | * @since 2.0.0
61 | */
62 | public class LegacyServletContextInitializerBeans
63 | extends AbstractCollection {
64 |
65 | private static final String DISPATCHER_SERVLET_NAME = "dispatcherServlet";
66 |
67 | private static final Log logger = LogFactory
68 | .getLog(ServletContextInitializerBeans.class);
69 |
70 | /**
71 | * Seen bean instances or bean names.
72 | */
73 | private final Set