private void loadConfig(String... configLocations) { for (int i=0; i<configLocations.length; i++) { configLocations[i] = getClass().getName().replaceAll("\\.", "/") + "-" + configLocations[i]; } XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocations(configLocations); context.setServletContext(new MockServletContext()); context.refresh(); this.context = context; context.getAutowireCapableBeanFactory().autowireBean(this); Filter springSecurityFilterChain = context.getBean("springSecurityFilterChain", Filter.class); mockMvc = MockMvcBuilders .standaloneSetup(new FooController()) .addFilters(springSecurityFilterChain) .build(); }
/** * Loads the bean definitions via an XmlBeanDefinitionReader. * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader * @see #initBeanDefinitionReader * @see #loadBeanDefinitions */ @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }
@Test @SuppressWarnings("resource") public void withoutMessageSource() throws Exception { MockServletContext sc = new MockServletContext(""); XmlWebApplicationContext wac = new XmlWebApplicationContext(); wac.setParent(root); wac.setServletContext(sc); wac.setNamespace("testNamespace"); wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"}); wac.refresh(); try { wac.getMessage("someMessage", null, Locale.getDefault()); fail("Should have thrown NoSuchMessageException"); } catch (NoSuchMessageException ex) { // expected; } String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault()); assertTrue("Default message returned", "default".equals(msg)); }
private void loadBeanDefinitions(String fileName) { this.appContext.setConfigLocation("classpath:org/springframework/web/servlet/config/" + fileName); this.appContext.refresh(); }
@Before public void setUp() { XmlWebApplicationContext wac = new XmlWebApplicationContext(); wac.setConfigLocations(CONTEXT); wac.refresh(); this.context = wac; }
public SpringTestContext configLocations(String... configLocations) { XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocations(configLocations); this.context = context; return this; }
@Override public void init(ServletConfig config) throws ServletException { applicationContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()); if (config.getInitParameter(CONTEXT_CONFIG_LOCATION_PARAMETER) != null) { XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setParent(applicationContext); context.setConfigLocation(config.getInitParameter(CONTEXT_CONFIG_LOCATION_PARAMETER)); context.setServletConfig(config); context.setServletContext(config.getServletContext()); context.refresh(); applicationContext = context; } if (config.getInitParameter(SYSTEM_MESSAGES_BEAN_NAME_PARAMETER) != null) { systemMessagesBeanName = config.getInitParameter(SYSTEM_MESSAGES_BEAN_NAME_PARAMETER); logger.debug("found SYSTEM_MESSAGES_BEAN_NAME_PARAMETER: {}", systemMessagesBeanName); } if (SpringApplicationContext.getApplicationContext() == null) { SpringApplicationContext.setApplicationContext(applicationContext); } super.init(config); }
XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { contextConfigLocation }); appctx.setParent(parentAppCtx); } else { log.warn("{} bean was not found in context: {}", defaultParentContextKey, applicationContext.getDisplayName()); ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader"); parentAppCtx = contextLoader.getContext(defaultParentContextKey); appctx.setParent(parentAppCtx); } else { log.debug("Context loader was not found, trying JMX"); proxy = JMX.newMXBeanProxy(mbs, oName, ContextLoaderMXBean.class, true); log.debug("Context loader was found"); proxy.setParentContext(defaultParentContextKey, appctx.getId()); } else { log.warn("Context loader was not found"); if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); appctx.setServletContext(servletContext); appctx.refresh();
ServletConfig servletConfig, String location) { XmlWebApplicationContext ctx2 = new XmlWebApplicationContext(); createdContext = ctx2; ctx2.setServletConfig(servletConfig); Resource r = ctx2.getResource(location); try { InputStream in = r.getInputStream(); r = ctx2.getResource("classpath:" + location); try { r.getInputStream().close(); ctx2.setParent(ctx); String[] names = ctx.getBeanNamesForType(Bus.class); if (names == null || names.length == 0) { ctx2.setConfigLocations(new String[] {"classpath:/META-INF/cxf/cxf.xml", location}); } else { ctx2.setConfigLocations(new String[] {location}); ctx2.setConfigLocations(new String[] {"classpath:/META-INF/cxf/cxf.xml", location}); createdContext = ctx2; ctx2.refresh(); return ctx2;
public static void clearDatabase() { webApplicationContext = new XmlWebApplicationContext(); webApplicationContext.setEnvironment(getMockEnvironment()); webApplicationContext.setConfigLocations("classpath:spring/env.xml", "classpath:spring/data-source.xml"); webApplicationContext.refresh(); webApplicationContext.getBean(Flyway.class).clean(); webApplicationContext.destroy(); }
@Test public void abstractRefreshableWAC_respectsProgrammaticConfigLocations() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); ctx.setConfigLocation("programmatic.xml"); ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML assertTrue(t.getMessage(), t.getMessage().endsWith( "Could not open ServletContext resource [/programmatic.xml]")); } }
@Test public void configureWhenUserDetailsServiceInParentContextThenLocatesSuccessfully() { assertThatCode(() -> this.spring.configLocations(this.xml("MissingUserDetailsService")).autowire()) .isInstanceOf(BeansException.class); try ( XmlWebApplicationContext parent = new XmlWebApplicationContext() ) { parent.setConfigLocations(this.xml("AutoConfig")); parent.refresh(); try ( XmlWebApplicationContext child = new XmlWebApplicationContext() ) { child.setParent(parent); child.setConfigLocation(this.xml("MissingUserDetailsService")); child.refresh(); } } }
public void afterPropertiesSet() throws Exception { if (loadContext) { context = new XmlWebApplicationContext(); context.setParent(parent); context.setDisplayName(displayName); context.setConfigLocations(configLocations); context.setServletContext(servletContext); context.refresh(); } }
public static XmlWebApplicationContext setUpContext() { webApplicationContext = new XmlWebApplicationContext(); MockEnvironment mockEnvironment = getMockEnvironment(); webApplicationContext.setEnvironment(mockEnvironment); webApplicationContext.setServletContext(new MockServletContext() { @Override public <Type extends EventListener> void addListener(Type t) { //no op } }); new YamlServletProfileInitializerContextInitializer() .initializeContext(webApplicationContext, "endpoint_test_config.yml,uaa.yml,login.yml,required_configuration.yml"); webApplicationContext.setConfigLocation("file:./src/main/webapp/WEB-INF/spring-servlet.xml"); webApplicationContext.refresh(); webApplicationContext.registerShutdownHook(); EventFactory honeycombEventFactory = honeycombEventFactory( System.getenv("HONEYCOMB_KEY"), System.getenv("HONEYCOMB_DATASET"), Optional.ofNullable(System.getProperty("testId")).orElse("-1") ); honeycombAuditEventTestListenerAuthenticationFailureLockedEvent( webApplicationContext, honeycombEventFactory); honeycombAuditEventTestListenerIdentityProviderAuthenticationFailureEvent( webApplicationContext, honeycombEventFactory); honeycombAuditEventTestListenerMfaAuthenticationFailureEvent( webApplicationContext, honeycombEventFactory); return webApplicationContext; }
/** * If context config locations have been specified neither against the application * context nor the context loader listener, then fall back to default values. */ @Test public void abstractRefreshableWAC_fallsBackToConventionBasedNaming() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); // no init-param set //sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML System.out.println(t.getMessage()); assertTrue(t.getMessage().endsWith( "Could not open ServletContext resource [/WEB-INF/applicationContext.xml]")); } }
@Override public void onStartup(final ServletContext servletContext) throws ServletException { final ApplicationContext parent = new ClassPathXmlApplicationContext(new String[ {"/com/mydomain/root.context.xml"}); XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocation("classpath:/com/mydomain/childContext.xml"); context.setParent(parent); ConfigurableWebApplicationContext webappContext = (ConfigurableWebApplicationContext) context; webappContext.setServletContext(servletContext); webappContext.refresh(); servletContext.addListener(new ContextLoaderListener(webappContext)); // ... register dispatcher servlets here ... }
protected WebApplicationContext createContextLoader(ServletContext servletContext) { XmlWebApplicationContext xmlWebApplicationContext = new XmlWebApplicationContext(); xmlWebApplicationContext.setServletContext(servletContext); xmlWebApplicationContext.setConfigLocations(getConfigLocations()); return xmlWebApplicationContext; }
@Override public void initialize(XmlWebApplicationContext ctx) { ctx.setAllowBeanDefinitionOverriding(true); ConfigurableEnvironment env = ctx.getEnvironment(); Set<String> aps = new LinkedHashSet<>(); Collections.addAll(aps, env.getActiveProfiles()); page.setAttribute(AppContextFinder.APP_CONTEXT_ATTRIB, ctx); ServletContext sc = ExecutionContext.getSession().getServletContext(); ctx.setDisplayName("Child XmlWebApplicationContext " + page); ctx.setParent(AppContextFinder.rootContext); ctx.setServletContext(sc); ctx.setConfigLocations(DEFAULT_LOCATIONS); } else { AppContextFinder.rootContext = ctx; env.getPropertySources().addLast(new DomainPropertySource(ctx)); env.setDefaultProfiles(Constants.PROFILE_ROOT_DEFAULT); ctx.setConfigLocations((String[]) ArrayUtils.addAll(Constants.DEFAULT_LOCATIONS, ctx.getConfigLocations())); ClasspathMessageSource.getInstance().setResourceLoader(ctx); registerSessionListener();
@Before public void setUp() throws Exception { TestMockServletContext servletContext = new TestMockServletContext(); appContext = new XmlWebApplicationContext(); appContext.setServletContext(servletContext); LocaleContextHolder.setLocale(Locale.US); String attributeName = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE; appContext.getServletContext().setAttribute(attributeName, appContext); handler = new TestController(); handlerMethod = new InvocableHandlerMethod(handler, TestController.class.getMethod("testBind", Date.class, Double.class, TestBean.class, BindingResult.class)); }
@Override protected ConfigurableApplicationContext createApplicationContext(URL url, ClassLoader loader) { final String resourceBases = System.getProperty("resourceBases"); final XmlWebApplicationContext context = resourceBases == null ? new XmlWebApplicationContext() : new DevXmlWebApplicationContext(resourceBases); context.setClassLoader(loader); context.setConfigLocation(url.toExternalForm()); context.setServletContext(servletContext); return context; }