Java Code Examples for org.springframework.web.context.WebApplicationContext

The following examples show how to use org.springframework.web.context.WebApplicationContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: DelegatingFilterProxy.java    License: MIT License 6 votes vote down vote up
/**
 * Return the {@code WebApplicationContext} passed in at construction time, if available.
 * Otherwise, attempt to retrieve a {@code WebApplicationContext} from the
 * {@code ServletContext} attribute with the {@linkplain #setContextAttribute
 * configured name} if set. Otherwise look up a {@code WebApplicationContext} under
 * the well-known "root" application context attribute. The
 * {@code WebApplicationContext} must have already been loaded and stored in the
 * {@code ServletContext} before this filter gets initialized (or invoked).
 * <p>Subclasses may override this method to provide a different
 * {@code WebApplicationContext} retrieval strategy.
 * @return the {@code WebApplicationContext} for this proxy, or {@code null} if not found
 * @see #DelegatingFilterProxy(String, WebApplicationContext)
 * @see #getContextAttribute()
 * @see WebApplicationContextUtils#getWebApplicationContext(javax.servlet.ServletContext)
 * @see WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
 */
@Nullable
protected WebApplicationContext findWebApplicationContext() {
	if (this.webApplicationContext != null) {
		// The user has injected a context at construction time -> use it...
		if (this.webApplicationContext instanceof ConfigurableApplicationContext) {
			ConfigurableApplicationContext cac = (ConfigurableApplicationContext) this.webApplicationContext;
			if (!cac.isActive()) {
				// The context has not yet been refreshed -> do so before returning it...
				cac.refresh();
			}
		}
		return this.webApplicationContext;
	}
	String attrName = getContextAttribute();
	if (attrName != null) {
		return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
	}
	else {
		return WebApplicationContextUtils.findWebApplicationContext(getServletContext());
	}
}
 
Example 2
private static CompositeUriComponentsContributor getConfiguredUriComponentsContributor() {
	WebApplicationContext wac = getWebApplicationContext();
	if (wac == null) {
		return null;
	}
	try {
		return wac.getBean(MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, CompositeUriComponentsContributor.class);
	}
	catch (NoSuchBeanDefinitionException ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("No CompositeUriComponentsContributor bean with name '" +
					MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME + "'");
		}
		return null;
	}
}
 
Example 3
Source Project: attic-rave   Source File: StaticContentTagTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void doStartTag_validKey() throws IOException, JspException {
    tag.setContentKey(VALID_CACHE_KEY);
    
    expect(service.getContent(VALID_CACHE_KEY)).andReturn(VALID_STATIC_CONTENT);
    expect(pageContext.getServletContext()).andReturn(servletContext).anyTimes();
    expect(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).andReturn(wContext).anyTimes();
    expect(wContext.getBean(StaticContentFetcherService.class)).andReturn(service).anyTimes();
    expect(pageContext.getOut()).andReturn(writer);
    replay(service, pageContext, servletContext, wContext, writer);

    int result = tag.doStartTag();

    assertThat(result, is(javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE));
    verify(service, pageContext, servletContext, wContext, writer);
}
 
Example 4
/**
 * Register web-specific scopes ("request", "session", "globalSession", "application")
 * with the given BeanFactory, as used by the WebApplicationContext.
 * @param beanFactory the BeanFactory to configure
 * @param sc the ServletContext that we're running within
 */
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) {
	beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
	beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false));
	beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true));
	if (sc != null) {
		ServletContextScope appScope = new ServletContextScope(sc);
		beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
		// Register as ServletContext attribute, for ContextCleanupListener to detect it.
		sc.setAttribute(ServletContextScope.class.getName(), appScope);
	}

	beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
	beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
	beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
	beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
	if (jsfPresent) {
		FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
	}
}
 
Example 5
Source Project: spring-cloud-dataflow   Source File: JobExecutionUtils.java    License: Apache License 2.0 6 votes vote down vote up
static MockMvc createBaseJobExecutionMockMvc(JobRepository jobRepository, TaskBatchDao taskBatchDao,
		TaskExecutionDao taskExecutionDao, WebApplicationContext wac, RequestMappingHandlerAdapter adapter) {
	MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac)
			.defaultRequest(get("/").accept(MediaType.APPLICATION_JSON)).build();
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_ORIG, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOO, 1);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FOOBAR, 2);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_COMPLETED, 1, BatchStatus.COMPLETED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STARTED, 1, BatchStatus.STARTED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_STOPPED, 1, BatchStatus.STOPPED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED1, 1, BatchStatus.FAILED);
	JobExecutionUtils.createSampleJob(jobRepository, taskBatchDao, taskExecutionDao, JOB_NAME_FAILED2, 1, BatchStatus.FAILED);
	for (HttpMessageConverter<?> converter : adapter.getMessageConverters()) {
		if (converter instanceof MappingJackson2HttpMessageConverter) {
			final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
			jacksonConverter.getObjectMapper().addMixIn(StepExecution.class, StepExecutionJacksonMixIn.class);
			jacksonConverter.getObjectMapper().addMixIn(ExecutionContext.class, ExecutionContextJacksonMixIn.class);
			jacksonConverter.getObjectMapper().setDateFormat(new ISO8601DateFormatWithMilliSeconds());
		}
	}
	return mockMvc;
}
 
Example 6
Source Project: spring-analysis-note   Source File: DelegatingFilterProxy.java    License: MIT License 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

	// Lazily initialize the delegate if necessary.
	Filter delegateToUse = this.delegate;
	if (delegateToUse == null) {
		synchronized (this.delegateMonitor) {
			delegateToUse = this.delegate;
			if (delegateToUse == null) {
				WebApplicationContext wac = findWebApplicationContext();
				if (wac == null) {
					throw new IllegalStateException("No WebApplicationContext found: " +
							"no ContextLoaderListener or DispatcherServlet registered?");
				}
				delegateToUse = initDelegate(wac);
			}
			this.delegate = delegateToUse;
		}
	}

	// Let the delegate perform the actual doFilter operation.
	invokeDelegate(delegateToUse, request, response, filterChain);
}
 
Example 7
protected List<IFrameDecoratorContainer> extractDecorators(RequestContext reqCtx) throws ApsSystemException {
	HttpServletRequest request = reqCtx.getRequest();
	WebApplicationContext wac = ApsWebApplicationUtils.getWebApplicationContext(request);
	List<IFrameDecoratorContainer> containters = new ArrayList<IFrameDecoratorContainer>();
	try {
		String[] beanNames = wac.getBeanNamesForType(IFrameDecoratorContainer.class);
		for (int i = 0; i < beanNames.length; i++) {
			IFrameDecoratorContainer container = (IFrameDecoratorContainer) wac.getBean(beanNames[i]);
			containters.add(container);
		}
		BeanComparator comparator = new BeanComparator("order");
		Collections.sort(containters, comparator);
	} catch (Throwable t) {
		_logger.error("Error extracting widget decorators", t);
		throw new ApsSystemException("Error extracting widget decorators", t);
	}
	return containters;
}
 
Example 8
Source Project: spring-analysis-note   Source File: DelegatingFilterProxyTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testDelegatingFilterProxyWithTargetBeanName() throws ServletException, IOException {
	MockServletContext sc = new MockServletContext();

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.registerSingleton("targetFilter", MockFilter.class);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");

	DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter");
	filterProxy.init(new MockFilterConfig(sc));

	MockHttpServletRequest request = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	filterProxy.doFilter(request, response, null);

	assertNull(targetFilter.filterConfig);
	assertEquals(Boolean.TRUE, request.getAttribute("called"));

	filterProxy.destroy();
	assertNull(targetFilter.filterConfig);
}
 
Example 9
Source Project: spring4-understanding   Source File: SpringConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
private String getBeanNameByType(WebApplicationContext wac, Class<?> endpointClass) {
	String wacId = wac.getId();

	Map<Class<?>, String> beanNamesByType = cache.get(wacId);
	if (beanNamesByType == null) {
		beanNamesByType = new ConcurrentHashMap<Class<?>, String>();
		cache.put(wacId, beanNamesByType);
	}

	if (!beanNamesByType.containsKey(endpointClass)) {
		String[] names = wac.getBeanNamesForType(endpointClass);
		if (names.length == 1) {
			beanNamesByType.put(endpointClass, names[0]);
		}
		else {
			beanNamesByType.put(endpointClass, NO_VALUE);
			if (names.length > 1) {
				throw new IllegalStateException("Found multiple @ServerEndpoint's of type [" +
						endpointClass.getName() + "]: bean names " + Arrays.asList(names));
			}
		}
	}

	String beanName = beanNamesByType.get(endpointClass);
	return (NO_VALUE.equals(beanName) ? null : beanName);
}
 
Example 10
@Test
public void testProcessInjectionBasedOnServletContext() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("name", "tb");
	wac.registerSingleton("testBean", TestBean.class, pvs);

	MockServletContext sc = new MockServletContext();
	wac.setServletContext(sc);
	wac.refresh();
	sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	InjectionTarget target = new InjectionTarget();
	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
	assertTrue(target.testBean instanceof TestBean);
	assertEquals("tb", target.name);
}
 
Example 11
@Test
public void pathVarsInModel() throws Exception {
	final Map<String, Object> pathVars = new HashMap<>();
	pathVars.put("hotel", "42");
	pathVars.put("booking", 21);
	pathVars.put("other", "other");

	WebApplicationContext wac =
		initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() {
			@Override
			public void initialize(GenericWebApplicationContext context) {
				RootBeanDefinition beanDef = new RootBeanDefinition(ModelValidatingViewResolver.class);
				beanDef.getConstructorArgumentValues().addGenericArgumentValue(pathVars);
				context.registerBeanDefinition("viewResolver", beanDef);
			}
		}, ViewRenderingController.class);

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42;q=1,2/bookings/21-other;q=3;r=R");
	getServlet().service(request, new MockHttpServletResponse());

	ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class);
	assertEquals(3, resolver.validatedAttrCount);
}
 
Example 12
Source Project: java-technology-stack   Source File: MockMvcBuilderSupport.java    License: MIT License 6 votes vote down vote up
protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig,
		WebApplicationContext webAppContext, @Nullable RequestBuilder defaultRequestBuilder,
		List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers,
		@Nullable List<DispatcherServletCustomizer> dispatcherServletCustomizers) {

	TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext);
	if (dispatcherServletCustomizers != null) {
		for (DispatcherServletCustomizer customizers : dispatcherServletCustomizers) {
			customizers.customize(dispatcherServlet);
		}
	}
	try {
		dispatcherServlet.init(servletConfig);
	}
	catch (ServletException ex) {
		// should never happen..
		throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
	}

	MockMvc mockMvc = new MockMvc(dispatcherServlet, filters);
	mockMvc.setDefaultRequest(defaultRequestBuilder);
	mockMvc.setGlobalResultMatchers(globalResultMatchers);
	mockMvc.setGlobalResultHandlers(globalResultHandlers);

	return mockMvc;
}
 
Example 13
@Override
protected void before() throws Throwable {
	originalConfigLocation = System.getProperty("spring.config.location");
	if (!StringUtils.isEmpty(configurationLocation)) {
		System.setProperty("spring.config.location", configurationLocation);
	}

	app = new SpringApplication(LocalTestDataFlowServer.class);
	configurableApplicationContext = (WebApplicationContext) app.run(new String[]{"--server.port=0"});

	Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values();
	mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext)
			.addFilters(filters.toArray(new Filter[filters.size()]))
			.build();
	dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}");
}
 
Example 14
Source Project: Lottery   Source File: MessageResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获得国际化信息
 * 
 * @param request
 *            HttpServletRequest
 * @param code
 *            国际化代码
 * @param args
 *            替换参数
 * @return
 * @see org.springframework.context.MessageSource#getMessage(String,
 *      Object[], Locale)
 */
public static String getMessage(HttpServletRequest request, String code,
		Object... args) {
	WebApplicationContext messageSource = RequestContextUtils
			.getWebApplicationContext(request);
	if (messageSource == null) {
		throw new IllegalStateException("WebApplicationContext not found!");
	}
	LocaleResolver localeResolver = RequestContextUtils
			.getLocaleResolver(request);
	Locale locale;
	if (localeResolver != null) {
		locale = localeResolver.resolveLocale(request);
	} else {
		locale = request.getLocale();
	}
	return messageSource.getMessage(code, args, locale);
}
 
Example 15
Source Project: java-technology-stack   Source File: WebApplicationContextUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Find a custom {@code WebApplicationContext} for this web app.
 * @param sc the ServletContext to find the web application context for
 * @param attrName the name of the ServletContext attribute to look for
 * @return the desired WebApplicationContext for this web app, or {@code null} if none
 */
@Nullable
public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
	Assert.notNull(sc, "ServletContext must not be null");
	Object attr = sc.getAttribute(attrName);
	if (attr == null) {
		return null;
	}
	if (attr instanceof RuntimeException) {
		throw (RuntimeException) attr;
	}
	if (attr instanceof Error) {
		throw (Error) attr;
	}
	if (attr instanceof Exception) {
		throw new IllegalStateException((Exception) attr);
	}
	if (!(attr instanceof WebApplicationContext)) {
		throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
	}
	return (WebApplicationContext) attr;
}
 
Example 16
Source Project: spring-analysis-note   Source File: AbstractTagTests.java    License: MIT License 6 votes vote down vote up
protected MockPageContext createPageContext() {
	MockServletContext sc = new MockServletContext();
	SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
	wac.setServletContext(sc);
	wac.setNamespace("test");
	wac.refresh();

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	MockHttpServletResponse response = new MockHttpServletResponse();
	if (inDispatcherServlet()) {
		request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
		LocaleResolver lr = new AcceptHeaderLocaleResolver();
		request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
		ThemeResolver tr = new FixedThemeResolver();
		request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
		request.setAttribute(DispatcherServlet.THEME_SOURCE_ATTRIBUTE, wac);
	}
	else {
		sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	}

	return new MockPageContext(sc, request, response);
}
 
Example 17
Source Project: spring-analysis-note   Source File: TomcatWebSocketTestServer.java    License: MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example 18
Source Project: java-technology-stack   Source File: TomcatWebSocketTestServer.java    License: MIT License 6 votes vote down vote up
@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
	Assert.state(this.port != -1, "setup() was never called.");
	this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
	this.context.addApplicationListener(WsContextListener.class.getName());
	Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
	this.context.addServletMappingDecoded("/", "dispatcherServlet");
	for (Filter filter : filters) {
		FilterDef filterDef = new FilterDef();
		filterDef.setFilterName(filter.getClass().getName());
		filterDef.setFilter(filter);
		filterDef.setAsyncSupported("true");
		this.context.addFilterDef(filterDef);
		FilterMap filterMap = new FilterMap();
		filterMap.setFilterName(filter.getClass().getName());
		filterMap.addURLPattern("/*");
		filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
		this.context.addFilterMap(filterMap);
	}
}
 
Example 19
Source Project: archiva   Source File: RepositoryServlet.java    License: Apache License 2.0 5 votes vote down vote up
public void initServers( ServletConfig servletConfig ) {

        long start = System.currentTimeMillis();

        WebApplicationContext wac =
            WebApplicationContextUtils.getRequiredWebApplicationContext( servletConfig.getServletContext() );

        rwLock.writeLock().lock();
        try {
            configuration = wac.getBean("archivaConfiguration#default", ArchivaConfiguration.class);
            configuration.addListener(this);

            repositoryRegistry = wac.getBean( ArchivaRepositoryRegistry.class);
            resourceFactory = wac.getBean("davResourceFactory#archiva", DavResourceFactory.class);
            locatorFactory = new ArchivaDavLocatorFactory();

            ServletAuthenticator servletAuth = wac.getBean(ServletAuthenticator.class);
            HttpAuthenticator httpAuth = wac.getBean("httpAuthenticator#basic", HttpAuthenticator.class);

            sessionProvider = new ArchivaDavSessionProvider(servletAuth, httpAuth);
        } finally {
            rwLock.writeLock().unlock();
        }
        long end = System.currentTimeMillis();

        log.debug( "initServers done in {} ms", (end - start) );
    }
 
Example 20
Source Project: flowable-engine   Source File: WebConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent sce) {
    LOGGER.info("Destroying Web application");
    WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext());
    AnnotationConfigWebApplicationContext gwac = (AnnotationConfigWebApplicationContext) ac;
    gwac.close();
    LOGGER.debug("Web application destroyed");
}
 
Example 21
private Vector<String> getAgnTags(String content, HttpServletRequest req) {
	WebApplicationContext context = getApplicationContext(req);
	ComMailing mailing = mailingFactory.newMailing();

	mailing.init(AgnUtils.getCompanyID(req), context);
	try {
		return mailing.findDynTagsInTemplates(content, context);
	} catch (Exception e) {
		logger.error("Error occurred: " + e.getMessage(), e);
		return new Vector<>();
	}
}
 
Example 22
Source Project: webcurator   Source File: ApplicationContextFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the WebApplicationContext.
 * @param aWebApplicationContext the WebApplicationContext to set
 */
public static void setWebApplicationContext(WebApplicationContext aWebApplicationContext) {
    synchronized (mutex) {
        if (instance == null) {
            instance = new ApplicationContextFactory(aWebApplicationContext);
        }
        else {
            instance.wac = aWebApplicationContext;
        }
    }
}
 
Example 23
Source Project: spring-analysis-note   Source File: MvcUriComponentsBuilder.java    License: MIT License 5 votes vote down vote up
private static String getPathPrefix(Class<?> controllerType) {
	WebApplicationContext wac = getWebApplicationContext();
	if (wac != null) {
		Map<String, RequestMappingHandlerMapping> map = wac.getBeansOfType(RequestMappingHandlerMapping.class);
		for (RequestMappingHandlerMapping mapping : map.values()) {
			if (mapping.isHandler(controllerType)) {
				String prefix = mapping.getPathPrefix(controllerType);
				if (prefix != null) {
					return prefix;
				}
			}
		}
	}
	return "";
}
 
Example 24
Source Project: sakai   Source File: RoleFilter.java    License: Educational Community License v2.0 5 votes vote down vote up
public void init(FilterConfig filterConfig) throws ServletException {
      if(log.isInfoEnabled()) log.info("Initializing sections role filter");

      ac = (ApplicationContext)filterConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

      authnBeanName = filterConfig.getInitParameter("authnServiceBean");
authzBeanName = filterConfig.getInitParameter("authzServiceBean");
contextBeanName = filterConfig.getInitParameter("contextManagementServiceBean");
authorizationFilterConfigurationBeanName = filterConfig.getInitParameter("authorizationFilterConfigurationBean");
selectSiteRedirect = filterConfig.getInitParameter("selectSiteRedirect");
  }
 
Example 25
Source Project: java-technology-stack   Source File: StandaloneMockMvcBuilder.java    License: MIT License 5 votes vote down vote up
private List<ViewResolver> initViewResolvers(WebApplicationContext wac) {
	this.viewResolvers = (this.viewResolvers != null ? this.viewResolvers :
			Collections.singletonList(new InternalResourceViewResolver()));
	for (Object viewResolver : this.viewResolvers) {
		if (viewResolver instanceof WebApplicationObjectSupport) {
			((WebApplicationObjectSupport) viewResolver).setApplicationContext(wac);
		}
	}
	return this.viewResolvers;
}
 
Example 26
/**
 * Look up the SessionFactory that this filter should use.
 * <p>The default implementation looks for a bean with the specified name
 * in Spring's root application context.
 * @return the SessionFactory to use
 * @see #getSessionFactoryBeanName
 */
protected SessionFactory lookupSessionFactory() {
	if (logger.isDebugEnabled()) {
		logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "' for OpenSessionInViewFilter");
	}
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	return wac.getBean(getSessionFactoryBeanName(), SessionFactory.class);
}
 
Example 27
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	TestMockServletContext servletContext = new TestMockServletContext();
	appContext = new GenericWebApplicationContext();
	appContext.setServletContext(servletContext);
	LocaleContextHolder.setLocale(Locale.US);

	String attributeName = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	appContext.getServletContext().setAttribute(attributeName, appContext);

	handler = new TestController();
	Method method = TestController.class.getMethod("testBind", Date.class, Double.class, TestBean.class, BindingResult.class);
	handlerMethod = new InvocableHandlerMethod(handler, method);
}
 
Example 28
/**
 * {@inheritDoc}
 * <p>This implementation creates an {@link AnnotationConfigWebApplicationContext},
 * providing it the annotated classes returned by {@link #getServletConfigClasses()}.
 */
@Override
protected WebApplicationContext createServletApplicationContext() {
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	Class<?>[] configClasses = getServletConfigClasses();
	if (!ObjectUtils.isEmpty(configClasses)) {
		context.register(configClasses);
	}
	return context;
}
 
Example 29
Source Project: alf.io   Source File: SpringBootInitializer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
        WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext);
        ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class);
        SessionCookieConfig config = servletContext.getSessionCookieConfig();
        config.setHttpOnly(true);
        config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
        // force log initialization, then disable it
        XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
        XRLog.setLoggingEnabled(false);
    };
}
 
Example 30
Source Project: spring-analysis-note   Source File: FrameworkServlet.java    License: MIT License 5 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
	// 允许我们自定义容器的类型,通过 contextClass 属性进行配置
	// 但是类型必须要继承 ConfigurableWebApplicationContext,不然将会报错
	Class<?> contextClass = getContextClass();
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	// 通过反射来创建 contextClass
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	// 获取 contextConfigLocation 属性,配置在 servlet 初始化函数中
	String configLocation = getContextConfigLocation();
	if (configLocation != null) {
		wac.setConfigLocation(configLocation);
	}
	// 初始化 Spring 环境包括加载配置环境
	configureAndRefreshWebApplicationContext(wac);

	return wac;
}