Fast forward existing prototype work
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.bootstrap.sampleconfig.MyComponent;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Tests for {@link BeanDefinitionLoader}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class BeanDefinitionLoaderTests {
|
||||
|
||||
// FIXME
|
||||
|
||||
private StaticApplicationContext registry;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.registry = new StaticApplicationContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadClass() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
MyComponent.class);
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myComponent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadXmlResource() throws Exception {
|
||||
ClassPathResource resource = new ClassPathResource("sample-beans.xml", getClass());
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, resource);
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myXmlComponent"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadPackage() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
MyComponent.class.getPackage());
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myComponent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadClassName() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
MyComponent.class.getName());
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myComponent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadResourceName() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
"classpath:org/springframework/bootstrap/sample-beans.xml");
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myXmlComponent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadPackageName() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
MyComponent.class.getPackage().getName());
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myComponent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadPackageAndClassDoesNotDoubleAdd() throws Exception {
|
||||
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry,
|
||||
MyComponent.class.getPackage(), MyComponent.class);
|
||||
int loaded = loader.load();
|
||||
assertThat(loaded, equalTo(1));
|
||||
assertTrue(this.registry.containsBean("myComponent"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2010-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.SimpleCommandLinePropertySource;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link ConfigFileApplicationContextInitializer}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class ConfigFileApplicationContextInitializerTests {
|
||||
|
||||
private StaticApplicationContext context = new StaticApplicationContext();
|
||||
|
||||
private ConfigFileApplicationContextInitializer initializer = new ConfigFileApplicationContextInitializer();
|
||||
|
||||
@Test
|
||||
public void loadPropertiesFile() throws Exception {
|
||||
this.initializer.setName("testproperties");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("frompropertiesfile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadYamlFile() throws Exception {
|
||||
this.initializer.setName("testyaml");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromyamlfile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commandLineWins() throws Exception {
|
||||
this.context
|
||||
.getEnvironment()
|
||||
.getPropertySources()
|
||||
.addFirst(
|
||||
new SimpleCommandLinePropertySource(
|
||||
"--my.property=fromcommandline"));
|
||||
this.initializer.setName("testproperties");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromcommandline"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadPropertiesThenProfileProperties() throws Exception {
|
||||
this.initializer.setName("enableprofile");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromprofilepropertiesfile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void yamlProfiles() throws Exception {
|
||||
this.initializer.setName("testprofiles");
|
||||
this.context.getEnvironment().setActiveProfiles("dev");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromdevprofile"));
|
||||
property = this.context.getEnvironment().getProperty("my.other");
|
||||
assertThat(property, equalTo("notempty"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void yamlSetsProfiles() throws Exception {
|
||||
this.initializer.setName("testsetprofiles");
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromdevprofile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificNameAndProfileFromExistingSource() throws Exception {
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("spring.profiles.active", "specificprofile");
|
||||
map.put("spring.config.name", "specificfile");
|
||||
MapPropertySource source = new MapPropertySource("map", map);
|
||||
this.context.getEnvironment().getPropertySources().addFirst(source);
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromspecificpropertiesfile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificResource() throws Exception {
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("spring.config.location", "classpath:/specificlocation.properties");
|
||||
MapPropertySource source = new MapPropertySource("map", map);
|
||||
this.context.getEnvironment().getPropertySources().addFirst(source);
|
||||
this.initializer.initialize(this.context);
|
||||
String property = this.context.getEnvironment().getProperty("my.property");
|
||||
assertThat(property, equalTo("fromspecificlocation"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.context.ApplicationContextException;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/**
|
||||
* Tests for {@link EnvironmentDelegateApplicationContextInitializer}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class EnvironmentDelegateApplicationContextInitializerTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private EnvironmentDelegateApplicationContextInitializer initializer = new EnvironmentDelegateApplicationContextInitializer();
|
||||
|
||||
@Test
|
||||
public void orderedInitialize() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("context.initializer.classes", MockInitB.class.getName() + ","
|
||||
+ MockInitA.class.getName());
|
||||
PropertySource<?> propertySource = new MapPropertySource("map", map);
|
||||
context.getEnvironment().getPropertySources().addFirst(propertySource);
|
||||
this.initializer.initialize(context);
|
||||
assertThat(context.getBeanFactory().getSingleton("a"), equalTo((Object) "a"));
|
||||
assertThat(context.getBeanFactory().getSingleton("b"), equalTo((Object) "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noInitializers() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
this.initializer.initialize(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyInitializers() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("context.initializer.classes", "");
|
||||
PropertySource<?> propertySource = new MapPropertySource("map", map);
|
||||
context.getEnvironment().getPropertySources().addFirst(propertySource);
|
||||
this.initializer.initialize(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSuchInitializerClass() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("context.initializer.classes", "missing.madeup.class");
|
||||
PropertySource<?> propertySource = new MapPropertySource("map", map);
|
||||
context.getEnvironment().getPropertySources().addFirst(propertySource);
|
||||
this.thrown.expect(ApplicationContextException.class);
|
||||
this.initializer.initialize(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notAnInitializerClass() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("context.initializer.classes", Object.class.getName());
|
||||
PropertySource<?> propertySource = new MapPropertySource("map", map);
|
||||
context.getEnvironment().getPropertySources().addFirst(propertySource);
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.initializer.initialize(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void genericNotSuitable() throws Exception {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
Map<String, Object> map = new HashMap<String, Object>();
|
||||
map.put("context.initializer.classes", NotSuitableInit.class.getName());
|
||||
PropertySource<?> propertySource = new MapPropertySource("map", map);
|
||||
context.getEnvironment().getPropertySources().addFirst(propertySource);
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("generic parameter");
|
||||
this.initializer.initialize(context);
|
||||
}
|
||||
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
private static class MockInitA implements
|
||||
ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
applicationContext.getBeanFactory().registerSingleton("a", "a");
|
||||
}
|
||||
}
|
||||
|
||||
@Order(Ordered.LOWEST_PRECEDENCE)
|
||||
private static class MockInitB implements
|
||||
ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
assertThat(applicationContext.getBeanFactory().getSingleton("a"),
|
||||
equalTo((Object) "a"));
|
||||
applicationContext.getBeanFactory().registerSingleton("b", "b");
|
||||
}
|
||||
}
|
||||
|
||||
private static class NotSuitableInit implements
|
||||
ApplicationContextInitializer<ConfigurableWebApplicationContext> {
|
||||
@Override
|
||||
public void initialize(ConfigurableWebApplicationContext applicationContext) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.BeanNameGenerator;
|
||||
import org.springframework.beans.factory.support.DefaultBeanNameGenerator;
|
||||
import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
|
||||
import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigUtils;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.env.CommandLinePropertySource;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.instanceOf;
|
||||
import static org.hamcrest.Matchers.sameInstance;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* Tests for {@link SpringApplication}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class SpringApplicationTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
@After
|
||||
public void close() {
|
||||
if (this.context instanceof ConfigurableApplicationContext) {
|
||||
((ConfigurableApplicationContext) this.context).close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourcesMustNotBeNull() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Sources must not be empty");
|
||||
new SpringApplication((Object[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourcesMustNotBeEmpty() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("Sources must not be empty");
|
||||
new SpringApplication();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableBanner() throws Exception {
|
||||
SpringApplication application = spy(new SpringApplication(ExampleConfig.class));
|
||||
application.setWebEnvironment(false);
|
||||
application.setShowBanner(false);
|
||||
application.run();
|
||||
verify(application, never()).printBanner();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customBanner() throws Exception {
|
||||
SpringApplication application = spy(new SpringApplication(ExampleConfig.class));
|
||||
application.setWebEnvironment(false);
|
||||
application.run();
|
||||
verify(application).printBanner();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificApplicationContext() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleConfig.class);
|
||||
ApplicationContext applicationContext = new StaticApplicationContext();
|
||||
application.setApplicationContext(applicationContext);
|
||||
this.context = application.run();
|
||||
assertThat(this.context, sameInstance(applicationContext));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificApplicationContextClass() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleConfig.class);
|
||||
application.setApplicationContextClass(StaticApplicationContext.class);
|
||||
this.context = application.run();
|
||||
assertThat(this.context, instanceOf(StaticApplicationContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultApplicationContext() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
this.context = application.run();
|
||||
assertThat(this.context, instanceOf(AnnotationConfigApplicationContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultApplicationContextForWeb() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleWebConfig.class);
|
||||
application.setWebEnvironment(true);
|
||||
this.context = application.run();
|
||||
assertThat(this.context,
|
||||
instanceOf(AnnotationConfigEmbeddedWebApplicationContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customEnvironment() throws Exception {
|
||||
TestSpringApplication application = new TestSpringApplication(ExampleConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
StaticApplicationContext applicationContext = spy(new StaticApplicationContext());
|
||||
ConfigurableEnvironment environment = new StandardEnvironment();
|
||||
application.setApplicationContext(applicationContext);
|
||||
application.setEnvironment(environment);
|
||||
application.run();
|
||||
verify(applicationContext).setEnvironment(environment);
|
||||
verify(application.getLoader()).setEnvironment(environment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customResourceLoader() throws Exception {
|
||||
TestSpringApplication application = new TestSpringApplication(ExampleConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
StaticApplicationContext applicationContext = spy(new StaticApplicationContext());
|
||||
ResourceLoader resourceLoader = new DefaultResourceLoader();
|
||||
application.setApplicationContext(applicationContext);
|
||||
application.setResourceLoader(resourceLoader);
|
||||
application.run();
|
||||
verify(applicationContext).setResourceLoader(resourceLoader);
|
||||
verify(application.getLoader()).setResourceLoader(resourceLoader);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customResourceLoaderFromConstructor() throws Exception {
|
||||
ResourceLoader resourceLoader = new DefaultResourceLoader();
|
||||
TestSpringApplication application = new TestSpringApplication(resourceLoader,
|
||||
ExampleWebConfig.class);
|
||||
StaticApplicationContext applicationContext = spy(new StaticApplicationContext());
|
||||
application.setApplicationContext(applicationContext);
|
||||
application.run();
|
||||
verify(applicationContext).setResourceLoader(resourceLoader);
|
||||
verify(application.getLoader()).setResourceLoader(resourceLoader);
|
||||
applicationContext.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customBeanNameGenerator() throws Exception {
|
||||
TestSpringApplication application = new TestSpringApplication(
|
||||
ExampleWebConfig.class);
|
||||
StaticWebApplicationContext applicationContext = spy(new StaticWebApplicationContext());
|
||||
applicationContext.setServletContext(new MockServletContext());
|
||||
BeanNameGenerator beanNameGenerator = new DefaultBeanNameGenerator();
|
||||
application.setApplicationContext(applicationContext);
|
||||
application.setBeanNameGenerator(beanNameGenerator);
|
||||
this.context = application.run();
|
||||
verify(application.getLoader()).setBeanNameGenerator(beanNameGenerator);
|
||||
assertThat(
|
||||
this.context
|
||||
.getBean(AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR),
|
||||
sameInstance((Object) beanNameGenerator));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commandLinePropertySource() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
ConfigurableEnvironment environment = new StandardEnvironment();
|
||||
application.setEnvironment(environment);
|
||||
application.run();
|
||||
assertThat(hasPropertySource(environment, CommandLinePropertySource.class),
|
||||
equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableCommandLinePropertySource() throws Exception {
|
||||
SpringApplication application = new SpringApplication(ExampleConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
application.setAddCommandLineProperties(false);
|
||||
ConfigurableEnvironment environment = new StandardEnvironment();
|
||||
application.setEnvironment(environment);
|
||||
application.run();
|
||||
assertThat(hasPropertySource(environment, CommandLinePropertySource.class),
|
||||
equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runCommandLineRunners() throws Exception {
|
||||
SpringApplication application = new SpringApplication(CommandLineRunConfig.class);
|
||||
application.setWebEnvironment(false);
|
||||
this.context = application.run("arg");
|
||||
assertTrue(this.context.getBean("runnerA", TestCommandLineRunner.class).hasRun());
|
||||
assertTrue(this.context.getBean("runnerB", TestCommandLineRunner.class).hasRun());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadSources() throws Exception {
|
||||
Object[] sources = { ExampleConfig.class, "a", TestCommandLineRunner.class };
|
||||
TestSpringApplication application = new TestSpringApplication(sources);
|
||||
application.setWebEnvironment(false);
|
||||
application.setUseMockLoader(true);
|
||||
application.run();
|
||||
assertThat(application.getSources(), equalTo(sources));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
this.context = SpringApplication.run(ExampleWebConfig.class);
|
||||
assertNotNull(this.context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runComponents() throws Exception {
|
||||
this.context = SpringApplication.runComponents(new Class<?>[] {
|
||||
ExampleWebConfig.class, Object.class });
|
||||
assertNotNull(this.context);
|
||||
}
|
||||
|
||||
private boolean hasPropertySource(ConfigurableEnvironment environment,
|
||||
Class<?> propertySourceClass) {
|
||||
for (PropertySource<?> source : environment.getPropertySources()) {
|
||||
if (propertySourceClass.isInstance(source)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// FIXME test initializers
|
||||
|
||||
// FIXME test config files?
|
||||
|
||||
private static class TestSpringApplication extends SpringApplication {
|
||||
|
||||
private BeanDefinitionLoader loader;
|
||||
|
||||
private boolean useMockLoader;
|
||||
|
||||
private Object[] sources;
|
||||
|
||||
public TestSpringApplication(Object... sources) {
|
||||
super(sources);
|
||||
}
|
||||
|
||||
public TestSpringApplication(ResourceLoader resourceLoader, Object... sources) {
|
||||
super(resourceLoader, sources);
|
||||
}
|
||||
|
||||
public void setUseMockLoader(boolean useMockLoader) {
|
||||
this.useMockLoader = useMockLoader;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BeanDefinitionLoader createBeanDefinitionLoader(
|
||||
BeanDefinitionRegistry registry, Object[] sources) {
|
||||
this.sources = sources;
|
||||
if (this.useMockLoader) {
|
||||
this.loader = mock(BeanDefinitionLoader.class);
|
||||
} else {
|
||||
this.loader = spy(super.createBeanDefinitionLoader(registry, sources));
|
||||
}
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
public BeanDefinitionLoader getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
public Object[] getSources() {
|
||||
return this.sources;
|
||||
}
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ExampleConfig {
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class ExampleWebConfig {
|
||||
|
||||
@Bean
|
||||
public JettyEmbeddedServletContainerFactory container() {
|
||||
return new JettyEmbeddedServletContainerFactory();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Configuration
|
||||
static class CommandLineRunConfig {
|
||||
|
||||
@Bean
|
||||
public TestCommandLineRunner runnerB() {
|
||||
return new TestCommandLineRunner(Ordered.LOWEST_PRECEDENCE, "runnerA");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TestCommandLineRunner runnerA() {
|
||||
return new TestCommandLineRunner(Ordered.HIGHEST_PRECEDENCE);
|
||||
}
|
||||
}
|
||||
|
||||
static class TestCommandLineRunner implements CommandLineRunner,
|
||||
ApplicationContextAware, Ordered {
|
||||
|
||||
private String[] expectedBefore;
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private String[] args;
|
||||
|
||||
private int order;
|
||||
|
||||
public TestCommandLineRunner(int order, String... expectedBefore) {
|
||||
this.expectedBefore = expectedBefore;
|
||||
this.order = order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return this.order;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) {
|
||||
this.args = args;
|
||||
for (String name : this.expectedBefore) {
|
||||
TestCommandLineRunner bean = this.applicationContext.getBean(name,
|
||||
TestCommandLineRunner.class);
|
||||
assertTrue(bean.hasRun());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasRun() {
|
||||
return this.args != null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.bind;
|
||||
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.NotWritablePropertyException;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.support.PropertiesLoaderUtils;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* Tests for {@link PropertiesConfigurationFactory}.
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class PropertiesConfigurationFactoryTests {
|
||||
|
||||
private PropertiesConfigurationFactory<Foo> factory;
|
||||
|
||||
private Validator validator;
|
||||
|
||||
private boolean exceptionIfInvalid = true;
|
||||
|
||||
private boolean ignoreUnknownFields = true;
|
||||
|
||||
private String targetName = null;
|
||||
|
||||
@Test
|
||||
public void testValidPropertiesLoadsWithNoErrors() throws Exception {
|
||||
Foo foo = createFoo("name: blah\nbar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
assertEquals("blah", foo.name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidPropertiesLoadsWithUpperCase() throws Exception {
|
||||
Foo foo = createFoo("NAME: blah\nbar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
assertEquals("blah", foo.name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidPropertiesLoadsWithDash() throws Exception {
|
||||
Foo foo = createFoo("na-me: blah\nbar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
assertEquals("blah", foo.name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnknownPropertyOkByDefault() throws Exception {
|
||||
Foo foo = createFoo("hi: hello\nname: foo\nbar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
}
|
||||
|
||||
@Test(expected = NotWritablePropertyException.class)
|
||||
public void testUnknownPropertyCausesLoadFailure() throws Exception {
|
||||
this.ignoreUnknownFields = false;
|
||||
createFoo("hi: hello\nname: foo\nbar: blah");
|
||||
}
|
||||
|
||||
@Test(expected = BindException.class)
|
||||
public void testMissingPropertyCausesValidationError() throws Exception {
|
||||
this.validator = new SpringValidatorAdapter(Validation
|
||||
.buildDefaultValidatorFactory().getValidator());
|
||||
createFoo("bar: blah");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindToNamedTarget() throws Exception {
|
||||
this.targetName = "foo";
|
||||
Foo foo = createFoo("hi: hello\nfoo.name: foo\nfoo.bar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
}
|
||||
|
||||
private Foo createFoo(final String values) throws Exception {
|
||||
this.factory = new PropertiesConfigurationFactory<Foo>(Foo.class);
|
||||
this.factory.setProperties(PropertiesLoaderUtils
|
||||
.loadProperties(new ByteArrayResource(values.getBytes())));
|
||||
this.factory.setExceptionIfInvalid(this.exceptionIfInvalid);
|
||||
this.factory.setValidator(this.validator);
|
||||
this.factory.setTargetName(this.targetName);
|
||||
this.factory.setIgnoreUnknownFields(this.ignoreUnknownFields);
|
||||
this.factory.setMessageSource(new StaticMessageSource());
|
||||
this.factory.afterPropertiesSet();
|
||||
return this.factory.getObject();
|
||||
}
|
||||
|
||||
// Foo needs to be public and to have setters for all properties
|
||||
public static class Foo {
|
||||
@NotNull
|
||||
private String name;
|
||||
|
||||
private String bar;
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getBar() {
|
||||
return this.bar;
|
||||
}
|
||||
|
||||
public void setBar(String bar) {
|
||||
this.bar = bar;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.bind;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.MutablePropertySources;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.validation.DataBinder;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class PropertySourcesPropertyValuesTests {
|
||||
|
||||
private MutablePropertySources propertySources = new MutablePropertySources();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.propertySources.addFirst(new PropertySource<String>("static", "foo") {
|
||||
@Override
|
||||
public Object getProperty(String name) {
|
||||
if (name.equals(getSource())) {
|
||||
return "bar";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
});
|
||||
this.propertySources.addFirst(new MapPropertySource("map", Collections
|
||||
.<String, Object> singletonMap("name", "${foo}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(
|
||||
this.propertySources);
|
||||
assertEquals(1, propertyValues.getPropertyValues().length);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonEnumeratedValue() {
|
||||
PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(
|
||||
this.propertySources);
|
||||
assertEquals("bar", propertyValues.getPropertyValue("foo").getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnumeratedValue() {
|
||||
PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(
|
||||
this.propertySources);
|
||||
assertEquals("bar", propertyValues.getPropertyValue("name").getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOverriddenValue() {
|
||||
this.propertySources.addFirst(new MapPropertySource("new", Collections
|
||||
.<String, Object> singletonMap("name", "spam")));
|
||||
PropertySourcesPropertyValues propertyValues = new PropertySourcesPropertyValues(
|
||||
this.propertySources);
|
||||
assertEquals("spam", propertyValues.getPropertyValue("name").getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPlaceholdersBinding() {
|
||||
TestBean target = new TestBean();
|
||||
DataBinder binder = new DataBinder(target);
|
||||
binder.bind(new PropertySourcesPropertyValues(this.propertySources));
|
||||
assertEquals("bar", target.getName());
|
||||
}
|
||||
|
||||
public static class TestBean {
|
||||
private String name;
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/*
|
||||
* Cloud Foundry 2012.02.03 Beta
|
||||
* Copyright (c) [2009-2012] VMware, Inc. All Rights Reserved.
|
||||
*
|
||||
* This product is licensed to you under the Apache License, Version 2.0 (the "License").
|
||||
* You may not use this product except in compliance with the License.
|
||||
*
|
||||
* This product includes a number of subcomponents with
|
||||
* separate copyright notices and license terms. Your use of these
|
||||
* subcomponents is subject to the terms and conditions of the
|
||||
* subcomponent's license, as noted in the LICENSE file.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.bind;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.validation.Constraint;
|
||||
import javax.validation.ConstraintValidator;
|
||||
import javax.validation.ConstraintValidatorContext;
|
||||
import javax.validation.Payload;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.bootstrap.bind.RelaxedDataBinderTests.OAuthConfiguration.OAuthConfigurationValidator;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.support.PropertiesLoaderUtils;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.DataBinder;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
/**
|
||||
* Tests for {@link RelaxedDataBinder}.
|
||||
*
|
||||
* @author Dave Syer
|
||||
*/
|
||||
public class RelaxedDataBinderTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException expected = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void testBindString() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
bind(target, "foo: bar");
|
||||
assertEquals("bar", target.getFoo());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindUnderscore() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
bind(target, "foo-bar: bar");
|
||||
assertEquals("bar", target.getFoo_bar());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindCamelCase() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
bind(target, "foo-baz: bar");
|
||||
assertEquals("bar", target.getFooBaz());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindNumber() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
bind(target, "foo: bar\n" + "value: 123");
|
||||
assertEquals(123, target.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSimpleValidation() throws Exception {
|
||||
ValidatedTarget target = new ValidatedTarget();
|
||||
BindingResult result = bind(target, "");
|
||||
assertEquals(1, result.getErrorCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRequiredFieldsValidation() throws Exception {
|
||||
TargetWithValidatedMap target = new TargetWithValidatedMap();
|
||||
BindingResult result = bind(target, "info[foo]: bar");
|
||||
assertEquals(2, result.getErrorCount());
|
||||
for (FieldError error : result.getFieldErrors()) {
|
||||
System.err.println(new StaticMessageSource().getMessage(error,
|
||||
Locale.getDefault()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindNested() throws Exception {
|
||||
TargetWithNestedObject target = new TargetWithNestedObject();
|
||||
bind(target, "nested.foo: bar\n" + "nested.value: 123");
|
||||
assertEquals(123, target.getNested().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindNestedMap() throws Exception {
|
||||
TargetWithNestedMap target = new TargetWithNestedMap();
|
||||
bind(target, "nested.foo: bar\n" + "nested.value: 123");
|
||||
assertEquals("123", target.getNested().get("value"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindNestedMapBracketReferenced() throws Exception {
|
||||
TargetWithNestedMap target = new TargetWithNestedMap();
|
||||
bind(target, "nested[foo]: bar\n" + "nested[value]: 123");
|
||||
assertEquals("123", target.getNested().get("value"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testBindDoubleNestedMap() throws Exception {
|
||||
TargetWithNestedMap target = new TargetWithNestedMap();
|
||||
bind(target, "nested.foo: bar\n" + "nested.bar.spam: bucket\n"
|
||||
+ "nested.bar.value: 123\nnested.bar.foo: crap");
|
||||
assertEquals(2, target.getNested().size());
|
||||
assertEquals(3, ((Map<String, Object>) target.getNested().get("bar")).size());
|
||||
assertEquals("123",
|
||||
((Map<String, Object>) target.getNested().get("bar")).get("value"));
|
||||
assertEquals("bar", target.getNested().get("foo"));
|
||||
assertFalse(target.getNested().containsValue(target.getNested()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindErrorTypeMismatch() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
BindingResult result = bind(target, "foo: bar\n" + "value: foo");
|
||||
assertEquals(1, result.getErrorCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindErrorNotWritable() throws Exception {
|
||||
this.expected.expectMessage("property 'spam'");
|
||||
this.expected.expectMessage("not writable");
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
BindingResult result = bind(target, "spam: bar\n" + "value: 123");
|
||||
assertEquals(1, result.getErrorCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBindErrorNotWritableWithPrefix() throws Exception {
|
||||
VanillaTarget target = new VanillaTarget();
|
||||
BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123",
|
||||
"vanilla");
|
||||
assertEquals(0, result.getErrorCount());
|
||||
assertEquals(123, target.getValue());
|
||||
}
|
||||
|
||||
private BindingResult bind(Object target, String values) throws Exception {
|
||||
return bind(target, values, null);
|
||||
}
|
||||
|
||||
private BindingResult bind(Object target, String values, String namePrefix)
|
||||
throws Exception {
|
||||
Properties properties = PropertiesLoaderUtils
|
||||
.loadProperties(new ByteArrayResource(values.getBytes()));
|
||||
DataBinder binder = new RelaxedDataBinder(target, namePrefix);
|
||||
binder.setIgnoreUnknownFields(false);
|
||||
LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean();
|
||||
validatorFactoryBean.afterPropertiesSet();
|
||||
binder.setValidator(validatorFactoryBean);
|
||||
binder.bind(new MutablePropertyValues(properties));
|
||||
binder.validate();
|
||||
|
||||
return binder.getBindingResult();
|
||||
}
|
||||
|
||||
@Documented
|
||||
@Target({ ElementType.TYPE })
|
||||
@Retention(RUNTIME)
|
||||
@Constraint(validatedBy = OAuthConfigurationValidator.class)
|
||||
public @interface ValidOAuthConfiguration {
|
||||
}
|
||||
|
||||
@ValidOAuthConfiguration
|
||||
public static class OAuthConfiguration {
|
||||
|
||||
private Client client;
|
||||
|
||||
private Map<String, OAuthClient> clients;
|
||||
|
||||
public Client getClient() {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
public void setClient(Client client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public Map<String, OAuthClient> getClients() {
|
||||
return this.clients;
|
||||
}
|
||||
|
||||
public void setClients(Map<String, OAuthClient> clients) {
|
||||
this.clients = clients;
|
||||
}
|
||||
|
||||
public static class Client {
|
||||
|
||||
private List<String> autoapprove;
|
||||
|
||||
public List<String> getAutoapprove() {
|
||||
return this.autoapprove;
|
||||
}
|
||||
|
||||
public void setAutoapprove(List<String> autoapprove) {
|
||||
this.autoapprove = autoapprove;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class OAuthClient {
|
||||
|
||||
private String id;
|
||||
|
||||
public String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class OAuthConfigurationValidator implements
|
||||
ConstraintValidator<ValidOAuthConfiguration, OAuthConfiguration> {
|
||||
|
||||
@Override
|
||||
public void initialize(ValidOAuthConfiguration constraintAnnotation) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(OAuthConfiguration value,
|
||||
ConstraintValidatorContext context) {
|
||||
boolean valid = true;
|
||||
if (value.client != null && value.client.autoapprove != null) {
|
||||
if (value.clients != null) {
|
||||
context.buildConstraintViolationWithTemplate(
|
||||
"Please use oauth.clients to specifiy autoapprove not client.autoapprove")
|
||||
.addConstraintViolation();
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Documented
|
||||
@Target({ ElementType.FIELD })
|
||||
@Retention(RUNTIME)
|
||||
@Constraint(validatedBy = RequiredKeysValidator.class)
|
||||
public @interface RequiredKeys {
|
||||
|
||||
String[] value();
|
||||
|
||||
String message() default "Required fields are not provided for field ''{0}''";
|
||||
|
||||
Class<?>[] groups() default {};
|
||||
|
||||
Class<? extends Payload>[] payload() default {};
|
||||
|
||||
}
|
||||
|
||||
public static class RequiredKeysValidator implements
|
||||
ConstraintValidator<RequiredKeys, Map<String, Object>> {
|
||||
|
||||
private String[] fields;
|
||||
|
||||
@Override
|
||||
public void initialize(RequiredKeys constraintAnnotation) {
|
||||
this.fields = constraintAnnotation.value();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isValid(Map<String, Object> value,
|
||||
ConstraintValidatorContext context) {
|
||||
boolean valid = true;
|
||||
for (String field : this.fields) {
|
||||
if (!value.containsKey(field)) {
|
||||
context.buildConstraintViolationWithTemplate(
|
||||
"Missing field ''" + field + "''").addConstraintViolation();
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class TargetWithValidatedMap {
|
||||
|
||||
@RequiredKeys({ "foo", "value" })
|
||||
private Map<String, Object> info;
|
||||
|
||||
public Map<String, Object> getInfo() {
|
||||
return this.info;
|
||||
}
|
||||
|
||||
public void setInfo(Map<String, Object> nested) {
|
||||
this.info = nested;
|
||||
}
|
||||
}
|
||||
|
||||
public static class TargetWithNestedMap {
|
||||
private Map<String, Object> nested;
|
||||
|
||||
public Map<String, Object> getNested() {
|
||||
return this.nested;
|
||||
}
|
||||
|
||||
public void setNested(Map<String, Object> nested) {
|
||||
this.nested = nested;
|
||||
}
|
||||
}
|
||||
|
||||
public static class TargetWithNestedObject {
|
||||
private VanillaTarget nested;
|
||||
|
||||
public VanillaTarget getNested() {
|
||||
return this.nested;
|
||||
}
|
||||
|
||||
public void setNested(VanillaTarget nested) {
|
||||
this.nested = nested;
|
||||
}
|
||||
}
|
||||
|
||||
public static class VanillaTarget {
|
||||
|
||||
private String foo;
|
||||
|
||||
private int value;
|
||||
|
||||
private String foo_bar;
|
||||
|
||||
private String fooBaz;
|
||||
|
||||
public int getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getFoo() {
|
||||
return this.foo;
|
||||
}
|
||||
|
||||
public void setFoo(String foo) {
|
||||
this.foo = foo;
|
||||
}
|
||||
|
||||
public String getFoo_bar() {
|
||||
return this.foo_bar;
|
||||
}
|
||||
|
||||
public void setFoo_bar(String foo_bar) {
|
||||
this.foo_bar = foo_bar;
|
||||
}
|
||||
|
||||
public String getFooBaz() {
|
||||
return this.fooBaz;
|
||||
}
|
||||
|
||||
public void setFooBaz(String fooBaz) {
|
||||
this.fooBaz = fooBaz;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ValidatedTarget {
|
||||
|
||||
@NotNull
|
||||
private String foo;
|
||||
|
||||
public String getFoo() {
|
||||
return this.foo;
|
||||
}
|
||||
|
||||
public void setFoo(String foo) {
|
||||
this.foo = foo;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.bind;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
|
||||
import org.yaml.snakeyaml.error.YAMLException;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class YamlConfigurationFactoryTests {
|
||||
|
||||
private YamlConfigurationFactory<Foo> factory;
|
||||
|
||||
private Validator validator;
|
||||
|
||||
private Map<Class<?>, Map<String, String>> aliases = new HashMap<Class<?>, Map<String, String>>();
|
||||
|
||||
private Foo createFoo(final String yaml) throws Exception {
|
||||
factory = new YamlConfigurationFactory<Foo>(Foo.class);
|
||||
factory.setYaml(yaml);
|
||||
factory.setExceptionIfInvalid(true);
|
||||
factory.setPropertyAliases(aliases);
|
||||
factory.setValidator(validator);
|
||||
factory.setMessageSource(new StaticMessageSource());
|
||||
factory.afterPropertiesSet();
|
||||
return factory.getObject();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidYamlLoadsWithNoErrors() throws Exception {
|
||||
Foo foo = createFoo("name: blah\nbar: blah");
|
||||
assertEquals("blah", foo.bar);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidYamlWithAliases() throws Exception {
|
||||
aliases.put(Foo.class, Collections.singletonMap("foo-name", "name"));
|
||||
Foo foo = createFoo("foo-name: blah\nbar: blah");
|
||||
assertEquals("blah", foo.name);
|
||||
}
|
||||
|
||||
@Test(expected = YAMLException.class)
|
||||
public void unknownPropertyCausesLoadFailure() throws Exception {
|
||||
createFoo("hi: hello\nname: foo\nbar: blah");
|
||||
}
|
||||
|
||||
@Test(expected = BindException.class)
|
||||
public void missingPropertyCausesValidationError() throws Exception {
|
||||
validator = new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory()
|
||||
.getValidator());
|
||||
createFoo("bar: blah");
|
||||
}
|
||||
|
||||
private static class Foo {
|
||||
@NotNull
|
||||
public String name;
|
||||
|
||||
public String bar;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.net.ConnectException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.apache.commons.httpclient.HttpClient;
|
||||
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
|
||||
import org.apache.commons.httpclient.methods.GetMethod;
|
||||
import org.junit.After;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.bootstrap.context.embedded.AbstractEmbeddedServletContainerFactory;
|
||||
import org.springframework.bootstrap.context.embedded.EmbeddedServletContainer;
|
||||
import org.springframework.bootstrap.context.embedded.FilterRegistrationBean;
|
||||
import org.springframework.bootstrap.context.embedded.ServletRegistrationBean;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.client.ClientHttpRequest;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.web.ServletContextInitializer;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyObject;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Base for testing classes that extends {@link AbstractEmbeddedServletContainerFactory}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public abstract class AbstractEmbeddedServletContainerFactoryTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
protected EmbeddedServletContainer container;
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
if (this.container != null) {
|
||||
try {
|
||||
this.container.stop();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startServlet() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
assertThat(getResponse("http://localhost:8080/hello"), equalTo("Hello World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stopServlet() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
this.container.stop();
|
||||
this.thrown.expect(ConnectException.class);
|
||||
getResponse("http://localhost:8080/hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void restartWithKeepAlive() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
|
||||
MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
|
||||
HttpClient client = new HttpClient(connectionManager);
|
||||
GetMethod get1 = new GetMethod("http://localhost:8080/hello");
|
||||
assertThat(client.executeMethod(get1), equalTo(200));
|
||||
get1.releaseConnection();
|
||||
|
||||
this.container.stop();
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
|
||||
GetMethod get2 = new GetMethod("http://localhost:8080/hello");
|
||||
assertThat(client.executeMethod(get2), equalTo(200));
|
||||
get2.releaseConnection();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startServletAndFilter() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
this.container = factory.getEmbdeddedServletContainer(
|
||||
exampleServletRegistration(), new FilterRegistrationBean(
|
||||
new ExampleFilter()));
|
||||
assertThat(getResponse("http://localhost:8080/hello"), equalTo("[Hello World]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startBlocksUntilReadyToServe() throws Exception {
|
||||
// FIXME Assume.group(TestGroup.LONG_RUNNING);
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
final Date[] date = new Date[1];
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(new ServletContextInitializer() {
|
||||
@Override
|
||||
public void onStartup(ServletContext servletContext)
|
||||
throws ServletException {
|
||||
try {
|
||||
Thread.sleep(500);
|
||||
date[0] = new Date();
|
||||
} catch (InterruptedException ex) {
|
||||
throw new ServletException(ex);
|
||||
}
|
||||
}
|
||||
});
|
||||
assertThat(date[0], notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificPort() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
factory.setPort(8081);
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
assertThat(getResponse("http://localhost:8081/hello"), equalTo("Hello World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificContextRoot() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
factory.setContextPath("/say");
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
assertThat(getResponse("http://localhost:8080/say/hello"), equalTo("Hello World"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextPathMustStartWithSlash() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("ContextPath must start with '/ and not end with '/'");
|
||||
getFactory().setContextPath("missingslash");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextPathMustNotEndWithSlash() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown.expectMessage("ContextPath must start with '/ and not end with '/'");
|
||||
getFactory().setContextPath("extraslash/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextRootPathMustNotBeSlash() throws Exception {
|
||||
this.thrown.expect(IllegalArgumentException.class);
|
||||
this.thrown
|
||||
.expectMessage("Root ContextPath must be specified using an empty string");
|
||||
getFactory().setContextPath("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doubleStop() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
this.container = factory
|
||||
.getEmbdeddedServletContainer(exampleServletRegistration());
|
||||
this.container.stop();
|
||||
this.container.stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleConfigurations() throws Exception {
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
ServletContextInitializer[] initializers = new ServletContextInitializer[6];
|
||||
for (int i = 0; i < initializers.length; i++) {
|
||||
initializers[i] = mock(ServletContextInitializer.class);
|
||||
}
|
||||
factory.setInitializers(Arrays.asList(initializers[2], initializers[3]));
|
||||
factory.addInitializers(initializers[4], initializers[5]);
|
||||
this.container = factory.getEmbdeddedServletContainer(initializers[0],
|
||||
initializers[1]);
|
||||
InOrder ordered = inOrder((Object[]) initializers);
|
||||
for (ServletContextInitializer initializer : initializers) {
|
||||
ordered.verify(initializer).onStartup((ServletContext) anyObject());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void documentRoot() throws Exception {
|
||||
FileCopyUtils.copy("test",
|
||||
new FileWriter(this.temporaryFolder.newFile("test.txt")));
|
||||
AbstractEmbeddedServletContainerFactory factory = getFactory();
|
||||
factory.setDocumentRoot(this.temporaryFolder.getRoot());
|
||||
this.container = factory.getEmbdeddedServletContainer();
|
||||
assertThat(getResponse("http://localhost:8080/test.txt"), equalTo("test"));
|
||||
}
|
||||
|
||||
// FIXME test error page
|
||||
|
||||
protected String getResponse(String url) throws IOException, URISyntaxException {
|
||||
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
|
||||
ClientHttpRequest request = clientHttpRequestFactory.createRequest(new URI(url),
|
||||
HttpMethod.GET);
|
||||
ClientHttpResponse response = request.execute();
|
||||
try {
|
||||
return StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8"));
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract AbstractEmbeddedServletContainerFactory getFactory();
|
||||
|
||||
private ServletContextInitializer exampleServletRegistration() {
|
||||
return new ServletRegistrationBean(new ExampleServlet(), "/hello");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
|
||||
import org.springframework.bootstrap.context.embedded.config.ExampleEmbeddedWebApplicationConfiguration;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests for {@link AnnotationConfigEmbeddedWebApplicationContext}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class AnnotationConfigEmbeddedWebApplicationContextTests {
|
||||
|
||||
private AnnotationConfigEmbeddedWebApplicationContext context;
|
||||
|
||||
@Test
|
||||
public void createFromScan() throws Exception {
|
||||
this.context = new AnnotationConfigEmbeddedWebApplicationContext(
|
||||
ExampleEmbeddedWebApplicationConfiguration.class.getPackage().getName());
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFromConfigClass() throws Exception {
|
||||
this.context = new AnnotationConfigEmbeddedWebApplicationContext(
|
||||
ExampleEmbeddedWebApplicationConfiguration.class);
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registerAndRefresh() throws Exception {
|
||||
this.context = new AnnotationConfigEmbeddedWebApplicationContext();
|
||||
this.context.register(ExampleEmbeddedWebApplicationConfiguration.class);
|
||||
this.context.refresh();
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void scanAndRefresh() throws Exception {
|
||||
this.context = new AnnotationConfigEmbeddedWebApplicationContext();
|
||||
this.context.scan(ExampleEmbeddedWebApplicationConfiguration.class.getPackage()
|
||||
.getName());
|
||||
this.context.refresh();
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
private void verifyContext() {
|
||||
MockEmbeddedServletContainerFactory containerFactory = this.context
|
||||
.getBean(MockEmbeddedServletContainerFactory.class);
|
||||
Servlet servlet = this.context.getBean(Servlet.class);
|
||||
verify(containerFactory.getServletContext()).addServlet("servlet", servlet);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.ConstructorArgumentValues;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.bootstrap.context.embedded.EmbeddedWebApplicationContext;
|
||||
import org.springframework.bootstrap.context.embedded.FilterRegistrationBean;
|
||||
import org.springframework.context.ApplicationContextException;
|
||||
import org.springframework.context.support.AbstractApplicationContext;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.web.ServletContextInitializer;
|
||||
import org.springframework.web.context.ServletContextAware;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.SessionScope;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.instanceOf;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Matchers.anyObject;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
/**
|
||||
* Tests for {@link EmbeddedWebApplicationContext}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class EmbeddedWebApplicationContextTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private EmbeddedWebApplicationContext context;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
this.context = new EmbeddedWebApplicationContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
this.context.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startRegistrations() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
this.context.refresh();
|
||||
|
||||
MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory();
|
||||
|
||||
// Ensure that the context has been setup
|
||||
assertThat(this.context.getServletContext(), equalTo(escf.getServletContext()));
|
||||
verify(escf.getServletContext()).setAttribute(
|
||||
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
|
||||
this.context);
|
||||
|
||||
// Ensure WebApplicationContextUtils.registerWebApplicationScopes was called
|
||||
assertThat(
|
||||
this.context.getBeanFactory().getRegisteredScope(
|
||||
WebApplicationContext.SCOPE_SESSION),
|
||||
instanceOf(SessionScope.class));
|
||||
|
||||
// Ensure WebApplicationContextUtils.registerEnvironmentBeans was called
|
||||
assertThat(
|
||||
this.context
|
||||
.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME),
|
||||
equalTo(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void registersShutdownHook() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
this.context.refresh();
|
||||
Field shutdownHookField = AbstractApplicationContext.class
|
||||
.getDeclaredField("shutdownHook");
|
||||
shutdownHookField.setAccessible(true);
|
||||
Object shutdownHook = shutdownHookField.get(this.context);
|
||||
assertThat(shutdownHook, not(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stopOnClose() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
this.context.refresh();
|
||||
MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory();
|
||||
this.context.close();
|
||||
verify(escf.getContainer()).stop();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cannotSecondRefresh() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
this.context.refresh();
|
||||
this.thrown.expect(IllegalStateException.class);
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void servletContextAwareBeansAreInjected() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
ServletContextAware bean = mock(ServletContextAware.class);
|
||||
this.context.registerBeanDefinition("bean", beanDefinition(bean));
|
||||
this.context.refresh();
|
||||
verify(bean).setServletContext(
|
||||
getEmbeddedServletContainerFactory().getServletContext());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingEmbeddedServletContainerFactory() throws Exception {
|
||||
this.thrown.expect(ApplicationContextException.class);
|
||||
this.thrown.expectMessage("Unable to start EmbeddedWebApplicationContext due to "
|
||||
+ "missing EmbeddedServletContainerFactory bean");
|
||||
this.context.refresh();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tooManyEmbeddedServletContainerFactories() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
this.context.registerBeanDefinition("embeddedServletContainerFactory2",
|
||||
new RootBeanDefinition(MockEmbeddedServletContainerFactory.class));
|
||||
this.thrown.expect(ApplicationContextException.class);
|
||||
this.thrown.expectMessage("Unable to start EmbeddedWebApplicationContext due to "
|
||||
+ "multiple EmbeddedServletContainerFactory beans");
|
||||
this.context.refresh();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleServletBean() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
Servlet servlet = mock(Servlet.class);
|
||||
this.context.registerBeanDefinition("servletBean", beanDefinition(servlet));
|
||||
this.context.refresh();
|
||||
MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory();
|
||||
verify(escf.getServletContext()).addServlet("servletBean", servlet);
|
||||
verify(escf.getRegisteredServlet(0).getRegistration()).addMapping("/");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void multipleServletBeans() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
Servlet servlet1 = mock(Servlet.class,
|
||||
withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) servlet1).getOrder()).willReturn(1);
|
||||
Servlet servlet2 = mock(Servlet.class,
|
||||
withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) servlet2).getOrder()).willReturn(2);
|
||||
this.context.registerBeanDefinition("servletBean2", beanDefinition(servlet2));
|
||||
this.context.registerBeanDefinition("servletBean1", beanDefinition(servlet1));
|
||||
this.context.refresh();
|
||||
MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory();
|
||||
ServletContext servletContext = escf.getServletContext();
|
||||
InOrder ordered = inOrder(servletContext);
|
||||
ordered.verify(servletContext).addServlet("servletBean1", servlet1);
|
||||
ordered.verify(servletContext).addServlet("servletBean2", servlet2);
|
||||
verify(escf.getRegisteredServlet(0).getRegistration()).addMapping(
|
||||
"/servletbean1/*");
|
||||
verify(escf.getRegisteredServlet(1).getRegistration()).addMapping(
|
||||
"/servletbean2/*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void servletAndFilterBeans() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
Servlet servlet = mock(Servlet.class);
|
||||
Filter filter1 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) filter1).getOrder()).willReturn(1);
|
||||
Filter filter2 = mock(Filter.class, withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) filter2).getOrder()).willReturn(2);
|
||||
this.context.registerBeanDefinition("servletBean", beanDefinition(servlet));
|
||||
this.context.registerBeanDefinition("filterBean2", beanDefinition(filter2));
|
||||
this.context.registerBeanDefinition("filterBean1", beanDefinition(filter1));
|
||||
this.context.refresh();
|
||||
MockEmbeddedServletContainerFactory escf = getEmbeddedServletContainerFactory();
|
||||
ServletContext servletContext = escf.getServletContext();
|
||||
InOrder ordered = inOrder(servletContext);
|
||||
verify(escf.getServletContext()).addServlet("servletBean", servlet);
|
||||
verify(escf.getRegisteredServlet(0).getRegistration()).addMapping("/");
|
||||
ordered.verify(escf.getServletContext()).addFilter("filterBean1", filter1);
|
||||
ordered.verify(escf.getServletContext()).addFilter("filterBean2", filter2);
|
||||
verify(escf.getRegisteredFilter(0).getRegistration()).addMappingForUrlPatterns(
|
||||
FilterRegistrationBean.ASYNC_DISPATCHER_TYPES, false, "/*");
|
||||
verify(escf.getRegisteredFilter(1).getRegistration()).addMappingForUrlPatterns(
|
||||
FilterRegistrationBean.ASYNC_DISPATCHER_TYPES, false, "/*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void servletContextInitializerBeans() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
ServletContextInitializer initializer1 = mock(ServletContextInitializer.class,
|
||||
withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) initializer1).getOrder()).willReturn(1);
|
||||
ServletContextInitializer initializer2 = mock(ServletContextInitializer.class,
|
||||
withSettings().extraInterfaces(Ordered.class));
|
||||
given(((Ordered) initializer2).getOrder()).willReturn(2);
|
||||
this.context.registerBeanDefinition("initializerBean2",
|
||||
beanDefinition(initializer2));
|
||||
this.context.registerBeanDefinition("initializerBean1",
|
||||
beanDefinition(initializer1));
|
||||
this.context.refresh();
|
||||
ServletContext servletContext = getEmbeddedServletContainerFactory()
|
||||
.getServletContext();
|
||||
InOrder ordered = inOrder(initializer1, initializer2);
|
||||
ordered.verify(initializer1).onStartup(servletContext);
|
||||
ordered.verify(initializer2).onStartup(servletContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void servletContextInitializerBeansSkipsServletsAndFilters() throws Exception {
|
||||
addEmbeddedServletContainerFactoryBean();
|
||||
ServletContextInitializer initializer = mock(ServletContextInitializer.class);
|
||||
Servlet servlet = mock(Servlet.class);
|
||||
Filter filter = mock(Filter.class);
|
||||
this.context.registerBeanDefinition("initializerBean",
|
||||
beanDefinition(initializer));
|
||||
this.context.registerBeanDefinition("servletBean", beanDefinition(servlet));
|
||||
this.context.registerBeanDefinition("filterBean", beanDefinition(filter));
|
||||
this.context.refresh();
|
||||
ServletContext servletContext = getEmbeddedServletContainerFactory()
|
||||
.getServletContext();
|
||||
verify(initializer).onStartup(servletContext);
|
||||
verify(servletContext, never()).addServlet(anyString(), (Servlet) anyObject());
|
||||
verify(servletContext, never()).addFilter(anyString(), (Filter) anyObject());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postProcessEmbeddedServletContainerFactory() throws Exception {
|
||||
RootBeanDefinition bd = new RootBeanDefinition(
|
||||
MockEmbeddedServletContainerFactory.class);
|
||||
MutablePropertyValues pv = new MutablePropertyValues();
|
||||
pv.add("port", "${port}");
|
||||
bd.setPropertyValues(pv);
|
||||
this.context.registerBeanDefinition("embeddedServletContainerFactory", bd);
|
||||
|
||||
PropertySourcesPlaceholderConfigurer propertySupport = new PropertySourcesPlaceholderConfigurer();
|
||||
Properties properties = new Properties();
|
||||
properties.put("port", 8080);
|
||||
propertySupport.setProperties(properties);
|
||||
this.context.registerBeanDefinition("propertySupport",
|
||||
beanDefinition(propertySupport));
|
||||
|
||||
this.context.refresh();
|
||||
assertThat(getEmbeddedServletContainerFactory().getContainer().getPort(),
|
||||
equalTo(8080));
|
||||
}
|
||||
|
||||
private void addEmbeddedServletContainerFactoryBean() {
|
||||
this.context.registerBeanDefinition("embeddedServletContainerFactory",
|
||||
new RootBeanDefinition(MockEmbeddedServletContainerFactory.class));
|
||||
}
|
||||
|
||||
public MockEmbeddedServletContainerFactory getEmbeddedServletContainerFactory() {
|
||||
return this.context.getBean(MockEmbeddedServletContainerFactory.class);
|
||||
}
|
||||
|
||||
private BeanDefinition beanDefinition(Object bean) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition();
|
||||
beanDefinition.setBeanClass(getClass());
|
||||
beanDefinition.setFactoryMethodName("getBean");
|
||||
ConstructorArgumentValues constructorArguments = new ConstructorArgumentValues();
|
||||
constructorArguments.addGenericArgumentValue(bean);
|
||||
beanDefinition.setConstructorArgumentValues(constructorArguments);
|
||||
return beanDefinition;
|
||||
}
|
||||
|
||||
public static <T> T getBean(T object) {
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
/**
|
||||
* Simple example Filter used for testing.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class ExampleFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
response.getWriter().write("[");
|
||||
chain.doFilter(request, response);
|
||||
response.getWriter().write("]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.GenericServlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
/**
|
||||
* Simple example Servlet used for testing.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class ExampleServlet extends GenericServlet {
|
||||
|
||||
@Override
|
||||
public void service(ServletRequest request, ServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
response.getWriter().write("Hello World");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.bootstrap.context.embedded.FilterRegistrationBean;
|
||||
import org.springframework.bootstrap.context.embedded.ServletRegistrationBean;
|
||||
|
||||
import static org.mockito.BDDMockito.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests for {@link FilterRegistrationBean}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class FilterRegistrationBeanTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockFilter filter = new MockFilter();
|
||||
|
||||
@Mock
|
||||
private ServletContext servletContext;
|
||||
|
||||
@Mock
|
||||
private FilterRegistration.Dynamic registration;
|
||||
|
||||
@Before
|
||||
public void setupMocks() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
given(this.servletContext.addFilter(anyString(), (Filter) anyObject()))
|
||||
.willReturn(this.registration);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startupWithDefaults() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addFilter("mockFilter", filter);
|
||||
verify(this.registration).setAsyncSupported(true);
|
||||
verify(this.registration).addMappingForUrlPatterns(
|
||||
FilterRegistrationBean.ASYNC_DISPATCHER_TYPES, false, "/*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startupWithSpecifiedValues() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean();
|
||||
bean.setName("test");
|
||||
bean.setFilter(this.filter);
|
||||
bean.setAsyncSupported(false);
|
||||
bean.setInitParameters(Collections.singletonMap("a", "b"));
|
||||
bean.addInitParameter("c", "d");
|
||||
bean.setUrlPatterns(new LinkedHashSet<String>(Arrays.asList("/a", "/b")));
|
||||
bean.addUrlPatterns("/c");
|
||||
bean.setServletNames(new LinkedHashSet<String>(Arrays.asList("s1", "s2")));
|
||||
bean.addServletNames("s3");
|
||||
bean.setServletRegistrationBeans(Collections
|
||||
.singleton(mockServletRegistation("s4")));
|
||||
bean.addServletRegistrationBeans(mockServletRegistation("s5"));
|
||||
bean.setMatchAfter(true);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addFilter("test", this.filter);
|
||||
verify(this.registration).setAsyncSupported(false);
|
||||
Map<String, String> expectedInitParameters = new HashMap<String, String>();
|
||||
expectedInitParameters.put("a", "b");
|
||||
expectedInitParameters.put("c", "d");
|
||||
verify(this.registration).setInitParameters(expectedInitParameters);
|
||||
verify(this.registration)
|
||||
.addMappingForUrlPatterns(
|
||||
FilterRegistrationBean.NON_ASYNC_DISPATCHER_TYPES, true, "/a",
|
||||
"/b", "/c");
|
||||
verify(this.registration).addMappingForServletNames(
|
||||
FilterRegistrationBean.NON_ASYNC_DISPATCHER_TYPES, true, "s4", "s5",
|
||||
"s1", "s2", "s3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificName() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean();
|
||||
bean.setName("specificName");
|
||||
bean.setFilter(this.filter);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addFilter("specificName", this.filter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deducedName() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean();
|
||||
bean.setFilter(this.filter);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addFilter("mockFilter", this.filter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setFilterMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean();
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("Filter must not be null");
|
||||
bean.onStartup(this.servletContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createServletMustNotBeNull() throws Exception {
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("Filter must not be null");
|
||||
new FilterRegistrationBean(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setServletRegistrationBeanMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("ServletRegistrationBeans must not be null");
|
||||
bean.setServletRegistrationBeans(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createServletRegistrationBeanMustNotBeNull() throws Exception {
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("ServletRegistrationBeans must not be null");
|
||||
new FilterRegistrationBean(this.filter, (ServletRegistrationBean[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addServletRegistrationBeanMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("ServletRegistrationBeans must not be null");
|
||||
bean.addServletRegistrationBeans((ServletRegistrationBean[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setServletRegistrationBeanReplacesValue() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter,
|
||||
mockServletRegistation("a"));
|
||||
bean.setServletRegistrationBeans(new LinkedHashSet<ServletRegistrationBean>(
|
||||
Arrays.asList(mockServletRegistation("b"))));
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.registration).addMappingForServletNames(
|
||||
FilterRegistrationBean.ASYNC_DISPATCHER_TYPES, false, "b");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyInitParameters() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
bean.addInitParameter("a", "b");
|
||||
bean.getInitParameters().put("a", "c");
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.registration).setInitParameters(Collections.singletonMap("a", "c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setUrlPatternMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("UrlPatterns must not be null");
|
||||
bean.setUrlPatterns(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addUrlPatternMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("UrlPatterns must not be null");
|
||||
bean.addUrlPatterns((String[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setServletNameMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("ServletNames must not be null");
|
||||
bean.setServletNames(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addServletNameMustNotBeNull() throws Exception {
|
||||
FilterRegistrationBean bean = new FilterRegistrationBean(this.filter);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("ServletNames must not be null");
|
||||
bean.addServletNames((String[]) null);
|
||||
}
|
||||
|
||||
private ServletRegistrationBean mockServletRegistation(String name) {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean();
|
||||
bean.setName(name);
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.Matchers.anyObject;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
import org.springframework.bootstrap.context.embedded.EmbeddedServletContainer;
|
||||
import org.springframework.bootstrap.context.embedded.EmbeddedServletContainerFactory;
|
||||
import org.springframework.web.ServletContextInitializer;
|
||||
|
||||
/**
|
||||
* Mock {@link EmbeddedServletContainerFactory}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class MockEmbeddedServletContainerFactory implements
|
||||
EmbeddedServletContainerFactory {
|
||||
|
||||
private MockEmbeddedServletContainer container;
|
||||
|
||||
private int port;
|
||||
|
||||
@Override
|
||||
public EmbeddedServletContainer getEmbdeddedServletContainer(
|
||||
ServletContextInitializer... initializers) {
|
||||
this.container = spy(new MockEmbeddedServletContainer(initializers, port));
|
||||
return this.container;
|
||||
}
|
||||
|
||||
public MockEmbeddedServletContainer getContainer() {
|
||||
return this.container;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return getContainer().servletContext;
|
||||
}
|
||||
|
||||
public RegisteredServlet getRegisteredServlet(int index) {
|
||||
return getContainer().getRegisteredServlets().get(index);
|
||||
}
|
||||
|
||||
public RegisteredFilter getRegisteredFilter(int index) {
|
||||
return getContainer().getRegisteredFilters().get(index);
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public static class MockEmbeddedServletContainer implements EmbeddedServletContainer {
|
||||
|
||||
private ServletContext servletContext;
|
||||
|
||||
private ServletContextInitializer[] initializers;
|
||||
|
||||
private List<RegisteredServlet> registeredServlets = new ArrayList<RegisteredServlet>();
|
||||
|
||||
private List<RegisteredFilter> registeredFilters = new ArrayList<RegisteredFilter>();
|
||||
|
||||
private int port;
|
||||
|
||||
public MockEmbeddedServletContainer(ServletContextInitializer[] initializers,
|
||||
int port) {
|
||||
this.initializers = initializers;
|
||||
this.port = port;
|
||||
start();
|
||||
}
|
||||
|
||||
private void start() {
|
||||
try {
|
||||
this.servletContext = mock(ServletContext.class);
|
||||
given(this.servletContext.addServlet(anyString(), (Servlet) anyObject()))
|
||||
.willAnswer(new Answer<ServletRegistration.Dynamic>() {
|
||||
@Override
|
||||
public ServletRegistration.Dynamic answer(
|
||||
InvocationOnMock invocation) throws Throwable {
|
||||
RegisteredServlet registeredServlet = new RegisteredServlet(
|
||||
(Servlet) invocation.getArguments()[1]);
|
||||
MockEmbeddedServletContainer.this.registeredServlets
|
||||
.add(registeredServlet);
|
||||
return registeredServlet.getRegistration();
|
||||
}
|
||||
});
|
||||
given(this.servletContext.addFilter(anyString(), (Filter) anyObject()))
|
||||
.willAnswer(new Answer<FilterRegistration.Dynamic>() {
|
||||
@Override
|
||||
public FilterRegistration.Dynamic answer(
|
||||
InvocationOnMock invocation) throws Throwable {
|
||||
RegisteredFilter registeredFilter = new RegisteredFilter(
|
||||
(Filter) invocation.getArguments()[1]);
|
||||
MockEmbeddedServletContainer.this.registeredFilters
|
||||
.add(registeredFilter);
|
||||
return registeredFilter.getRegistration();
|
||||
}
|
||||
});
|
||||
given(this.servletContext.getInitParameterNames()).willReturn(
|
||||
MockEmbeddedServletContainer.<String> emptyEnumeration());
|
||||
given(this.servletContext.getAttributeNames()).willReturn(
|
||||
MockEmbeddedServletContainer.<String> emptyEnumeration());
|
||||
for (ServletContextInitializer initializer : this.initializers) {
|
||||
initializer.onStartup(this.servletContext);
|
||||
}
|
||||
} catch (ServletException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Enumeration<T> emptyEnumeration() {
|
||||
return (Enumeration<T>) EmptyEnumeration.EMPTY_ENUMERATION;
|
||||
}
|
||||
|
||||
private static class EmptyEnumeration<E> implements Enumeration<E> {
|
||||
static final EmptyEnumeration<Object> EMPTY_ENUMERATION = new EmptyEnumeration<Object>();
|
||||
|
||||
@Override
|
||||
public boolean hasMoreElements() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public E nextElement() {
|
||||
throw new NoSuchElementException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
this.servletContext = null;
|
||||
this.registeredServlets.clear();
|
||||
}
|
||||
|
||||
public Servlet[] getServlets() {
|
||||
Servlet[] servlets = new Servlet[this.registeredServlets.size()];
|
||||
for (int i = 0; i < servlets.length; i++) {
|
||||
servlets[i] = this.registeredServlets.get(i).getServlet();
|
||||
}
|
||||
return servlets;
|
||||
}
|
||||
|
||||
public List<RegisteredServlet> getRegisteredServlets() {
|
||||
return this.registeredServlets;
|
||||
}
|
||||
|
||||
public List<RegisteredFilter> getRegisteredFilters() {
|
||||
return this.registeredFilters;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
public static class RegisteredServlet {
|
||||
|
||||
private Servlet servlet;
|
||||
|
||||
private ServletRegistration.Dynamic registration;
|
||||
|
||||
public RegisteredServlet(Servlet servlet) {
|
||||
this.servlet = servlet;
|
||||
this.registration = mock(ServletRegistration.Dynamic.class);
|
||||
}
|
||||
|
||||
public ServletRegistration.Dynamic getRegistration() {
|
||||
return this.registration;
|
||||
}
|
||||
|
||||
public Servlet getServlet() {
|
||||
return this.servlet;
|
||||
}
|
||||
}
|
||||
|
||||
public static class RegisteredFilter {
|
||||
|
||||
private Filter filter;
|
||||
|
||||
private FilterRegistration.Dynamic registration;
|
||||
|
||||
public RegisteredFilter(Filter filter) {
|
||||
this.filter = filter;
|
||||
this.registration = mock(FilterRegistration.Dynamic.class);
|
||||
}
|
||||
|
||||
public FilterRegistration.Dynamic getRegistration() {
|
||||
return this.registration;
|
||||
}
|
||||
|
||||
public Filter getFilter() {
|
||||
return this.filter;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
/**
|
||||
* Simple mock Filter that does nothing.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class MockFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) throws IOException, ServletException {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.GenericServlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
/**
|
||||
* Simple mock Servlet that does nothing.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class MockServlet extends GenericServlet {
|
||||
|
||||
@Override
|
||||
public void service(ServletRequest req, ServletResponse res) throws ServletException,
|
||||
IOException {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.bootstrap.context.embedded.ServletRegistrationBean;
|
||||
|
||||
import static org.mockito.BDDMockito.*;
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests for {@link ServletRegistrationBean}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class ServletRegistrationBeanTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
private MockServlet servlet = new MockServlet();
|
||||
|
||||
@Mock
|
||||
private ServletContext servletContext;
|
||||
|
||||
@Mock
|
||||
private ServletRegistration.Dynamic registration;
|
||||
|
||||
@Mock
|
||||
private FilterRegistration.Dynamic filterRegistration;
|
||||
|
||||
@Before
|
||||
public void setupMocks() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
given(this.servletContext.addServlet(anyString(), (Servlet) anyObject()))
|
||||
.willReturn(this.registration);
|
||||
given(this.servletContext.addFilter(anyString(), (Filter) anyObject()))
|
||||
.willReturn(this.filterRegistration);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startupWithDefaults() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addServlet("mockServlet", this.servlet);
|
||||
verify(this.registration).setAsyncSupported(true);
|
||||
verify(this.registration).addMapping("/*");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startupWithSpecifiedValues() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean();
|
||||
bean.setName("test");
|
||||
bean.setServlet(this.servlet);
|
||||
bean.setAsyncSupported(false);
|
||||
bean.setInitParameters(Collections.singletonMap("a", "b"));
|
||||
bean.addInitParameter("c", "d");
|
||||
bean.setUrlMappings(new LinkedHashSet<String>(Arrays.asList("/a", "/b")));
|
||||
bean.addUrlMappings("/c");
|
||||
bean.setLoadOnStartup(10);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addServlet("test", this.servlet);
|
||||
verify(this.registration).setAsyncSupported(false);
|
||||
Map<String, String> expectedInitParameters = new HashMap<String, String>();
|
||||
expectedInitParameters.put("a", "b");
|
||||
expectedInitParameters.put("c", "d");
|
||||
verify(this.registration).setInitParameters(expectedInitParameters);
|
||||
verify(this.registration).addMapping("/a", "/b", "/c");
|
||||
verify(this.registration).setLoadOnStartup(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificName() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean();
|
||||
bean.setName("specificName");
|
||||
bean.setServlet(this.servlet);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addServlet("specificName", this.servlet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deducedName() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean();
|
||||
bean.setServlet(this.servlet);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.servletContext).addServlet("mockServlet", this.servlet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setServletMustNotBeNull() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean();
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("Servlet must not be null");
|
||||
bean.onStartup(this.servletContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createServletMustNotBeNull() throws Exception {
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("Servlet must not be null");
|
||||
new ServletRegistrationBean(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setMappingMustNotBeNull() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("UrlMappings must not be null");
|
||||
bean.setUrlMappings(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createMappingMustNotBeNull() throws Exception {
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("UrlMappings must not be null");
|
||||
new ServletRegistrationBean(this.servlet, (String[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addMappingMustNotBeNull() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet);
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("UrlMappings must not be null");
|
||||
bean.addUrlMappings((String[]) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setMappingReplacesValue() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a",
|
||||
"/b");
|
||||
bean.setUrlMappings(new LinkedHashSet<String>(Arrays.asList("/c", "/d")));
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.registration).addMapping("/c", "/d");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modifyInitParameters() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet, "/a",
|
||||
"/b");
|
||||
bean.addInitParameter("a", "b");
|
||||
bean.getInitParameters().put("a", "c");
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(this.registration).setInitParameters(Collections.singletonMap("a", "c"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filters() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet);
|
||||
Filter filter = new MockFilter();
|
||||
bean.addFilters(filter);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(servletContext).addFilter("mockFilter", filter);
|
||||
verify(filterRegistration).setAsyncSupported(true);
|
||||
verify(filterRegistration).addMappingForServletNames(
|
||||
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
|
||||
DispatcherType.INCLUDE, DispatcherType.ASYNC), false,
|
||||
"mockServlet");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filtersNoAsync() throws Exception {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(this.servlet);
|
||||
Filter filter = new MockFilter();
|
||||
bean.addFilters(filter);
|
||||
bean.setAsyncSupported(false);
|
||||
bean.onStartup(this.servletContext);
|
||||
verify(servletContext).addFilter("mockFilter", filter);
|
||||
verify(filterRegistration).setAsyncSupported(false);
|
||||
verify(filterRegistration).addMappingForServletNames(
|
||||
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
|
||||
DispatcherType.INCLUDE), false, "mockServlet");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.bootstrap.context.embedded.XmlEmbeddedWebApplicationContext;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests for {@link XmlEmbeddedWebApplicationContext}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class XmlEmbeddedWebApplicationContextTests {
|
||||
|
||||
private static final String PATH = XmlEmbeddedWebApplicationContextTests.class
|
||||
.getPackage().getName().replace(".", "/")
|
||||
+ "/";
|
||||
|
||||
private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml";
|
||||
|
||||
private XmlEmbeddedWebApplicationContext context;
|
||||
|
||||
@Test
|
||||
public void createFromResource() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext(new ClassPathResource(FILE,
|
||||
getClass()));
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFromResourceLocation() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext(PATH + FILE);
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createFromRelativeResourceLocation() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext(getClass(), FILE);
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAndRefreshFromResource() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext();
|
||||
this.context.load(new ClassPathResource(FILE, getClass()));
|
||||
this.context.refresh();
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAndRefreshFromResourceLocation() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext();
|
||||
this.context.load(PATH + FILE);
|
||||
this.context.refresh();
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadAndRefreshFromRelativeResourceLocation() throws Exception {
|
||||
this.context = new XmlEmbeddedWebApplicationContext();
|
||||
this.context.load(getClass(), FILE);
|
||||
this.context.refresh();
|
||||
verifyContext();
|
||||
}
|
||||
|
||||
private void verifyContext() {
|
||||
MockEmbeddedServletContainerFactory containerFactory = this.context
|
||||
.getBean(MockEmbeddedServletContainerFactory.class);
|
||||
Servlet servlet = this.context.getBean(Servlet.class);
|
||||
verify(containerFactory.getServletContext()).addServlet("servlet", servlet);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded.config;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
|
||||
import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContextTests;
|
||||
import org.springframework.bootstrap.context.embedded.EmbeddedServletContainerFactory;
|
||||
import org.springframework.bootstrap.context.embedded.MockEmbeddedServletContainerFactory;
|
||||
import org.springframework.bootstrap.context.embedded.MockServlet;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Example {@code @Configuration} for use with
|
||||
* {@link AnnotationConfigEmbeddedWebApplicationContextTests}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
@Configuration
|
||||
public class ExampleEmbeddedWebApplicationConfiguration {
|
||||
|
||||
@Bean
|
||||
public EmbeddedServletContainerFactory containerFactory() {
|
||||
return new MockEmbeddedServletContainerFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Servlet servlet() {
|
||||
return new MockServlet();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded.jetty;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.eclipse.jetty.webapp.Configuration;
|
||||
import org.eclipse.jetty.webapp.WebAppContext;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.bootstrap.context.embedded.AbstractEmbeddedServletContainerFactoryTests;
|
||||
import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainer;
|
||||
import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
|
||||
|
||||
import static org.mockito.Matchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests for {@link JettyEmbeddedServletContainerFactory} and
|
||||
* {@link JettyEmbeddedServletContainer}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class JettyEmbeddedServletContainerFactoryTests extends
|
||||
AbstractEmbeddedServletContainerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void jettyConfigurations() throws Exception {
|
||||
JettyEmbeddedServletContainerFactory factory = getFactory();
|
||||
Configuration[] configurations = new Configuration[4];
|
||||
for (int i = 0; i < configurations.length; i++) {
|
||||
configurations[i] = mock(Configuration.class);
|
||||
}
|
||||
factory.setConfigurations(Arrays.asList(configurations[0], configurations[1]));
|
||||
factory.addConfigurations(configurations[2], configurations[3]);
|
||||
this.container = factory.getEmbdeddedServletContainer();
|
||||
InOrder ordered = inOrder((Object[]) configurations);
|
||||
for (Configuration configuration : configurations) {
|
||||
ordered.verify(configuration).configure((WebAppContext) anyObject());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected JettyEmbeddedServletContainerFactory getFactory() {
|
||||
return new JettyEmbeddedServletContainerFactory();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.context.embedded.tomcat;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.catalina.LifecycleEvent;
|
||||
import org.apache.catalina.LifecycleListener;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InOrder;
|
||||
import org.springframework.bootstrap.context.embedded.AbstractEmbeddedServletContainerFactoryTests;
|
||||
import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainer;
|
||||
import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
|
||||
|
||||
import static org.mockito.Matchers.anyObject;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* Tests for {@link TomcatEmbeddedServletContainerFactory} and
|
||||
* {@link TomcatEmbeddedServletContainer}.
|
||||
*
|
||||
* @author Phillip Webb
|
||||
*/
|
||||
public class TomcatEmbeddedServletContainerFactoryTests extends
|
||||
AbstractEmbeddedServletContainerFactoryTests {
|
||||
|
||||
@Test
|
||||
public void tomcatListeners() throws Exception {
|
||||
TomcatEmbeddedServletContainerFactory factory = getFactory();
|
||||
LifecycleListener[] listeners = new LifecycleListener[4];
|
||||
for (int i = 0; i < listeners.length; i++) {
|
||||
listeners[i] = mock(LifecycleListener.class);
|
||||
}
|
||||
factory.setContextLifecycleListeners(Arrays.asList(listeners[0], listeners[1]));
|
||||
factory.addContextLifecycleListeners(listeners[2], listeners[3]);
|
||||
this.container = factory.getEmbdeddedServletContainer();
|
||||
InOrder ordered = inOrder((Object[]) listeners);
|
||||
for (LifecycleListener listener : listeners) {
|
||||
ordered.verify(listener).lifecycleEvent((LifecycleEvent) anyObject());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected TomcatEmbeddedServletContainerFactory getFactory() {
|
||||
return new TomcatEmbeddedServletContainerFactory();
|
||||
}
|
||||
|
||||
// FIXME test valve
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.logging;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class JavaLoggerConfigurerTests {
|
||||
|
||||
private PrintStream savedOutput;
|
||||
private ByteArrayOutputStream output;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.savedOutput = System.out;
|
||||
this.output = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(this.output));
|
||||
}
|
||||
|
||||
@After
|
||||
public void clear() {
|
||||
System.clearProperty("LOG_FILE");
|
||||
System.clearProperty("LOG_PATH");
|
||||
System.clearProperty("PID");
|
||||
System.setOut(this.savedOutput);
|
||||
}
|
||||
|
||||
private String getOutput() {
|
||||
return this.output.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultConfigLocation() throws Exception {
|
||||
JavaLoggerConfigurer.initLogging("classpath:logging-nondefault.properties");
|
||||
Log logger = LogFactory.getLog(JavaLoggerConfigurerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.contains("Hello world"));
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("["));
|
||||
}
|
||||
|
||||
@Test(expected = FileNotFoundException.class)
|
||||
public void testNonexistentConfigLocation() throws Exception {
|
||||
JavaLoggerConfigurer.initLogging("classpath:logging-nonexistent.properties");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.logging;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class LogbackConfigurerTests {
|
||||
|
||||
private PrintStream savedOutput;
|
||||
private ByteArrayOutputStream output;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.savedOutput = System.out;
|
||||
this.output = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(this.output));
|
||||
}
|
||||
|
||||
@After
|
||||
public void clear() {
|
||||
System.clearProperty("LOG_FILE");
|
||||
System.clearProperty("LOG_PATH");
|
||||
System.clearProperty("PID");
|
||||
System.setOut(this.savedOutput);
|
||||
}
|
||||
|
||||
private String getOutput() {
|
||||
return this.output.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultConfigLocation() throws Exception {
|
||||
LogbackConfigurer.initLogging("classpath:logback-nondefault.xml");
|
||||
Log logger = LogFactory.getLog(LogbackConfigurerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.contains("Hello world"));
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("/tmp/bootstrap.log"));
|
||||
}
|
||||
|
||||
@Test(expected = FileNotFoundException.class)
|
||||
public void testNonexistentConfigLocation() throws Exception {
|
||||
LogbackConfigurer.initLogging("classpath:logback-nonexistent.xml");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.logging;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.GenericApplicationContext;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class LoggingInitializerTests {
|
||||
|
||||
private LoggingInitializer initializer = new LoggingInitializer();
|
||||
|
||||
private PrintStream savedOutput;
|
||||
private ByteArrayOutputStream output;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.savedOutput = System.out;
|
||||
this.output = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(this.output));
|
||||
}
|
||||
|
||||
@After
|
||||
public void clear() {
|
||||
System.clearProperty("LOG_FILE");
|
||||
System.clearProperty("LOG_PATH");
|
||||
System.clearProperty("PID");
|
||||
System.setOut(this.savedOutput);
|
||||
}
|
||||
|
||||
private String getOutput() {
|
||||
return this.output.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultConfigLocation() {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
this.initializer.initialize(context);
|
||||
Log logger = LogFactory.getLog(LoggingInitializerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.contains("Hello world"));
|
||||
assertFalse("Wrong output:\n" + output, output.contains("???"));
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("["));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOverrideConfigLocation() {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new PropertySource<String>("manual") {
|
||||
@Override
|
||||
public Object getProperty(String name) {
|
||||
if ("logging.config".equals(name)) {
|
||||
return "classpath:logback-nondefault.xml";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
this.initializer.initialize(context);
|
||||
Log logger = LogFactory.getLog(LoggingInitializerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.contains("Hello world"));
|
||||
assertFalse("Wrong output:\n" + output, output.contains("???"));
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("/tmp/bootstrap.log"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddLogFileProperty() {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new PropertySource<String>("manual") {
|
||||
@Override
|
||||
public Object getProperty(String name) {
|
||||
if ("logging.config".equals(name)) {
|
||||
return "classpath:logback-nondefault.xml";
|
||||
}
|
||||
if ("logging.file".equals(name)) {
|
||||
return "foo.log";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
this.initializer.initialize(context);
|
||||
Log logger = LogFactory.getLog(LoggingInitializerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("foo.log"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddLogPathProperty() {
|
||||
GenericApplicationContext context = new GenericApplicationContext();
|
||||
context.getEnvironment().getPropertySources()
|
||||
.addFirst(new PropertySource<String>("manual") {
|
||||
@Override
|
||||
public Object getProperty(String name) {
|
||||
if ("logging.config".equals(name)) {
|
||||
return "classpath:logback-nondefault.xml";
|
||||
}
|
||||
if ("logging.path".equals(name)) {
|
||||
return "foo/";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
this.initializer.initialize(context);
|
||||
Log logger = LogFactory.getLog(LoggingInitializerTests.class);
|
||||
logger.info("Hello world");
|
||||
String output = getOutput().trim();
|
||||
assertTrue("Wrong output:\n" + output, output.startsWith("foo/bootstrap.log"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.bootstrap.logging;
|
||||
|
||||
import java.util.logging.Formatter;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
/**
|
||||
* @author Dave Syer
|
||||
*
|
||||
*/
|
||||
public class TestFormatter extends Formatter {
|
||||
|
||||
@Override
|
||||
public String format(LogRecord record) {
|
||||
return String.format("foo: %s -- %s\n", record.getLoggerName(),
|
||||
record.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2012-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.bootstrap.sampleconfig;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MyComponent {
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
my.property=fromprofilepropertiesfile
|
||||
@@ -0,0 +1 @@
|
||||
spring.profiles.active=myprofile
|
||||
12
spring-bootstrap/src/test/resources/logback-nondefault.xml
Normal file
12
spring-bootstrap/src/test/resources/logback-nondefault.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-/tmp/}bootstrap.log}"/>
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${LOG_FILE} [%t] ${PID:-????} %c{1}: %m%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
</root>
|
||||
</configuration>
|
||||
13
spring-bootstrap/src/test/resources/logback-test.xml
Normal file
13
spring-bootstrap/src/test/resources/logback-test.xml
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<property name="LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] bootstrap - ${PID:-????} %5p [%t] --- %c{1}: %m%n"/>
|
||||
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-/tmp/logs/service.log}}"/>
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>${LOG_PATTERN}</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,3 @@
|
||||
handlers = java.util.logging.ConsoleHandler
|
||||
.level = INFO
|
||||
java.util.logging.ConsoleHandler.formatter =
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<bean name="servletContainerFactory"
|
||||
class="org.springframework.bootstrap.context.embedded.MockEmbeddedServletContainerFactory" />
|
||||
|
||||
<bean name="servlet" class="org.springframework.bootstrap.context.embedded.MockServlet"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<bean id="myXmlComponent" class="org.springframework.bootstrap.sampleconfig.MyComponent"/>
|
||||
</beans>
|
||||
@@ -0,0 +1 @@
|
||||
my.property=fromspecificpropertiesfile
|
||||
@@ -0,0 +1 @@
|
||||
my.property=fromspecificlocation
|
||||
9
spring-bootstrap/src/test/resources/testprofiles.yml
Normal file
9
spring-bootstrap/src/test/resources/testprofiles.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
---
|
||||
my:
|
||||
property: fromyamlfile
|
||||
other: notempty
|
||||
---
|
||||
spring:
|
||||
profiles: dev
|
||||
my:
|
||||
property: fromdevprofile
|
||||
@@ -0,0 +1 @@
|
||||
my.property=frompropertiesfile
|
||||
11
spring-bootstrap/src/test/resources/testsetprofiles.yml
Normal file
11
spring-bootstrap/src/test/resources/testsetprofiles.yml
Normal file
@@ -0,0 +1,11 @@
|
||||
---
|
||||
spring:
|
||||
profiles:
|
||||
active: dev
|
||||
my:
|
||||
property: fromyamlfile
|
||||
---
|
||||
spring:
|
||||
profiles: dev
|
||||
my:
|
||||
property: fromdevprofile
|
||||
3
spring-bootstrap/src/test/resources/testyaml.yml
Normal file
3
spring-bootstrap/src/test/resources/testyaml.yml
Normal file
@@ -0,0 +1,3 @@
|
||||
---
|
||||
my:
|
||||
property: fromyamlfile
|
||||
Reference in New Issue
Block a user