Rename modules {org.springframework.*=>spring-*}
This renaming more intuitively expresses the relationship between
subprojects and the JAR artifacts they produce.
Tracking history across these renames is possible, but it requires
use of the --follow flag to `git log`, for example
$ git log spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history up until the renaming event, where
$ git log --follow spring-aop/src/main/java/org/springframework/aop/Advisor.java
will show history for all changes to the file, before and after the
renaming.
See http://chrisbeams.com/git-diff-across-renamed-directories
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 17.08.2004
|
||||
*/
|
||||
public class BeanWithObjectProperty {
|
||||
|
||||
private Object object;
|
||||
|
||||
public Object getObject() {
|
||||
return object;
|
||||
}
|
||||
|
||||
public void setObject(Object object) {
|
||||
this.object = object;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
import org.springframework.core.enums.ShortCodedLabeledEnum;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class Colour extends ShortCodedLabeledEnum {
|
||||
|
||||
public static final Colour RED = new Colour(0, "RED");
|
||||
public static final Colour BLUE = new Colour(1, "BLUE");
|
||||
public static final Colour GREEN = new Colour(2, "GREEN");
|
||||
public static final Colour PURPLE = new Colour(3, "PURPLE");
|
||||
|
||||
private Colour(int code, String label) {
|
||||
super(code, label);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public enum CustomEnum {
|
||||
|
||||
VALUE_1, VALUE_2;
|
||||
|
||||
public String toString() {
|
||||
return "CustomEnum: " + name();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 21.08.2003
|
||||
*/
|
||||
public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private boolean initialized;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
|
||||
public DerivedTestBean() {
|
||||
}
|
||||
|
||||
public DerivedTestBean(String[] names) {
|
||||
if (names == null || names.length < 2) {
|
||||
throw new IllegalArgumentException("Invalid names array");
|
||||
}
|
||||
setName(names[0]);
|
||||
setBeanName(names[1]);
|
||||
}
|
||||
|
||||
public static DerivedTestBean create(String[] names) {
|
||||
return new DerivedTestBean(names);
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
if (this.beanName == null || beanName == null) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setSpouseRef(String name) {
|
||||
setSpouse(new TestBean(name));
|
||||
}
|
||||
|
||||
|
||||
public void initialize() {
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
public boolean wasInitialized() {
|
||||
return initialized;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.beans;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 07.03.2006
|
||||
*/
|
||||
public class FieldAccessBean {
|
||||
|
||||
public String name;
|
||||
|
||||
protected int age;
|
||||
|
||||
private TestBean spouse;
|
||||
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public TestBean getSpouse() {
|
||||
return spouse;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.beans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class GenericBean<T> {
|
||||
|
||||
private Set<Integer> integerSet;
|
||||
|
||||
private Set<ITestBean> testBeanSet;
|
||||
|
||||
private List<Resource> resourceList;
|
||||
|
||||
private List<List<Integer>> listOfLists;
|
||||
|
||||
private ArrayList<String[]> listOfArrays;
|
||||
|
||||
private List<Map<Integer, Long>> listOfMaps;
|
||||
|
||||
private Map plainMap;
|
||||
|
||||
private Map<Short, Integer> shortMap;
|
||||
|
||||
private HashMap<Long, ?> longMap;
|
||||
|
||||
private Map<Number, Collection<? extends Object>> collectionMap;
|
||||
|
||||
private Map<String, Map<Integer, Long>> mapOfMaps;
|
||||
|
||||
private Map<Integer, List<Integer>> mapOfLists;
|
||||
|
||||
private CustomEnum customEnum;
|
||||
|
||||
private T genericProperty;
|
||||
|
||||
private List<T> genericListProperty;
|
||||
|
||||
|
||||
public GenericBean() {
|
||||
}
|
||||
|
||||
public GenericBean(Set<Integer> integerSet) {
|
||||
this.integerSet = integerSet;
|
||||
}
|
||||
|
||||
public GenericBean(Set<Integer> integerSet, List<Resource> resourceList) {
|
||||
this.integerSet = integerSet;
|
||||
this.resourceList = resourceList;
|
||||
}
|
||||
|
||||
public GenericBean(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
|
||||
this.integerSet = integerSet;
|
||||
this.shortMap = shortMap;
|
||||
}
|
||||
|
||||
public GenericBean(Map<Short, Integer> shortMap, Resource resource) {
|
||||
this.shortMap = shortMap;
|
||||
this.resourceList = Collections.singletonList(resource);
|
||||
}
|
||||
|
||||
public GenericBean(Map plainMap, Map<Short, Integer> shortMap) {
|
||||
this.plainMap = plainMap;
|
||||
this.shortMap = shortMap;
|
||||
}
|
||||
|
||||
public GenericBean(HashMap<Long, ?> longMap) {
|
||||
this.longMap = longMap;
|
||||
}
|
||||
|
||||
public GenericBean(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
|
||||
this.collectionMap = collectionMap;
|
||||
}
|
||||
|
||||
|
||||
public Set<Integer> getIntegerSet() {
|
||||
return integerSet;
|
||||
}
|
||||
|
||||
public void setIntegerSet(Set<Integer> integerSet) {
|
||||
this.integerSet = integerSet;
|
||||
}
|
||||
|
||||
public Set<ITestBean> getTestBeanSet() {
|
||||
return testBeanSet;
|
||||
}
|
||||
|
||||
public void setTestBeanSet(Set<ITestBean> testBeanSet) {
|
||||
this.testBeanSet = testBeanSet;
|
||||
}
|
||||
|
||||
public List<Resource> getResourceList() {
|
||||
return resourceList;
|
||||
}
|
||||
|
||||
public void setResourceList(List<Resource> resourceList) {
|
||||
this.resourceList = resourceList;
|
||||
}
|
||||
|
||||
public List<List<Integer>> getListOfLists() {
|
||||
return listOfLists;
|
||||
}
|
||||
|
||||
public ArrayList<String[]> getListOfArrays() {
|
||||
return listOfArrays;
|
||||
}
|
||||
|
||||
public void setListOfArrays(ArrayList<String[]> listOfArrays) {
|
||||
this.listOfArrays = listOfArrays;
|
||||
}
|
||||
|
||||
public void setListOfLists(List<List<Integer>> listOfLists) {
|
||||
this.listOfLists = listOfLists;
|
||||
}
|
||||
|
||||
public List<Map<Integer, Long>> getListOfMaps() {
|
||||
return listOfMaps;
|
||||
}
|
||||
|
||||
public void setListOfMaps(List<Map<Integer, Long>> listOfMaps) {
|
||||
this.listOfMaps = listOfMaps;
|
||||
}
|
||||
|
||||
public Map getPlainMap() {
|
||||
return plainMap;
|
||||
}
|
||||
|
||||
public Map<Short, Integer> getShortMap() {
|
||||
return shortMap;
|
||||
}
|
||||
|
||||
public void setShortMap(Map<Short, Integer> shortMap) {
|
||||
this.shortMap = shortMap;
|
||||
}
|
||||
|
||||
public HashMap<Long, ?> getLongMap() {
|
||||
return longMap;
|
||||
}
|
||||
|
||||
public void setLongMap(HashMap<Long, ?> longMap) {
|
||||
this.longMap = longMap;
|
||||
}
|
||||
|
||||
public Map<Number, Collection<? extends Object>> getCollectionMap() {
|
||||
return collectionMap;
|
||||
}
|
||||
|
||||
public void setCollectionMap(Map<Number, Collection<? extends Object>> collectionMap) {
|
||||
this.collectionMap = collectionMap;
|
||||
}
|
||||
|
||||
public Map<String, Map<Integer, Long>> getMapOfMaps() {
|
||||
return mapOfMaps;
|
||||
}
|
||||
|
||||
public void setMapOfMaps(Map<String, Map<Integer, Long>> mapOfMaps) {
|
||||
this.mapOfMaps = mapOfMaps;
|
||||
}
|
||||
|
||||
public Map<Integer, List<Integer>> getMapOfLists() {
|
||||
return mapOfLists;
|
||||
}
|
||||
|
||||
public void setMapOfLists(Map<Integer, List<Integer>> mapOfLists) {
|
||||
this.mapOfLists = mapOfLists;
|
||||
}
|
||||
|
||||
public T getGenericProperty() {
|
||||
return genericProperty;
|
||||
}
|
||||
|
||||
public void setGenericProperty(T genericProperty) {
|
||||
this.genericProperty = genericProperty;
|
||||
}
|
||||
|
||||
public List<T> getGenericListProperty() {
|
||||
return genericListProperty;
|
||||
}
|
||||
|
||||
public void setGenericListProperty(List<T> genericListProperty) {
|
||||
this.genericListProperty = genericListProperty;
|
||||
}
|
||||
|
||||
public CustomEnum getCustomEnum() {
|
||||
return customEnum;
|
||||
}
|
||||
|
||||
public void setCustomEnum(CustomEnum customEnum) {
|
||||
this.customEnum = customEnum;
|
||||
}
|
||||
|
||||
|
||||
public static GenericBean createInstance(Set<Integer> integerSet) {
|
||||
return new GenericBean(integerSet);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(Set<Integer> integerSet, List<Resource> resourceList) {
|
||||
return new GenericBean(integerSet, resourceList);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
|
||||
return new GenericBean(integerSet, shortMap);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(Map<Short, Integer> shortMap, Resource resource) {
|
||||
return new GenericBean(shortMap, resource);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(Map map, Map<Short, Integer> shortMap) {
|
||||
return new GenericBean(map, shortMap);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(HashMap<Long, ?> longMap) {
|
||||
return new GenericBean(longMap);
|
||||
}
|
||||
|
||||
public static GenericBean createInstance(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
|
||||
return new GenericBean(someFlag, collectionMap);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
public interface INestedTestBean {
|
||||
|
||||
public String getCompany();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
public interface IOther {
|
||||
|
||||
void absquatulate();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Interface used for {@link org.springframework.beans.TestBean}.
|
||||
*
|
||||
* <p>Two methods are the same as on Person, but if this
|
||||
* extends person it breaks quite a few tests..
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public interface ITestBean {
|
||||
|
||||
int getAge();
|
||||
|
||||
void setAge(int age);
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
ITestBean getSpouse();
|
||||
|
||||
void setSpouse(ITestBean spouse);
|
||||
|
||||
ITestBean[] getSpouses();
|
||||
|
||||
String[] getStringArray();
|
||||
|
||||
void setStringArray(String[] stringArray);
|
||||
|
||||
/**
|
||||
* Throws a given (non-null) exception.
|
||||
*/
|
||||
void exceptional(Throwable t) throws Throwable;
|
||||
|
||||
Object returnsThis();
|
||||
|
||||
INestedTestBean getDoctor();
|
||||
|
||||
INestedTestBean getLawyer();
|
||||
|
||||
IndexedTestBean getNestedIndexedBean();
|
||||
|
||||
/**
|
||||
* Increment the age by one.
|
||||
* @return the previous age
|
||||
*/
|
||||
int haveBirthday();
|
||||
|
||||
void unreliableFileOperation() throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.beans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 11.11.2003
|
||||
*/
|
||||
public class IndexedTestBean {
|
||||
|
||||
private TestBean[] array;
|
||||
|
||||
private Collection collection;
|
||||
|
||||
private List list;
|
||||
|
||||
private Set set;
|
||||
|
||||
private SortedSet sortedSet;
|
||||
|
||||
private Map map;
|
||||
|
||||
private SortedMap sortedMap;
|
||||
|
||||
|
||||
public IndexedTestBean() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
public IndexedTestBean(boolean populate) {
|
||||
if (populate) {
|
||||
populate();
|
||||
}
|
||||
}
|
||||
|
||||
public void populate() {
|
||||
TestBean tb0 = new TestBean("name0", 0);
|
||||
TestBean tb1 = new TestBean("name1", 0);
|
||||
TestBean tb2 = new TestBean("name2", 0);
|
||||
TestBean tb3 = new TestBean("name3", 0);
|
||||
TestBean tb4 = new TestBean("name4", 0);
|
||||
TestBean tb5 = new TestBean("name5", 0);
|
||||
TestBean tb6 = new TestBean("name6", 0);
|
||||
TestBean tb7 = new TestBean("name7", 0);
|
||||
TestBean tbX = new TestBean("nameX", 0);
|
||||
TestBean tbY = new TestBean("nameY", 0);
|
||||
this.array = new TestBean[] {tb0, tb1};
|
||||
this.list = new ArrayList();
|
||||
this.list.add(tb2);
|
||||
this.list.add(tb3);
|
||||
this.set = new TreeSet();
|
||||
this.set.add(tb6);
|
||||
this.set.add(tb7);
|
||||
this.map = new HashMap();
|
||||
this.map.put("key1", tb4);
|
||||
this.map.put("key2", tb5);
|
||||
this.map.put("key.3", tb5);
|
||||
List list = new ArrayList();
|
||||
list.add(tbX);
|
||||
list.add(tbY);
|
||||
this.map.put("key4", list);
|
||||
}
|
||||
|
||||
|
||||
public TestBean[] getArray() {
|
||||
return array;
|
||||
}
|
||||
|
||||
public void setArray(TestBean[] array) {
|
||||
this.array = array;
|
||||
}
|
||||
|
||||
public Collection getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(Collection collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
|
||||
public List getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Set getSet() {
|
||||
return set;
|
||||
}
|
||||
|
||||
public void setSet(Set set) {
|
||||
this.set = set;
|
||||
}
|
||||
|
||||
public SortedSet getSortedSet() {
|
||||
return sortedSet;
|
||||
}
|
||||
|
||||
public void setSortedSet(SortedSet sortedSet) {
|
||||
this.sortedSet = sortedSet;
|
||||
}
|
||||
|
||||
public Map getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public SortedMap getSortedMap() {
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
public void setSortedMap(SortedMap sortedMap) {
|
||||
this.sortedMap = sortedMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
/**
|
||||
* Simple nested test bean used for testing bean factories, AOP framework etc.
|
||||
*
|
||||
* @author Trevor D. Cook
|
||||
* @since 30.09.2003
|
||||
*/
|
||||
public class NestedTestBean implements INestedTestBean {
|
||||
|
||||
private String company = "";
|
||||
|
||||
public NestedTestBean() {
|
||||
}
|
||||
|
||||
public NestedTestBean(String company) {
|
||||
setCompany(company);
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = (company != null ? company : "");
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof NestedTestBean)) {
|
||||
return false;
|
||||
}
|
||||
NestedTestBean ntb = (NestedTestBean) obj;
|
||||
return this.company.equals(ntb.company);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.company.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "NestedTestBean: " + this.company;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public interface Person {
|
||||
|
||||
String getName();
|
||||
void setName(String name);
|
||||
int getAge();
|
||||
void setAge(int i);
|
||||
|
||||
/**
|
||||
* Test for non-property method matching.
|
||||
* If the parameter is a Throwable, it will be thrown rather than
|
||||
* returned.
|
||||
*/
|
||||
Object echo(Object o) throws Throwable;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.beans;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
* @since 2.0
|
||||
*/
|
||||
public class Pet {
|
||||
|
||||
private String name;
|
||||
|
||||
public Pet(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return getName();
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
final Pet pet = (Pet) o;
|
||||
|
||||
if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return (name != null ? name.hashCode() : 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Serializable implementation of the Person interface.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class SerializablePerson implements Person, Serializable {
|
||||
|
||||
private String name;
|
||||
private int age;
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Object echo(Object o) throws Throwable {
|
||||
if (o instanceof Throwable) {
|
||||
throw (Throwable) o;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (!(other instanceof SerializablePerson)) {
|
||||
return false;
|
||||
}
|
||||
SerializablePerson p = (SerializablePerson) other;
|
||||
return p.age == age && ObjectUtils.nullSafeEquals(name, p.name);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Simple test bean used for testing bean factories, the AOP framework etc.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 15 April 2001
|
||||
*/
|
||||
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private String country;
|
||||
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private String name;
|
||||
|
||||
private String sex;
|
||||
|
||||
private int age;
|
||||
|
||||
private boolean jedi;
|
||||
|
||||
private ITestBean[] spouses;
|
||||
|
||||
private String touchy;
|
||||
|
||||
private String[] stringArray;
|
||||
|
||||
private Integer[] someIntegerArray;
|
||||
|
||||
private Date date = new Date();
|
||||
|
||||
private Float myFloat = new Float(0.0);
|
||||
|
||||
private Collection friends = new LinkedList();
|
||||
|
||||
private Set someSet = new HashSet();
|
||||
|
||||
private Map someMap = new HashMap();
|
||||
|
||||
private List someList = new ArrayList();
|
||||
|
||||
private Properties someProperties = new Properties();
|
||||
|
||||
private INestedTestBean doctor = new NestedTestBean();
|
||||
|
||||
private INestedTestBean lawyer = new NestedTestBean();
|
||||
|
||||
private IndexedTestBean nestedIndexedBean;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
private Number someNumber;
|
||||
|
||||
private Colour favouriteColour;
|
||||
|
||||
private Boolean someBoolean;
|
||||
|
||||
private List otherColours;
|
||||
|
||||
private List pets;
|
||||
|
||||
|
||||
public TestBean() {
|
||||
}
|
||||
|
||||
public TestBean(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public TestBean(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse, Properties someProperties) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public TestBean(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public TestBean(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public TestBean(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public TestBean(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSex() {
|
||||
return sex;
|
||||
}
|
||||
|
||||
public void setSex(String sex) {
|
||||
this.sex = sex;
|
||||
if (this.name == null) {
|
||||
this.name = sex;
|
||||
}
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public boolean isJedi() {
|
||||
return jedi;
|
||||
}
|
||||
|
||||
public void setJedi(boolean jedi) {
|
||||
this.jedi = jedi;
|
||||
}
|
||||
|
||||
public ITestBean getSpouse() {
|
||||
return (spouses != null ? spouses[0] : null);
|
||||
}
|
||||
|
||||
public void setSpouse(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public ITestBean[] getSpouses() {
|
||||
return spouses;
|
||||
}
|
||||
|
||||
public String getTouchy() {
|
||||
return touchy;
|
||||
}
|
||||
|
||||
public void setTouchy(String touchy) throws Exception {
|
||||
if (touchy.indexOf('.') != -1) {
|
||||
throw new Exception("Can't contain a .");
|
||||
}
|
||||
if (touchy.indexOf(',') != -1) {
|
||||
throw new NumberFormatException("Number format exception: contains a ,");
|
||||
}
|
||||
this.touchy = touchy;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String[] getStringArray() {
|
||||
return stringArray;
|
||||
}
|
||||
|
||||
public void setStringArray(String[] stringArray) {
|
||||
this.stringArray = stringArray;
|
||||
}
|
||||
|
||||
public Integer[] getSomeIntegerArray() {
|
||||
return someIntegerArray;
|
||||
}
|
||||
|
||||
public void setSomeIntegerArray(Integer[] someIntegerArray) {
|
||||
this.someIntegerArray = someIntegerArray;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Float getMyFloat() {
|
||||
return myFloat;
|
||||
}
|
||||
|
||||
public void setMyFloat(Float myFloat) {
|
||||
this.myFloat = myFloat;
|
||||
}
|
||||
|
||||
public Collection getFriends() {
|
||||
return friends;
|
||||
}
|
||||
|
||||
public void setFriends(Collection friends) {
|
||||
this.friends = friends;
|
||||
}
|
||||
|
||||
public Set getSomeSet() {
|
||||
return someSet;
|
||||
}
|
||||
|
||||
public void setSomeSet(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public Map getSomeMap() {
|
||||
return someMap;
|
||||
}
|
||||
|
||||
public void setSomeMap(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public List getSomeList() {
|
||||
return someList;
|
||||
}
|
||||
|
||||
public void setSomeList(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public Properties getSomeProperties() {
|
||||
return someProperties;
|
||||
}
|
||||
|
||||
public void setSomeProperties(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public INestedTestBean getDoctor() {
|
||||
return doctor;
|
||||
}
|
||||
|
||||
public void setDoctor(INestedTestBean doctor) {
|
||||
this.doctor = doctor;
|
||||
}
|
||||
|
||||
public INestedTestBean getLawyer() {
|
||||
return lawyer;
|
||||
}
|
||||
|
||||
public void setLawyer(INestedTestBean lawyer) {
|
||||
this.lawyer = lawyer;
|
||||
}
|
||||
|
||||
public Number getSomeNumber() {
|
||||
return someNumber;
|
||||
}
|
||||
|
||||
public void setSomeNumber(Number someNumber) {
|
||||
this.someNumber = someNumber;
|
||||
}
|
||||
|
||||
public Colour getFavouriteColour() {
|
||||
return favouriteColour;
|
||||
}
|
||||
|
||||
public void setFavouriteColour(Colour favouriteColour) {
|
||||
this.favouriteColour = favouriteColour;
|
||||
}
|
||||
|
||||
public Boolean getSomeBoolean() {
|
||||
return someBoolean;
|
||||
}
|
||||
|
||||
public void setSomeBoolean(Boolean someBoolean) {
|
||||
this.someBoolean = someBoolean;
|
||||
}
|
||||
|
||||
public IndexedTestBean getNestedIndexedBean() {
|
||||
return nestedIndexedBean;
|
||||
}
|
||||
|
||||
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
|
||||
this.nestedIndexedBean = nestedIndexedBean;
|
||||
}
|
||||
|
||||
public List getOtherColours() {
|
||||
return otherColours;
|
||||
}
|
||||
|
||||
public void setOtherColours(List otherColours) {
|
||||
this.otherColours = otherColours;
|
||||
}
|
||||
|
||||
public List getPets() {
|
||||
return pets;
|
||||
}
|
||||
|
||||
public void setPets(List pets) {
|
||||
this.pets = pets;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
|
||||
*/
|
||||
public void exceptional(Throwable t) throws Throwable {
|
||||
if (t != null) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
public void unreliableFileOperation() throws IOException {
|
||||
throw new IOException();
|
||||
}
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#returnsThis()
|
||||
*/
|
||||
public Object returnsThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.IOther#absquatulate()
|
||||
*/
|
||||
public void absquatulate() {
|
||||
}
|
||||
|
||||
public int haveBirthday() {
|
||||
return age++;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other == null || !(other instanceof TestBean)) {
|
||||
return false;
|
||||
}
|
||||
TestBean tb2 = (TestBean) other;
|
||||
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.age;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (this.name != null && other instanceof TestBean) {
|
||||
return this.name.compareTo(((TestBean) other).getName());
|
||||
}
|
||||
else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans.factory;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
|
||||
/**
|
||||
* Simple factory to allow testing of FactoryBean support in AbstractBeanFactory.
|
||||
* Depending on whether its singleton property is set, it will return a singleton
|
||||
* or a prototype instance.
|
||||
*
|
||||
* <p>Implements InitializingBean interface, so we can check that
|
||||
* factories get this lifecycle callback if they want.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since 10.03.2003
|
||||
*/
|
||||
public class DummyFactory
|
||||
implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
|
||||
|
||||
public static final String SINGLETON_NAME = "Factory singleton";
|
||||
|
||||
private static boolean prototypeCreated;
|
||||
|
||||
/**
|
||||
* Clear static state.
|
||||
*/
|
||||
public static void reset() {
|
||||
prototypeCreated = false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Default is for factories to return a singleton instance.
|
||||
*/
|
||||
private boolean singleton = true;
|
||||
|
||||
private String beanName;
|
||||
|
||||
private AutowireCapableBeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private boolean initialized;
|
||||
|
||||
private TestBean testBean;
|
||||
|
||||
private TestBean otherTestBean;
|
||||
|
||||
|
||||
public DummyFactory() {
|
||||
this.testBean = new TestBean();
|
||||
this.testBean.setName(SINGLETON_NAME);
|
||||
this.testBean.setAge(25);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return if the bean managed by this factory is a singleton.
|
||||
* @see FactoryBean#isSingleton()
|
||||
*/
|
||||
public boolean isSingleton() {
|
||||
return this.singleton;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if the bean managed by this factory is a singleton.
|
||||
*/
|
||||
public void setSingleton(boolean singleton) {
|
||||
this.singleton = singleton;
|
||||
}
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
|
||||
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName);
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public void setOtherTestBean(TestBean otherTestBean) {
|
||||
this.otherTestBean = otherTestBean;
|
||||
this.testBean.setSpouse(otherTestBean);
|
||||
}
|
||||
|
||||
public TestBean getOtherTestBean() {
|
||||
return otherTestBean;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (initialized) {
|
||||
throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean");
|
||||
}
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Was this initialized by invocation of the
|
||||
* afterPropertiesSet() method from the InitializingBean interface?
|
||||
*/
|
||||
public boolean wasInitialized() {
|
||||
return initialized;
|
||||
}
|
||||
|
||||
public static boolean wasPrototypeCreated() {
|
||||
return prototypeCreated;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the managed object, supporting both singleton
|
||||
* and prototype mode.
|
||||
* @see FactoryBean#getObject()
|
||||
*/
|
||||
public Object getObject() throws BeansException {
|
||||
if (isSingleton()) {
|
||||
return this.testBean;
|
||||
}
|
||||
else {
|
||||
TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11);
|
||||
if (this.beanFactory != null) {
|
||||
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName);
|
||||
}
|
||||
prototypeCreated = true;
|
||||
return prototype;
|
||||
}
|
||||
}
|
||||
|
||||
public Class getObjectType() {
|
||||
return TestBean.class;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
if (this.testBean != null) {
|
||||
this.testBean.setName(null);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.beans.factory;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
|
||||
/**
|
||||
* Simple test of BeanFactory initialization and lifecycle callbacks.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Colin Sampaleanu
|
||||
* @since 12.03.2003
|
||||
*/
|
||||
public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
|
||||
|
||||
protected boolean initMethodDeclared = false;
|
||||
|
||||
protected String beanName;
|
||||
|
||||
protected BeanFactory owningFactory;
|
||||
|
||||
protected boolean postProcessedBeforeInit;
|
||||
|
||||
protected boolean inited;
|
||||
|
||||
protected boolean initedViaDeclaredInitMethod;
|
||||
|
||||
protected boolean postProcessedAfterInit;
|
||||
|
||||
protected boolean destroyed;
|
||||
|
||||
|
||||
public void setInitMethodDeclared(boolean initMethodDeclared) {
|
||||
this.initMethodDeclared = initMethodDeclared;
|
||||
}
|
||||
|
||||
public boolean isInitMethodDeclared() {
|
||||
return initMethodDeclared;
|
||||
}
|
||||
|
||||
public void setBeanName(String name) {
|
||||
this.beanName = name;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.owningFactory = beanFactory;
|
||||
}
|
||||
|
||||
public void postProcessBeforeInit() {
|
||||
if (this.inited || this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
|
||||
}
|
||||
if (this.postProcessedBeforeInit) {
|
||||
throw new RuntimeException("Factory called postProcessBeforeInit twice");
|
||||
}
|
||||
this.postProcessedBeforeInit = true;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (this.owningFactory == null) {
|
||||
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
if (!this.postProcessedBeforeInit) {
|
||||
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
if (this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
|
||||
}
|
||||
if (this.inited) {
|
||||
throw new RuntimeException("Factory called afterPropertiesSet twice");
|
||||
}
|
||||
this.inited = true;
|
||||
}
|
||||
|
||||
public void declaredInitMethod() {
|
||||
if (!this.inited) {
|
||||
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
|
||||
}
|
||||
|
||||
if (this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called declared init method twice");
|
||||
}
|
||||
this.initedViaDeclaredInitMethod = true;
|
||||
}
|
||||
|
||||
public void postProcessAfterInit() {
|
||||
if (!this.inited) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
|
||||
}
|
||||
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
|
||||
}
|
||||
if (this.postProcessedAfterInit) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit twice");
|
||||
}
|
||||
this.postProcessedAfterInit = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dummy business method that will fail unless the factory
|
||||
* managed the bean's lifecycle correctly
|
||||
*/
|
||||
public void businessMethod() {
|
||||
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
|
||||
!this.postProcessedAfterInit) {
|
||||
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (this.destroyed) {
|
||||
throw new IllegalStateException("Already destroyed");
|
||||
}
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean isDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public static class PostProcessor implements BeanPostProcessor {
|
||||
|
||||
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof LifecycleBean) {
|
||||
((LifecycleBean) bean).postProcessBeforeInit();
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof LifecycleBean) {
|
||||
((LifecycleBean) bean).postProcessAfterInit();
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans.factory;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
/**
|
||||
* Simple test of BeanFactory initialization
|
||||
* @author Rod Johnson
|
||||
* @since 12.03.2003
|
||||
*/
|
||||
public class MustBeInitialized implements InitializingBean {
|
||||
|
||||
private boolean inited;
|
||||
|
||||
/**
|
||||
* @see InitializingBean#afterPropertiesSet()
|
||||
*/
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
this.inited = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dummy business method that will fail unless the factory
|
||||
* managed the bean's lifecycle correctly
|
||||
*/
|
||||
public void businessMethod() {
|
||||
if (!this.inited)
|
||||
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.beans.factory.access;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Scrap bean for use in tests.
|
||||
*
|
||||
* @author Colin Sampaleanu
|
||||
*/
|
||||
public class TestBean {
|
||||
|
||||
private String name;
|
||||
|
||||
private List list;
|
||||
|
||||
private Object objRef;
|
||||
|
||||
/**
|
||||
* @return Returns the name.
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name The name to set.
|
||||
*/
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the list.
|
||||
*/
|
||||
public List getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list The list to set.
|
||||
*/
|
||||
public void setList(List list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Returns the object.
|
||||
*/
|
||||
public Object getObjRef() {
|
||||
return objRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param object The object to set.
|
||||
*/
|
||||
public void setObjRef(Object object) {
|
||||
this.objRef = object;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.context;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ApplicationContextException;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
|
||||
public class ACATester implements ApplicationContextAware {
|
||||
|
||||
private ApplicationContext ac;
|
||||
|
||||
public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException {
|
||||
// check reinitialization
|
||||
if (this.ac != null) {
|
||||
throw new IllegalStateException("Already initialized");
|
||||
}
|
||||
|
||||
// check message source availability
|
||||
if (ctx != null) {
|
||||
try {
|
||||
ctx.getMessage("code1", null, Locale.getDefault());
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
this.ac = ctx;
|
||||
}
|
||||
|
||||
public ApplicationContext getApplicationContext() {
|
||||
return ac;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.context;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanThatBroadcasts implements ApplicationContextAware {
|
||||
|
||||
public ApplicationContext applicationContext;
|
||||
|
||||
public int receivedCount;
|
||||
|
||||
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
if (applicationContext.getDisplayName().indexOf("listener") != -1) {
|
||||
applicationContext.getBean("listener");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.context;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A stub {@link ApplicationListener}.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanThatListens implements ApplicationListener {
|
||||
|
||||
private BeanThatBroadcasts beanThatBroadcasts;
|
||||
|
||||
private int eventCount;
|
||||
|
||||
|
||||
public BeanThatListens() {
|
||||
}
|
||||
|
||||
public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) {
|
||||
this.beanThatBroadcasts = beanThatBroadcasts;
|
||||
Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class);
|
||||
if (!beans.isEmpty()) {
|
||||
throw new IllegalStateException("Shouldn't have found any BeanThatListens instances");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
eventCount++;
|
||||
if (beanThatBroadcasts != null) {
|
||||
beanThatBroadcasts.receivedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
public int getEventCount() {
|
||||
return eventCount;
|
||||
}
|
||||
|
||||
public void zero() {
|
||||
eventCount = 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.springframework.context;
|
||||
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.LifecycleBean;
|
||||
|
||||
/**
|
||||
* Simple bean to test ApplicationContext lifecycle methods for beans
|
||||
*
|
||||
* @author Colin Sampaleanu
|
||||
* @since 03.07.2004
|
||||
*/
|
||||
public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware {
|
||||
|
||||
protected ApplicationContext owningContext;
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
super.setBeanFactory(beanFactory);
|
||||
if (this.owningContext != null)
|
||||
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
super.afterPropertiesSet();
|
||||
if (this.owningContext == null)
|
||||
throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
if (this.owningFactory == null)
|
||||
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
|
||||
|
||||
this.owningContext = applicationContext;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.springframework.context;
|
||||
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
|
||||
/**
|
||||
* Listener that maintains a global count of events.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since January 21, 2001
|
||||
*/
|
||||
public class TestListener implements ApplicationListener {
|
||||
|
||||
private int eventCount;
|
||||
|
||||
public int getEventCount() {
|
||||
return eventCount;
|
||||
}
|
||||
|
||||
public void zeroCounter() {
|
||||
eventCount = 0;
|
||||
}
|
||||
|
||||
public void onApplicationEvent(ApplicationEvent e) {
|
||||
++eventCount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.http.client;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.Random;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Utility class that finds free BSD ports for use in testing scenario's.
|
||||
*
|
||||
* @author Ben Hale
|
||||
* @author Arjen Poutsma
|
||||
*/
|
||||
public abstract class FreePortScanner {
|
||||
|
||||
private static final int MIN_SAFE_PORT = 1024;
|
||||
|
||||
private static final int MAX_PORT = 65535;
|
||||
|
||||
private static final Random random = new Random();
|
||||
|
||||
/**
|
||||
* Returns the number of a free port in the default range.
|
||||
*/
|
||||
public static int getFreePort() {
|
||||
return getFreePort(MIN_SAFE_PORT, MAX_PORT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of a free port in the given range.
|
||||
*/
|
||||
public static int getFreePort(int minPort, int maxPort) {
|
||||
Assert.isTrue(minPort > 0, "'minPort' must be larger than 0");
|
||||
Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort");
|
||||
int portRange = maxPort - minPort;
|
||||
int candidatePort;
|
||||
int searchCounter = 0;
|
||||
do {
|
||||
if (++searchCounter > portRange) {
|
||||
throw new IllegalStateException(
|
||||
String.format("There were no ports available in the range %d to %d", minPort, maxPort));
|
||||
}
|
||||
candidatePort = getRandomPort(minPort, portRange);
|
||||
}
|
||||
while (!isPortAvailable(candidatePort));
|
||||
|
||||
return candidatePort;
|
||||
}
|
||||
|
||||
private static int getRandomPort(int minPort, int portRange) {
|
||||
return minPort + random.nextInt(portRange);
|
||||
}
|
||||
|
||||
private static boolean isPortAvailable(int port) {
|
||||
ServerSocket serverSocket;
|
||||
try {
|
||||
serverSocket = new ServerSocket();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
throw new IllegalStateException("Unable to create ServerSocket.", ex);
|
||||
}
|
||||
|
||||
try {
|
||||
InetSocketAddress sa = new InetSocketAddress(port);
|
||||
serverSocket.bind(sa);
|
||||
return true;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
return false;
|
||||
}
|
||||
finally {
|
||||
try {
|
||||
serverSocket.close();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import javax.servlet.ServletInputStream;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Delegating implementation of {@link javax.servlet.ServletInputStream}.
|
||||
*
|
||||
* <p>Used by {@link MockHttpServletRequest}; typically not directly
|
||||
* used for testing application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see MockHttpServletRequest
|
||||
*/
|
||||
public class DelegatingServletInputStream extends ServletInputStream {
|
||||
|
||||
private final InputStream sourceStream;
|
||||
|
||||
|
||||
/**
|
||||
* Create a DelegatingServletInputStream for the given source stream.
|
||||
* @param sourceStream the source stream (never <code>null</code>)
|
||||
*/
|
||||
public DelegatingServletInputStream(InputStream sourceStream) {
|
||||
Assert.notNull(sourceStream, "Source InputStream must not be null");
|
||||
this.sourceStream = sourceStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying source stream (never <code>null</code>).
|
||||
*/
|
||||
public final InputStream getSourceStream() {
|
||||
return this.sourceStream;
|
||||
}
|
||||
|
||||
|
||||
public int read() throws IOException {
|
||||
return this.sourceStream.read();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
this.sourceStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Delegating implementation of {@link javax.servlet.ServletOutputStream}.
|
||||
*
|
||||
* <p>Used by {@link MockHttpServletResponse}; typically not directly
|
||||
* used for testing application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see MockHttpServletResponse
|
||||
*/
|
||||
public class DelegatingServletOutputStream extends ServletOutputStream {
|
||||
|
||||
private final OutputStream targetStream;
|
||||
|
||||
|
||||
/**
|
||||
* Create a DelegatingServletOutputStream for the given target stream.
|
||||
* @param targetStream the target stream (never <code>null</code>)
|
||||
*/
|
||||
public DelegatingServletOutputStream(OutputStream targetStream) {
|
||||
Assert.notNull(targetStream, "Target OutputStream must not be null");
|
||||
this.targetStream = targetStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying target stream (never <code>null</code>).
|
||||
*/
|
||||
public final OutputStream getTargetStream() {
|
||||
return this.targetStream;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void write(int b) throws IOException {
|
||||
this.targetStream.write(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() throws IOException {
|
||||
super.flush();
|
||||
this.targetStream.flush();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
this.targetStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
/**
|
||||
* Internal helper class that serves as value holder for request headers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rick Evans
|
||||
* @since 2.0.1
|
||||
*/
|
||||
class HeaderValueHolder {
|
||||
|
||||
private final List<Object> values = new LinkedList<Object>();
|
||||
|
||||
|
||||
public void setValue(Object value) {
|
||||
this.values.clear();
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
public void addValue(Object value) {
|
||||
this.values.add(value);
|
||||
}
|
||||
|
||||
public void addValues(Collection<?> values) {
|
||||
this.values.addAll(values);
|
||||
}
|
||||
|
||||
public void addValueArray(Object values) {
|
||||
CollectionUtils.mergeArrayIntoCollection(values, this.values);
|
||||
}
|
||||
|
||||
public List<Object> getValues() {
|
||||
return Collections.unmodifiableList(this.values);
|
||||
}
|
||||
|
||||
public List<String> getStringValues() {
|
||||
List<String> stringList = new ArrayList<String>(this.values.size());
|
||||
for (Object value : this.values) {
|
||||
stringList.add(value.toString());
|
||||
}
|
||||
return Collections.unmodifiableList(stringList);
|
||||
}
|
||||
|
||||
public Object getValue() {
|
||||
return (!this.values.isEmpty() ? this.values.get(0) : null);
|
||||
}
|
||||
|
||||
public String getStringValue() {
|
||||
return (!this.values.isEmpty() ? this.values.get(0).toString() : null);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Find a HeaderValueHolder by name, ignoring casing.
|
||||
* @param headers the Map of header names to HeaderValueHolders
|
||||
* @param name the name of the desired header
|
||||
* @return the corresponding HeaderValueHolder,
|
||||
* or <code>null</code> if none found
|
||||
*/
|
||||
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
|
||||
Assert.notNull(name, "Header name must not be null");
|
||||
for (String headerName : headers.keySet()) {
|
||||
if (headerName.equalsIgnoreCase(name)) {
|
||||
return headers.get(headerName);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.Writer;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.jsp.JspWriter;
|
||||
import javax.servlet.jsp.tagext.BodyContent;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.jsp.tagext.BodyContent} class.
|
||||
*
|
||||
* <p>Used for testing the web framework; only necessary for testing
|
||||
* applications when testing custom JSP tags.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5
|
||||
*/
|
||||
public class MockBodyContent extends BodyContent {
|
||||
|
||||
private final String content;
|
||||
|
||||
|
||||
/**
|
||||
* Create a MockBodyContent for the given response.
|
||||
* @param content the body content to expose
|
||||
* @param response the servlet response to wrap
|
||||
*/
|
||||
public MockBodyContent(String content, HttpServletResponse response) {
|
||||
this(content, response, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a MockBodyContent for the given response.
|
||||
* @param content the body content to expose
|
||||
* @param targetWriter the target Writer to wrap
|
||||
*/
|
||||
public MockBodyContent(String content, Writer targetWriter) {
|
||||
this(content, null, targetWriter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a MockBodyContent for the given response.
|
||||
* @param content the body content to expose
|
||||
* @param response the servlet response to wrap
|
||||
* @param targetWriter the target Writer to wrap
|
||||
*/
|
||||
public MockBodyContent(String content, HttpServletResponse response, Writer targetWriter) {
|
||||
super(adaptJspWriter(targetWriter, response));
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
private static JspWriter adaptJspWriter(Writer targetWriter, HttpServletResponse response) {
|
||||
if (targetWriter instanceof JspWriter) {
|
||||
return (JspWriter) targetWriter;
|
||||
}
|
||||
else {
|
||||
return new MockJspWriter(response, targetWriter);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public Reader getReader() {
|
||||
return new StringReader(this.content);
|
||||
}
|
||||
|
||||
public String getString() {
|
||||
return this.content;
|
||||
}
|
||||
|
||||
public void writeOut(Writer writer) throws IOException {
|
||||
writer.write(this.content);
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Delegating implementations of JspWriter's abstract methods
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void clear() throws IOException {
|
||||
getEnclosingWriter().clear();
|
||||
}
|
||||
|
||||
public void clearBuffer() throws IOException {
|
||||
getEnclosingWriter().clearBuffer();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
getEnclosingWriter().close();
|
||||
}
|
||||
|
||||
public int getRemaining() {
|
||||
return getEnclosingWriter().getRemaining();
|
||||
}
|
||||
|
||||
public void newLine() throws IOException {
|
||||
getEnclosingWriter().println();
|
||||
}
|
||||
|
||||
public void write(char value[], int offset, int length) throws IOException {
|
||||
getEnclosingWriter().write(value, offset, length);
|
||||
}
|
||||
|
||||
public void print(boolean value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(char value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(char[] value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(double value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(float value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(int value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(long value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(Object value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(String value) throws IOException {
|
||||
getEnclosingWriter().print(value);
|
||||
}
|
||||
|
||||
public void println() throws IOException {
|
||||
getEnclosingWriter().println();
|
||||
}
|
||||
|
||||
public void println(boolean value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(char value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(char[] value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(double value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(float value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(int value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(long value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(Object value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(String value) throws IOException {
|
||||
getEnclosingWriter().println(value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.FilterConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; also usefol for testing
|
||||
* custom {@link javax.servlet.Filter} implementations.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.0.3
|
||||
* @see MockFilterConfig
|
||||
* @see PassThroughFilterChain
|
||||
*/
|
||||
public class MockFilterChain implements FilterChain {
|
||||
|
||||
private ServletRequest request;
|
||||
|
||||
private ServletResponse response;
|
||||
|
||||
|
||||
/**
|
||||
* Records the request and response.
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
if (this.request != null) {
|
||||
throw new IllegalStateException("This FilterChain has already been called!");
|
||||
}
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the request that {@link #doFilter} has been called with.
|
||||
*/
|
||||
public ServletRequest getRequest() {
|
||||
return this.request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the response that {@link #doFilter} has been called with.
|
||||
*/
|
||||
public ServletResponse getResponse() {
|
||||
return this.response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.FilterConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; also usefol for testing
|
||||
* custom {@link javax.servlet.Filter} implementations.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see MockFilterChain
|
||||
* @see PassThroughFilterChain
|
||||
*/
|
||||
public class MockFilterConfig implements FilterConfig {
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final String filterName;
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig with a default {@link MockServletContext}.
|
||||
*/
|
||||
public MockFilterConfig() {
|
||||
this(null, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig with a default {@link MockServletContext}.
|
||||
* @param filterName the name of the filter
|
||||
*/
|
||||
public MockFilterConfig(String filterName) {
|
||||
this(null, filterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
*/
|
||||
public MockFilterConfig(ServletContext servletContext) {
|
||||
this(servletContext, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockFilterConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
* @param filterName the name of the filter
|
||||
*/
|
||||
public MockFilterConfig(ServletContext servletContext, String filterName) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.filterName = filterName;
|
||||
}
|
||||
|
||||
|
||||
public String getFilterName() {
|
||||
return filterName;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return servletContext;
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,948 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Principal;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.AsyncContext;
|
||||
import javax.servlet.DispatcherType;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletInputStream;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.servlet.http.Part;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.LinkedCaseInsensitiveMap;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpServletRequest}
|
||||
* interface. Supports the Servlet 2.5 API level; throws
|
||||
* {@link UnsupportedOperationException} for all methods introduced in Servlet 3.0.
|
||||
*
|
||||
* <p>Used for testing the web framework; also useful for testing
|
||||
* application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @author Rick Evans
|
||||
* @author Mark Fisher
|
||||
* @author Chris Beams
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockHttpServletRequest implements HttpServletRequest {
|
||||
|
||||
/**
|
||||
* The default protocol: 'http'.
|
||||
*/
|
||||
public static final String DEFAULT_PROTOCOL = "http";
|
||||
|
||||
/**
|
||||
* The default server address: '127.0.0.1'.
|
||||
*/
|
||||
public static final String DEFAULT_SERVER_ADDR = "127.0.0.1";
|
||||
|
||||
/**
|
||||
* The default server name: 'localhost'.
|
||||
*/
|
||||
public static final String DEFAULT_SERVER_NAME = "localhost";
|
||||
|
||||
/**
|
||||
* The default server port: '80'.
|
||||
*/
|
||||
public static final int DEFAULT_SERVER_PORT = 80;
|
||||
|
||||
/**
|
||||
* The default remote address: '127.0.0.1'.
|
||||
*/
|
||||
public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1";
|
||||
|
||||
/**
|
||||
* The default remote host: 'localhost'.
|
||||
*/
|
||||
public static final String DEFAULT_REMOTE_HOST = "localhost";
|
||||
|
||||
private static final String CONTENT_TYPE_HEADER = "Content-Type";
|
||||
|
||||
private static final String CHARSET_PREFIX = "charset=";
|
||||
|
||||
|
||||
private boolean active = true;
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletRequest properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private String characterEncoding;
|
||||
|
||||
private byte[] content;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>(16);
|
||||
|
||||
private String protocol = DEFAULT_PROTOCOL;
|
||||
|
||||
private String scheme = DEFAULT_PROTOCOL;
|
||||
|
||||
private String serverName = DEFAULT_SERVER_NAME;
|
||||
|
||||
private int serverPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String remoteAddr = DEFAULT_REMOTE_ADDR;
|
||||
|
||||
private String remoteHost = DEFAULT_REMOTE_HOST;
|
||||
|
||||
/** List of locales in descending order */
|
||||
private final List<Locale> locales = new LinkedList<Locale>();
|
||||
|
||||
private boolean secure = false;
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private int remotePort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String localName = DEFAULT_SERVER_NAME;
|
||||
|
||||
private String localAddr = DEFAULT_SERVER_ADDR;
|
||||
|
||||
private int localPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private Map<String, Part> parts = new HashMap<String, Part>();
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletRequest properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private String authType;
|
||||
|
||||
private Cookie[] cookies;
|
||||
|
||||
private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<HeaderValueHolder>();
|
||||
|
||||
private String method;
|
||||
|
||||
private String pathInfo;
|
||||
|
||||
private String contextPath = "";
|
||||
|
||||
private String queryString;
|
||||
|
||||
private String remoteUser;
|
||||
|
||||
private final Set<String> userRoles = new HashSet<String>();
|
||||
|
||||
private Principal userPrincipal;
|
||||
|
||||
private String requestedSessionId;
|
||||
|
||||
private String requestURI;
|
||||
|
||||
private String servletPath = "";
|
||||
|
||||
private HttpSession session;
|
||||
|
||||
private boolean requestedSessionIdValid = true;
|
||||
|
||||
private boolean requestedSessionIdFromCookie = true;
|
||||
|
||||
private boolean requestedSessionIdFromURL = false;
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Constructors
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest with a default
|
||||
* {@link MockServletContext}.
|
||||
* @see MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest() {
|
||||
this(null, "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest with a default
|
||||
* {@link MockServletContext}.
|
||||
* @param method the request method (may be <code>null</code>)
|
||||
* @param requestURI the request URI (may be <code>null</code>)
|
||||
* @see #setMethod
|
||||
* @see #setRequestURI
|
||||
* @see MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(String method, String requestURI) {
|
||||
this(null, method, requestURI);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest.
|
||||
* @param servletContext the ServletContext that the request runs in
|
||||
* (may be <code>null</code> to use a default MockServletContext)
|
||||
* @see MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(ServletContext servletContext) {
|
||||
this(servletContext, "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpServletRequest.
|
||||
* @param servletContext the ServletContext that the request runs in
|
||||
* (may be <code>null</code> to use a default MockServletContext)
|
||||
* @param method the request method (may be <code>null</code>)
|
||||
* @param requestURI the request URI (may be <code>null</code>)
|
||||
* @see #setMethod
|
||||
* @see #setRequestURI
|
||||
* @see MockServletContext
|
||||
*/
|
||||
public MockHttpServletRequest(ServletContext servletContext, String method, String requestURI) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.method = method;
|
||||
this.requestURI = requestURI;
|
||||
this.locales.add(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Lifecycle methods
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Return the ServletContext that this request is associated with.
|
||||
* (Not available in the standard HttpServletRequest interface for some reason.)
|
||||
*/
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether this request is still active (that is, not completed yet).
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return this.active;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark this request as completed, keeping its state.
|
||||
*/
|
||||
public void close() {
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate this request, clearing its state.
|
||||
*/
|
||||
public void invalidate() {
|
||||
close();
|
||||
clearAttributes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether this request is still active (that is, not completed yet),
|
||||
* throwing an IllegalStateException if not active anymore.
|
||||
*/
|
||||
protected void checkActive() throws IllegalStateException {
|
||||
if (!this.active) {
|
||||
throw new IllegalStateException("Request is not active anymore");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletRequest interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
checkActive();
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
checkActive();
|
||||
return Collections.enumeration(this.attributes.keySet());
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
return this.characterEncoding;
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String characterEncoding) {
|
||||
this.characterEncoding = characterEncoding;
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
|
||||
private void updateContentTypeHeader() {
|
||||
if (this.contentType != null) {
|
||||
StringBuilder sb = new StringBuilder(this.contentType);
|
||||
if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.characterEncoding != null) {
|
||||
sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding);
|
||||
}
|
||||
doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true);
|
||||
}
|
||||
}
|
||||
|
||||
public void setContent(byte[] content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public int getContentLength() {
|
||||
return (this.content != null ? this.content.length : -1);
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
if (contentType != null) {
|
||||
int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
|
||||
if (charsetIndex != -1) {
|
||||
String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
|
||||
this.characterEncoding = encoding;
|
||||
}
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public ServletInputStream getInputStream() {
|
||||
if (this.content != null) {
|
||||
return new DelegatingServletInputStream(new ByteArrayInputStream(this.content));
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a single value for the specified HTTP parameter.
|
||||
* <p>If there are already one or more values registered for the given
|
||||
* parameter name, they will be replaced.
|
||||
*/
|
||||
public void setParameter(String name, String value) {
|
||||
setParameter(name, new String[] {value});
|
||||
}
|
||||
|
||||
/**
|
||||
* Set an array of values for the specified HTTP parameter.
|
||||
* <p>If there are already one or more values registered for the given
|
||||
* parameter name, they will be replaced.
|
||||
*/
|
||||
public void setParameter(String name, String[] values) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.parameters.put(name, values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets all provided parameters <emphasis>replacing</emphasis> any
|
||||
* existing values for the provided parameter names. To add without
|
||||
* replacing existing values, use {@link #addParameters(java.util.Map)}.
|
||||
*/
|
||||
public void setParameters(Map params) {
|
||||
Assert.notNull(params, "Parameter map must not be null");
|
||||
for (Object key : params.keySet()) {
|
||||
Assert.isInstanceOf(String.class, key,
|
||||
"Parameter map key must be of type [" + String.class.getName() + "]");
|
||||
Object value = params.get(key);
|
||||
if (value instanceof String) {
|
||||
this.setParameter((String) key, (String) value);
|
||||
}
|
||||
else if (value instanceof String[]) {
|
||||
this.setParameter((String) key, (String[]) value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException(
|
||||
"Parameter map value must be single value " + " or array of type [" + String.class.getName() +
|
||||
"]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a single value for the specified HTTP parameter.
|
||||
* <p>If there are already one or more values registered for the given
|
||||
* parameter name, the given value will be added to the end of the list.
|
||||
*/
|
||||
public void addParameter(String name, String value) {
|
||||
addParameter(name, new String[] {value});
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an array of values for the specified HTTP parameter.
|
||||
* <p>If there are already one or more values registered for the given
|
||||
* parameter name, the given values will be added to the end of the list.
|
||||
*/
|
||||
public void addParameter(String name, String[] values) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
String[] oldArr = this.parameters.get(name);
|
||||
if (oldArr != null) {
|
||||
String[] newArr = new String[oldArr.length + values.length];
|
||||
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
|
||||
System.arraycopy(values, 0, newArr, oldArr.length, values.length);
|
||||
this.parameters.put(name, newArr);
|
||||
}
|
||||
else {
|
||||
this.parameters.put(name, values);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds all provided parameters <emphasis>without</emphasis> replacing
|
||||
* any existing values. To replace existing values, use
|
||||
* {@link #setParameters(java.util.Map)}.
|
||||
*/
|
||||
public void addParameters(Map params) {
|
||||
Assert.notNull(params, "Parameter map must not be null");
|
||||
for (Object key : params.keySet()) {
|
||||
Assert.isInstanceOf(String.class, key,
|
||||
"Parameter map key must be of type [" + String.class.getName() + "]");
|
||||
Object value = params.get(key);
|
||||
if (value instanceof String) {
|
||||
this.addParameter((String) key, (String) value);
|
||||
}
|
||||
else if (value instanceof String[]) {
|
||||
this.addParameter((String) key, (String[]) value);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Parameter map value must be single value " +
|
||||
" or array of type [" + String.class.getName() + "]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove already registered values for the specified HTTP parameter, if any.
|
||||
*/
|
||||
public void removeParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.parameters.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all existing parameters.
|
||||
*/
|
||||
public void removeAllParameters() {
|
||||
this.parameters.clear();
|
||||
}
|
||||
|
||||
public String getParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
String[] arr = this.parameters.get(name);
|
||||
return (arr != null && arr.length > 0 ? arr[0] : null);
|
||||
}
|
||||
|
||||
public Enumeration<String> getParameterNames() {
|
||||
return Collections.enumeration(this.parameters.keySet());
|
||||
}
|
||||
|
||||
public String[] getParameterValues(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.parameters.get(name);
|
||||
}
|
||||
|
||||
public Map<String, String[]> getParameterMap() {
|
||||
return Collections.unmodifiableMap(this.parameters);
|
||||
}
|
||||
|
||||
public void setProtocol(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return this.protocol;
|
||||
}
|
||||
|
||||
public void setScheme(String scheme) {
|
||||
this.scheme = scheme;
|
||||
}
|
||||
|
||||
public String getScheme() {
|
||||
return this.scheme;
|
||||
}
|
||||
|
||||
public void setServerName(String serverName) {
|
||||
this.serverName = serverName;
|
||||
}
|
||||
|
||||
public String getServerName() {
|
||||
return this.serverName;
|
||||
}
|
||||
|
||||
public void setServerPort(int serverPort) {
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
public int getServerPort() {
|
||||
return this.serverPort;
|
||||
}
|
||||
|
||||
public BufferedReader getReader() throws UnsupportedEncodingException {
|
||||
if (this.content != null) {
|
||||
InputStream sourceStream = new ByteArrayInputStream(this.content);
|
||||
Reader sourceReader = (this.characterEncoding != null) ?
|
||||
new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream);
|
||||
return new BufferedReader(sourceReader);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void setRemoteAddr(String remoteAddr) {
|
||||
this.remoteAddr = remoteAddr;
|
||||
}
|
||||
|
||||
public String getRemoteAddr() {
|
||||
return this.remoteAddr;
|
||||
}
|
||||
|
||||
public void setRemoteHost(String remoteHost) {
|
||||
this.remoteHost = remoteHost;
|
||||
}
|
||||
|
||||
public String getRemoteHost() {
|
||||
return this.remoteHost;
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
checkActive();
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
else {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
checkActive();
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all of this request's attributes.
|
||||
*/
|
||||
public void clearAttributes() {
|
||||
this.attributes.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new preferred locale, before any existing locales.
|
||||
*/
|
||||
public void addPreferredLocale(Locale locale) {
|
||||
Assert.notNull(locale, "Locale must not be null");
|
||||
this.locales.add(0, locale);
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return this.locales.get(0);
|
||||
}
|
||||
|
||||
public Enumeration<Locale> getLocales() {
|
||||
return Collections.enumeration(this.locales);
|
||||
}
|
||||
|
||||
public void setSecure(boolean secure) {
|
||||
this.secure = secure;
|
||||
}
|
||||
|
||||
public boolean isSecure() {
|
||||
return this.secure;
|
||||
}
|
||||
|
||||
public RequestDispatcher getRequestDispatcher(String path) {
|
||||
return new MockRequestDispatcher(path);
|
||||
}
|
||||
|
||||
public String getRealPath(String path) {
|
||||
return this.servletContext.getRealPath(path);
|
||||
}
|
||||
|
||||
public void setRemotePort(int remotePort) {
|
||||
this.remotePort = remotePort;
|
||||
}
|
||||
|
||||
public int getRemotePort() {
|
||||
return this.remotePort;
|
||||
}
|
||||
|
||||
public void setLocalName(String localName) {
|
||||
this.localName = localName;
|
||||
}
|
||||
|
||||
public String getLocalName() {
|
||||
return this.localName;
|
||||
}
|
||||
|
||||
public void setLocalAddr(String localAddr) {
|
||||
this.localAddr = localAddr;
|
||||
}
|
||||
|
||||
public String getLocalAddr() {
|
||||
return this.localAddr;
|
||||
}
|
||||
|
||||
public void setLocalPort(int localPort) {
|
||||
this.localPort = localPort;
|
||||
}
|
||||
|
||||
public int getLocalPort() {
|
||||
return this.localPort;
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletRequest interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void setAuthType(String authType) {
|
||||
this.authType = authType;
|
||||
}
|
||||
|
||||
public String getAuthType() {
|
||||
return this.authType;
|
||||
}
|
||||
|
||||
public void setCookies(Cookie... cookies) {
|
||||
this.cookies = cookies;
|
||||
}
|
||||
|
||||
public Cookie[] getCookies() {
|
||||
return this.cookies;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a header entry for the given name.
|
||||
* <p>If there was no entry for that header name before,
|
||||
* the value will be used as-is. In case of an existing entry,
|
||||
* a String array will be created, adding the given value (more
|
||||
* specifically, its toString representation) as further element.
|
||||
* <p>Multiple values can only be stored as list of Strings,
|
||||
* following the Servlet spec (see <code>getHeaders</code> accessor).
|
||||
* As alternative to repeated <code>addHeader</code> calls for
|
||||
* individual elements, you can use a single call with an entire
|
||||
* array or Collection of values as parameter.
|
||||
* @see #getHeaderNames
|
||||
* @see #getHeader
|
||||
* @see #getHeaders
|
||||
* @see #getDateHeader
|
||||
* @see #getIntHeader
|
||||
*/
|
||||
public void addHeader(String name, Object value) {
|
||||
if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentType((String) value);
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private void doAddHeaderValue(String name, Object value, boolean replace) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Assert.notNull(value, "Header value must not be null");
|
||||
if (header == null || replace) {
|
||||
header = new HeaderValueHolder();
|
||||
this.headers.put(name, header);
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
header.addValues((Collection) value);
|
||||
}
|
||||
else if (value.getClass().isArray()) {
|
||||
header.addValueArray(value);
|
||||
}
|
||||
else {
|
||||
header.addValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
public long getDateHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Object value = (header != null ? header.getValue() : null);
|
||||
if (value instanceof Date) {
|
||||
return ((Date) value).getTime();
|
||||
}
|
||||
else if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
else if (value != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"Value for header '" + name + "' is neither a Date nor a Number: " + value);
|
||||
}
|
||||
else {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
public String getHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getValue().toString() : null);
|
||||
}
|
||||
|
||||
public Enumeration<String> getHeaders(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return Collections.enumeration(header != null ? header.getStringValues() : new LinkedList<String>());
|
||||
}
|
||||
|
||||
public Enumeration<String> getHeaderNames() {
|
||||
return Collections.enumeration(this.headers.keySet());
|
||||
}
|
||||
|
||||
public int getIntHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Object value = (header != null ? header.getValue() : null);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
else if (value instanceof String) {
|
||||
return Integer.parseInt((String) value);
|
||||
}
|
||||
else if (value != null) {
|
||||
throw new NumberFormatException("Value for header '" + name + "' is not a Number: " + value);
|
||||
}
|
||||
else {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public void setMethod(String method) {
|
||||
this.method = method;
|
||||
}
|
||||
|
||||
public String getMethod() {
|
||||
return this.method;
|
||||
}
|
||||
|
||||
public void setPathInfo(String pathInfo) {
|
||||
this.pathInfo = pathInfo;
|
||||
}
|
||||
|
||||
public String getPathInfo() {
|
||||
return this.pathInfo;
|
||||
}
|
||||
|
||||
public String getPathTranslated() {
|
||||
return (this.pathInfo != null ? getRealPath(this.pathInfo) : null);
|
||||
}
|
||||
|
||||
public void setContextPath(String contextPath) {
|
||||
this.contextPath = contextPath;
|
||||
}
|
||||
|
||||
public String getContextPath() {
|
||||
return this.contextPath;
|
||||
}
|
||||
|
||||
public void setQueryString(String queryString) {
|
||||
this.queryString = queryString;
|
||||
}
|
||||
|
||||
public String getQueryString() {
|
||||
return this.queryString;
|
||||
}
|
||||
|
||||
public void setRemoteUser(String remoteUser) {
|
||||
this.remoteUser = remoteUser;
|
||||
}
|
||||
|
||||
public String getRemoteUser() {
|
||||
return this.remoteUser;
|
||||
}
|
||||
|
||||
public void addUserRole(String role) {
|
||||
this.userRoles.add(role);
|
||||
}
|
||||
|
||||
public boolean isUserInRole(String role) {
|
||||
return this.userRoles.contains(role);
|
||||
}
|
||||
|
||||
public void setUserPrincipal(Principal userPrincipal) {
|
||||
this.userPrincipal = userPrincipal;
|
||||
}
|
||||
|
||||
public Principal getUserPrincipal() {
|
||||
return this.userPrincipal;
|
||||
}
|
||||
|
||||
public void setRequestedSessionId(String requestedSessionId) {
|
||||
this.requestedSessionId = requestedSessionId;
|
||||
}
|
||||
|
||||
public String getRequestedSessionId() {
|
||||
return this.requestedSessionId;
|
||||
}
|
||||
|
||||
public void setRequestURI(String requestURI) {
|
||||
this.requestURI = requestURI;
|
||||
}
|
||||
|
||||
public String getRequestURI() {
|
||||
return this.requestURI;
|
||||
}
|
||||
|
||||
public StringBuffer getRequestURL() {
|
||||
StringBuffer url = new StringBuffer(this.scheme);
|
||||
url.append("://").append(this.serverName).append(':').append(this.serverPort);
|
||||
url.append(getRequestURI());
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setServletPath(String servletPath) {
|
||||
this.servletPath = servletPath;
|
||||
}
|
||||
|
||||
public String getServletPath() {
|
||||
return this.servletPath;
|
||||
}
|
||||
|
||||
public void setSession(HttpSession session) {
|
||||
this.session = session;
|
||||
if (session instanceof MockHttpSession) {
|
||||
MockHttpSession mockSession = ((MockHttpSession) session);
|
||||
mockSession.access();
|
||||
}
|
||||
}
|
||||
|
||||
public HttpSession getSession(boolean create) {
|
||||
checkActive();
|
||||
// Reset session if invalidated.
|
||||
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) {
|
||||
this.session = null;
|
||||
}
|
||||
// Create new session if necessary.
|
||||
if (this.session == null && create) {
|
||||
this.session = new MockHttpSession(this.servletContext);
|
||||
}
|
||||
return this.session;
|
||||
}
|
||||
|
||||
public HttpSession getSession() {
|
||||
return getSession(true);
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
|
||||
this.requestedSessionIdValid = requestedSessionIdValid;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdValid() {
|
||||
return this.requestedSessionIdValid;
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {
|
||||
this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromCookie() {
|
||||
return this.requestedSessionIdFromCookie;
|
||||
}
|
||||
|
||||
public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {
|
||||
this.requestedSessionIdFromURL = requestedSessionIdFromURL;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromURL() {
|
||||
return this.requestedSessionIdFromURL;
|
||||
}
|
||||
|
||||
public boolean isRequestedSessionIdFromUrl() {
|
||||
return isRequestedSessionIdFromURL();
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Methods introduced in Servlet 3.0
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public AsyncContext getAsyncContext() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public DispatcherType getDispatcherType() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isAsyncSupported() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public AsyncContext startAsync() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean isAsyncStarted() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void addPart(Part part) {
|
||||
parts.put(part.getName(), part);
|
||||
}
|
||||
|
||||
public Part getPart(String key) throws IOException, IllegalStateException, ServletException {
|
||||
return parts.get(key);
|
||||
}
|
||||
|
||||
public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
|
||||
return parts.values();
|
||||
}
|
||||
|
||||
public void login(String arg0, String arg1) throws ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void logout() throws ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.mock.web;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.io.Writer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.LinkedCaseInsensitiveMap;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpServletResponse}
|
||||
* interface. Supports the Servlet 2.5 API level.
|
||||
*
|
||||
* <p>Used for testing the web framework; also useful for testing
|
||||
* application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockHttpServletResponse implements HttpServletResponse {
|
||||
|
||||
public static final int DEFAULT_SERVER_PORT = 80;
|
||||
|
||||
private static final String CHARSET_PREFIX = "charset=";
|
||||
|
||||
private static final String CONTENT_TYPE_HEADER = "Content-Type";
|
||||
|
||||
private static final String CONTENT_LENGTH_HEADER = "Content-Length";
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletResponse properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private boolean outputStreamAccessAllowed = true;
|
||||
|
||||
private boolean writerAccessAllowed = true;
|
||||
|
||||
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
|
||||
|
||||
private boolean charset = false;
|
||||
|
||||
private final ByteArrayOutputStream content = new ByteArrayOutputStream();
|
||||
|
||||
private final ServletOutputStream outputStream = new ResponseServletOutputStream(this.content);
|
||||
|
||||
private PrintWriter writer;
|
||||
|
||||
private int contentLength = 0;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private int bufferSize = 4096;
|
||||
|
||||
private boolean committed;
|
||||
|
||||
private Locale locale = Locale.getDefault();
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletResponse properties
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
private final List<Cookie> cookies = new ArrayList<Cookie>();
|
||||
|
||||
private final Map<String, HeaderValueHolder> headers = new LinkedCaseInsensitiveMap<HeaderValueHolder>();
|
||||
|
||||
private int status = HttpServletResponse.SC_OK;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
private String redirectedUrl;
|
||||
|
||||
private String forwardedUrl;
|
||||
|
||||
private final List<String> includedUrls = new ArrayList<String>();
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// ServletResponse interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set whether {@link #getOutputStream()} access is allowed.
|
||||
* <p>Default is <code>true</code>.
|
||||
*/
|
||||
public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed) {
|
||||
this.outputStreamAccessAllowed = outputStreamAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether {@link #getOutputStream()} access is allowed.
|
||||
*/
|
||||
public boolean isOutputStreamAccessAllowed() {
|
||||
return this.outputStreamAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether {@link #getWriter()} access is allowed.
|
||||
* <p>Default is <code>true</code>.
|
||||
*/
|
||||
public void setWriterAccessAllowed(boolean writerAccessAllowed) {
|
||||
this.writerAccessAllowed = writerAccessAllowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether {@link #getOutputStream()} access is allowed.
|
||||
*/
|
||||
public boolean isWriterAccessAllowed() {
|
||||
return this.writerAccessAllowed;
|
||||
}
|
||||
|
||||
public void setCharacterEncoding(String characterEncoding) {
|
||||
this.characterEncoding = characterEncoding;
|
||||
this.charset = true;
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
|
||||
private void updateContentTypeHeader() {
|
||||
if (this.contentType != null) {
|
||||
StringBuilder sb = new StringBuilder(this.contentType);
|
||||
if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.charset) {
|
||||
sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding);
|
||||
}
|
||||
doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true);
|
||||
}
|
||||
}
|
||||
|
||||
public String getCharacterEncoding() {
|
||||
return this.characterEncoding;
|
||||
}
|
||||
|
||||
public ServletOutputStream getOutputStream() {
|
||||
if (!this.outputStreamAccessAllowed) {
|
||||
throw new IllegalStateException("OutputStream access not allowed");
|
||||
}
|
||||
return this.outputStream;
|
||||
}
|
||||
|
||||
public PrintWriter getWriter() throws UnsupportedEncodingException {
|
||||
if (!this.writerAccessAllowed) {
|
||||
throw new IllegalStateException("Writer access not allowed");
|
||||
}
|
||||
if (this.writer == null) {
|
||||
Writer targetWriter = (this.characterEncoding != null ?
|
||||
new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content));
|
||||
this.writer = new ResponsePrintWriter(targetWriter);
|
||||
}
|
||||
return this.writer;
|
||||
}
|
||||
|
||||
public byte[] getContentAsByteArray() {
|
||||
flushBuffer();
|
||||
return this.content.toByteArray();
|
||||
}
|
||||
|
||||
public String getContentAsString() throws UnsupportedEncodingException {
|
||||
flushBuffer();
|
||||
return (this.characterEncoding != null) ?
|
||||
this.content.toString(this.characterEncoding) : this.content.toString();
|
||||
}
|
||||
|
||||
public void setContentLength(int contentLength) {
|
||||
this.contentLength = contentLength;
|
||||
doAddHeaderValue(CONTENT_LENGTH_HEADER, contentLength, true);
|
||||
}
|
||||
|
||||
public int getContentLength() {
|
||||
return this.contentLength;
|
||||
}
|
||||
|
||||
public void setContentType(String contentType) {
|
||||
this.contentType = contentType;
|
||||
if (contentType != null) {
|
||||
int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
|
||||
if (charsetIndex != -1) {
|
||||
String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
|
||||
this.characterEncoding = encoding;
|
||||
this.charset = true;
|
||||
}
|
||||
updateContentTypeHeader();
|
||||
}
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public void setBufferSize(int bufferSize) {
|
||||
this.bufferSize = bufferSize;
|
||||
}
|
||||
|
||||
public int getBufferSize() {
|
||||
return this.bufferSize;
|
||||
}
|
||||
|
||||
public void flushBuffer() {
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void resetBuffer() {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot reset buffer - response is already committed");
|
||||
}
|
||||
this.content.reset();
|
||||
}
|
||||
|
||||
private void setCommittedIfBufferSizeExceeded() {
|
||||
int bufSize = getBufferSize();
|
||||
if (bufSize > 0 && this.content.size() > bufSize) {
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void setCommitted(boolean committed) {
|
||||
this.committed = committed;
|
||||
}
|
||||
|
||||
public boolean isCommitted() {
|
||||
return this.committed;
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
resetBuffer();
|
||||
this.characterEncoding = null;
|
||||
this.contentLength = 0;
|
||||
this.contentType = null;
|
||||
this.locale = null;
|
||||
this.cookies.clear();
|
||||
this.headers.clear();
|
||||
this.status = HttpServletResponse.SC_OK;
|
||||
this.errorMessage = null;
|
||||
}
|
||||
|
||||
public void setLocale(Locale locale) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
public Locale getLocale() {
|
||||
return this.locale;
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// HttpServletResponse interface
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void addCookie(Cookie cookie) {
|
||||
Assert.notNull(cookie, "Cookie must not be null");
|
||||
this.cookies.add(cookie);
|
||||
}
|
||||
|
||||
public Cookie[] getCookies() {
|
||||
return this.cookies.toArray(new Cookie[this.cookies.size()]);
|
||||
}
|
||||
|
||||
public Cookie getCookie(String name) {
|
||||
Assert.notNull(name, "Cookie name must not be null");
|
||||
for (Cookie cookie : this.cookies) {
|
||||
if (name.equals(cookie.getName())) {
|
||||
return cookie;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean containsHeader(String name) {
|
||||
return (HeaderValueHolder.getByName(this.headers, name) != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the names of all specified headers as a Set of Strings.
|
||||
* @return the <code>Set</code> of header name <code>Strings</code>, or an empty <code>Set</code> if none
|
||||
*/
|
||||
public Set<String> getHeaderNames() {
|
||||
return this.headers.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the primary value for the given header, if any.
|
||||
* <p>Will return the first value in case of multiple values.
|
||||
* @param name the name of the header
|
||||
* @return the associated header value, or <code>null<code> if none
|
||||
*/
|
||||
public String getHeader(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getValue().toString() : null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all values for the given header as a List of value objects.
|
||||
* @param name the name of the header
|
||||
* @return the associated header values, or an empty List if none
|
||||
*/
|
||||
public List<String> getHeaders(String name) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
return (header != null ? header.getStringValues() : Collections.<String>emptyList());
|
||||
}
|
||||
|
||||
/**
|
||||
* The default implementation returns the given URL String as-is.
|
||||
* <p>Can be overridden in subclasses, appending a session id or the like.
|
||||
*/
|
||||
public String encodeURL(String url) {
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default implementation delegates to {@link #encodeURL},
|
||||
* returning the given URL String as-is.
|
||||
* <p>Can be overridden in subclasses, appending a session id or the like
|
||||
* in a redirect-specific fashion. For general URL encoding rules,
|
||||
* override the common {@link #encodeURL} method instead, appyling
|
||||
* to redirect URLs as well as to general URLs.
|
||||
*/
|
||||
public String encodeRedirectURL(String url) {
|
||||
return encodeURL(url);
|
||||
}
|
||||
|
||||
public String encodeUrl(String url) {
|
||||
return encodeURL(url);
|
||||
}
|
||||
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return encodeRedirectURL(url);
|
||||
}
|
||||
|
||||
public void sendError(int status, String errorMessage) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot set error status - response is already committed");
|
||||
}
|
||||
this.status = status;
|
||||
this.errorMessage = errorMessage;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void sendError(int status) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot set error status - response is already committed");
|
||||
}
|
||||
this.status = status;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public void sendRedirect(String url) throws IOException {
|
||||
if (isCommitted()) {
|
||||
throw new IllegalStateException("Cannot send redirect - response is already committed");
|
||||
}
|
||||
Assert.notNull(url, "Redirect URL must not be null");
|
||||
this.redirectedUrl = url;
|
||||
setCommitted(true);
|
||||
}
|
||||
|
||||
public String getRedirectedUrl() {
|
||||
return this.redirectedUrl;
|
||||
}
|
||||
|
||||
public void setDateHeader(String name, long value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addDateHeader(String name, long value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void setHeader(String name, String value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addHeader(String name, String value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void setIntHeader(String name, int value) {
|
||||
setHeaderValue(name, value);
|
||||
}
|
||||
|
||||
public void addIntHeader(String name, int value) {
|
||||
addHeaderValue(name, value);
|
||||
}
|
||||
|
||||
private void setHeaderValue(String name, Object value) {
|
||||
if (setSpecialHeader(name, value)) {
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, true);
|
||||
}
|
||||
|
||||
private void addHeaderValue(String name, Object value) {
|
||||
if (setSpecialHeader(name, value)) {
|
||||
return;
|
||||
}
|
||||
doAddHeaderValue(name, value, false);
|
||||
}
|
||||
|
||||
private boolean setSpecialHeader(String name, Object value) {
|
||||
if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentType((String) value);
|
||||
return true;
|
||||
}
|
||||
else if (CONTENT_LENGTH_HEADER.equalsIgnoreCase(name)) {
|
||||
setContentLength(Integer.parseInt((String) value));
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void doAddHeaderValue(String name, Object value, boolean replace) {
|
||||
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
|
||||
Assert.notNull(value, "Header value must not be null");
|
||||
if (header == null) {
|
||||
header = new HeaderValueHolder();
|
||||
this.headers.put(name, header);
|
||||
}
|
||||
if (replace) {
|
||||
header.setValue(value);
|
||||
}
|
||||
else {
|
||||
header.addValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public void setStatus(int status, String errorMessage) {
|
||||
this.status = status;
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return this.errorMessage;
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Methods for MockRequestDispatcher
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public void setForwardedUrl(String forwardedUrl) {
|
||||
this.forwardedUrl = forwardedUrl;
|
||||
}
|
||||
|
||||
public String getForwardedUrl() {
|
||||
return this.forwardedUrl;
|
||||
}
|
||||
|
||||
public void setIncludedUrl(String includedUrl) {
|
||||
this.includedUrls.clear();
|
||||
if (includedUrl != null) {
|
||||
this.includedUrls.add(includedUrl);
|
||||
}
|
||||
}
|
||||
|
||||
public String getIncludedUrl() {
|
||||
int count = this.includedUrls.size();
|
||||
if (count > 1) {
|
||||
throw new IllegalStateException(
|
||||
"More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls);
|
||||
}
|
||||
return (count == 1 ? this.includedUrls.get(0) : null);
|
||||
}
|
||||
|
||||
public void addIncludedUrl(String includedUrl) {
|
||||
Assert.notNull(includedUrl, "Included URL must not be null");
|
||||
this.includedUrls.add(includedUrl);
|
||||
}
|
||||
|
||||
public List<String> getIncludedUrls() {
|
||||
return this.includedUrls;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner class that adapts the ServletOutputStream to mark the
|
||||
* response as committed once the buffer size is exceeded.
|
||||
*/
|
||||
private class ResponseServletOutputStream extends DelegatingServletOutputStream {
|
||||
|
||||
public ResponseServletOutputStream(OutputStream out) {
|
||||
super(out);
|
||||
}
|
||||
|
||||
public void write(int b) throws IOException {
|
||||
super.write(b);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
super.flush();
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner class that adapts the PrintWriter to mark the
|
||||
* response as committed once the buffer size is exceeded.
|
||||
*/
|
||||
private class ResponsePrintWriter extends PrintWriter {
|
||||
|
||||
public ResponsePrintWriter(Writer out) {
|
||||
super(out, true);
|
||||
}
|
||||
|
||||
public void write(char buf[], int off, int len) {
|
||||
super.write(buf, off, len);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void write(String s, int off, int len) {
|
||||
super.write(s, off, len);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void write(int c) {
|
||||
super.write(c);
|
||||
super.flush();
|
||||
setCommittedIfBufferSizeExceeded();
|
||||
}
|
||||
|
||||
public void flush() {
|
||||
super.flush();
|
||||
setCommitted(true);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.servlet.http.HttpSessionBindingEvent;
|
||||
import javax.servlet.http.HttpSessionBindingListener;
|
||||
import javax.servlet.http.HttpSessionContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.http.HttpSession} interface.
|
||||
* Supports the Servlet 2.4 API level.
|
||||
*
|
||||
* <p>Used for testing the web framework; also useful for testing
|
||||
* application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Rod Johnson
|
||||
* @author Mark Fisher
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockHttpSession implements HttpSession {
|
||||
|
||||
public static final String SESSION_COOKIE_NAME = "JSESSION";
|
||||
|
||||
private static int nextId = 1;
|
||||
|
||||
|
||||
private final String id;
|
||||
|
||||
private final long creationTime = System.currentTimeMillis();
|
||||
|
||||
private int maxInactiveInterval;
|
||||
|
||||
private long lastAccessedTime = System.currentTimeMillis();
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private boolean invalid = false;
|
||||
|
||||
private boolean isNew = true;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession with a default {@link MockServletContext}.
|
||||
* @see MockServletContext
|
||||
*/
|
||||
public MockHttpSession() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession.
|
||||
* @param servletContext the ServletContext that the session runs in
|
||||
*/
|
||||
public MockHttpSession(ServletContext servletContext) {
|
||||
this(servletContext, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockHttpSession.
|
||||
* @param servletContext the ServletContext that the session runs in
|
||||
* @param id a unique identifier for this session
|
||||
*/
|
||||
public MockHttpSession(ServletContext servletContext, String id) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.id = (id != null ? id : Integer.toString(nextId++));
|
||||
}
|
||||
|
||||
|
||||
public long getCreationTime() {
|
||||
return this.creationTime;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void access() {
|
||||
this.lastAccessedTime = System.currentTimeMillis();
|
||||
this.isNew = false;
|
||||
}
|
||||
|
||||
public long getLastAccessedTime() {
|
||||
return this.lastAccessedTime;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
public void setMaxInactiveInterval(int interval) {
|
||||
this.maxInactiveInterval = interval;
|
||||
}
|
||||
|
||||
public int getMaxInactiveInterval() {
|
||||
return this.maxInactiveInterval;
|
||||
}
|
||||
|
||||
public HttpSessionContext getSessionContext() {
|
||||
throw new UnsupportedOperationException("getSessionContext");
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Object getValue(String name) {
|
||||
return getAttribute(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return Collections.enumeration(this.attributes.keySet());
|
||||
}
|
||||
|
||||
public String[] getValueNames() {
|
||||
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
else {
|
||||
removeAttribute(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void putValue(String name, Object value) {
|
||||
setAttribute(name, value);
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
Object value = this.attributes.remove(name);
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
|
||||
public void removeValue(String name) {
|
||||
removeAttribute(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all of this session's attributes.
|
||||
*/
|
||||
public void clearAttributes() {
|
||||
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
|
||||
Map.Entry<String, Object> entry = it.next();
|
||||
String name = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
it.remove();
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void invalidate() {
|
||||
this.invalid = true;
|
||||
clearAttributes();
|
||||
}
|
||||
|
||||
public boolean isInvalid() {
|
||||
return this.invalid;
|
||||
}
|
||||
|
||||
public void setNew(boolean value) {
|
||||
this.isNew = value;
|
||||
}
|
||||
|
||||
public boolean isNew() {
|
||||
return this.isNew;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Serialize the attributes of this session into an object that can
|
||||
* be turned into a byte array with standard Java serialization.
|
||||
* @return a representation of this session's serialized state
|
||||
*/
|
||||
public Serializable serializeState() {
|
||||
HashMap<String, Serializable> state = new HashMap<String, Serializable>();
|
||||
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
|
||||
Map.Entry<String, Object> entry = it.next();
|
||||
String name = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
it.remove();
|
||||
if (value instanceof Serializable) {
|
||||
state.put(name, (Serializable) value);
|
||||
}
|
||||
else {
|
||||
// Not serializable... Servlet containers usually automatically
|
||||
// unbind the attribute in this case.
|
||||
if (value instanceof HttpSessionBindingListener) {
|
||||
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize the attributes of this session from a state object
|
||||
* created by {@link #serializeState()}.
|
||||
* @param state a representation of this session's serialized state
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void deserializeState(Serializable state) {
|
||||
Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
|
||||
this.attributes.putAll((Map<String, Object>) state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.Writer;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.jsp.JspWriter;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.jsp.JspWriter} class.
|
||||
*
|
||||
* <p>Used for testing the web framework; only necessary for testing
|
||||
* applications when testing custom JSP tags.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.5
|
||||
*/
|
||||
public class MockJspWriter extends JspWriter {
|
||||
|
||||
private final HttpServletResponse response;
|
||||
|
||||
private PrintWriter targetWriter;
|
||||
|
||||
|
||||
/**
|
||||
* Create a MockJspWriter for the given response,
|
||||
* using the response's default Writer.
|
||||
* @param response the servlet response to wrap
|
||||
*/
|
||||
public MockJspWriter(HttpServletResponse response) {
|
||||
this(response, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a MockJspWriter for the given plain Writer.
|
||||
* @param targetWriter the target Writer to wrap
|
||||
*/
|
||||
public MockJspWriter(Writer targetWriter) {
|
||||
this(null, targetWriter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a MockJspWriter for the given response.
|
||||
* @param response the servlet response to wrap
|
||||
* @param targetWriter the target Writer to wrap
|
||||
*/
|
||||
public MockJspWriter(HttpServletResponse response, Writer targetWriter) {
|
||||
super(DEFAULT_BUFFER, true);
|
||||
this.response = (response != null ? response : new MockHttpServletResponse());
|
||||
if (targetWriter instanceof PrintWriter) {
|
||||
this.targetWriter = (PrintWriter) targetWriter;
|
||||
}
|
||||
else if (targetWriter != null) {
|
||||
this.targetWriter = new PrintWriter(targetWriter);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazily initialize the target Writer.
|
||||
*/
|
||||
protected PrintWriter getTargetWriter() throws IOException {
|
||||
if (this.targetWriter == null) {
|
||||
this.targetWriter = this.response.getWriter();
|
||||
}
|
||||
return this.targetWriter;
|
||||
}
|
||||
|
||||
|
||||
public void clear() throws IOException {
|
||||
if (this.response.isCommitted()) {
|
||||
throw new IOException("Response already committed");
|
||||
}
|
||||
this.response.resetBuffer();
|
||||
}
|
||||
|
||||
public void clearBuffer() throws IOException {
|
||||
}
|
||||
|
||||
public void flush() throws IOException {
|
||||
this.response.flushBuffer();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
flush();
|
||||
}
|
||||
|
||||
public int getRemaining() {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
|
||||
public void newLine() throws IOException {
|
||||
getTargetWriter().println();
|
||||
}
|
||||
|
||||
public void write(char value[], int offset, int length) throws IOException {
|
||||
getTargetWriter().write(value, offset, length);
|
||||
}
|
||||
|
||||
public void print(boolean value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(char value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(char[] value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(double value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(float value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(int value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(long value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(Object value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void print(String value) throws IOException {
|
||||
getTargetWriter().print(value);
|
||||
}
|
||||
|
||||
public void println() throws IOException {
|
||||
getTargetWriter().println();
|
||||
}
|
||||
|
||||
public void println(boolean value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(char value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(char[] value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(double value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(float value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(int value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(long value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(Object value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
public void println(String value) throws IOException {
|
||||
getTargetWriter().println(value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link org.springframework.web.multipart.MultipartFile}
|
||||
* interface.
|
||||
*
|
||||
* <p>Useful in conjunction with a {@link MockMultipartHttpServletRequest}
|
||||
* for testing application controllers that access multipart uploads.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Eric Crampton
|
||||
* @since 2.0
|
||||
* @see MockMultipartHttpServletRequest
|
||||
*/
|
||||
public class MockMultipartFile implements MultipartFile {
|
||||
|
||||
private final String name;
|
||||
|
||||
private String originalFilename;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private final byte[] content;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockMultipartFile with the given content.
|
||||
* @param name the name of the file
|
||||
* @param content the content of the file
|
||||
*/
|
||||
public MockMultipartFile(String name, byte[] content) {
|
||||
this(name, "", null, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockMultipartFile with the given content.
|
||||
* @param name the name of the file
|
||||
* @param contentStream the content of the file as stream
|
||||
* @throws IOException if reading from the stream failed
|
||||
*/
|
||||
public MockMultipartFile(String name, InputStream contentStream) throws IOException {
|
||||
this(name, "", null, FileCopyUtils.copyToByteArray(contentStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockMultipartFile with the given content.
|
||||
* @param name the name of the file
|
||||
* @param originalFilename the original filename (as on the client's machine)
|
||||
* @param contentType the content type (if known)
|
||||
* @param content the content of the file
|
||||
*/
|
||||
public MockMultipartFile(String name, String originalFilename, String contentType, byte[] content) {
|
||||
Assert.hasLength(name, "Name must not be null");
|
||||
this.name = name;
|
||||
this.originalFilename = (originalFilename != null ? originalFilename : "");
|
||||
this.contentType = contentType;
|
||||
this.content = (content != null ? content : new byte[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockMultipartFile with the given content.
|
||||
* @param name the name of the file
|
||||
* @param originalFilename the original filename (as on the client's machine)
|
||||
* @param contentType the content type (if known)
|
||||
* @param contentStream the content of the file as stream
|
||||
* @throws IOException if reading from the stream failed
|
||||
*/
|
||||
public MockMultipartFile(String name, String originalFilename, String contentType, InputStream contentStream)
|
||||
throws IOException {
|
||||
|
||||
this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public String getOriginalFilename() {
|
||||
return this.originalFilename;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return (this.content.length == 0);
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
return this.content.length;
|
||||
}
|
||||
|
||||
public byte[] getBytes() throws IOException {
|
||||
return this.content;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(this.content);
|
||||
}
|
||||
|
||||
public void transferTo(File dest) throws IOException, IllegalStateException {
|
||||
FileCopyUtils.copy(this.content, dest);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
|
||||
/**
|
||||
* Mock implementation of the
|
||||
* {@link org.springframework.web.multipart.MultipartHttpServletRequest} interface.
|
||||
*
|
||||
* <p>Useful for testing application controllers that access multipart uploads.
|
||||
* The {@link MockMultipartFile} can be used to populate these mock requests
|
||||
* with files.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Eric Crampton
|
||||
* @author Arjen Poutsma
|
||||
* @since 2.0
|
||||
* @see MockMultipartFile
|
||||
*/
|
||||
public class MockMultipartHttpServletRequest extends MockHttpServletRequest implements MultipartHttpServletRequest {
|
||||
|
||||
private final MultiValueMap<String, MultipartFile> multipartFiles =
|
||||
new LinkedMultiValueMap<String, MultipartFile>();
|
||||
|
||||
|
||||
public MockMultipartHttpServletRequest() {
|
||||
setMethod("POST");
|
||||
setContentType("multipart/form-data");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add a file to this request. The parameter name from the multipart
|
||||
* form is taken from the {@link MultipartFile#getName()}.
|
||||
* @param file multipart file to be added
|
||||
*/
|
||||
public void addFile(MultipartFile file) {
|
||||
Assert.notNull(file, "MultipartFile must not be null");
|
||||
this.multipartFiles.add(file.getName(), file);
|
||||
}
|
||||
|
||||
public Iterator<String> getFileNames() {
|
||||
return this.multipartFiles.keySet().iterator();
|
||||
}
|
||||
|
||||
public MultipartFile getFile(String name) {
|
||||
return this.multipartFiles.getFirst(name);
|
||||
}
|
||||
|
||||
public List<MultipartFile> getFiles(String name) {
|
||||
List<MultipartFile> multipartFiles = this.multipartFiles.get(name);
|
||||
if (multipartFiles != null) {
|
||||
return multipartFiles;
|
||||
}
|
||||
else {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, MultipartFile> getFileMap() {
|
||||
return this.multipartFiles.toSingleValueMap();
|
||||
}
|
||||
|
||||
public MultiValueMap<String, MultipartFile> getMultiFileMap() {
|
||||
return new LinkedMultiValueMap<String, MultipartFile>(this.multipartFiles);
|
||||
}
|
||||
|
||||
public String getMultipartContentType(String paramOrFileName) {
|
||||
MultipartFile file = getFile(paramOrFileName);
|
||||
if (file != null) {
|
||||
return file.getContentType();
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public HttpMethod getRequestMethod() {
|
||||
return HttpMethod.valueOf(getMethod());
|
||||
}
|
||||
|
||||
public HttpHeaders getRequestHeaders() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
Enumeration<String> headerNames = getHeaderNames();
|
||||
while (headerNames.hasMoreElements()) {
|
||||
String headerName = headerNames.nextElement();
|
||||
headers.put(headerName, Collections.list(getHeaders(headerName)));
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
|
||||
String contentType = getMultipartContentType(paramOrFileName);
|
||||
if (contentType != null) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("Content-Type", contentType);
|
||||
return headers;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.el.ELContext;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
import javax.servlet.jsp.JspWriter;
|
||||
import javax.servlet.jsp.PageContext;
|
||||
import javax.servlet.jsp.el.ELException;
|
||||
import javax.servlet.jsp.el.Expression;
|
||||
import javax.servlet.jsp.el.ExpressionEvaluator;
|
||||
import javax.servlet.jsp.el.FunctionMapper;
|
||||
import javax.servlet.jsp.el.VariableResolver;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.jsp.PageContext} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; only necessary for testing
|
||||
* applications when testing custom JSP tags.
|
||||
*
|
||||
* <p>Note: Expects initialization via the constructor rather than via the
|
||||
* <code>PageContext.initialize</code> method. Does not support writing to
|
||||
* a JspWriter, request dispatching, and <code>handlePageException</code> calls.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockPageContext extends PageContext {
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final HttpServletRequest request;
|
||||
|
||||
private final HttpServletResponse response;
|
||||
|
||||
private final ServletConfig servletConfig;
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private JspWriter out;
|
||||
|
||||
|
||||
/**
|
||||
* Create new MockPageContext with a default {@link MockServletContext},
|
||||
* {@link MockHttpServletRequest}, {@link MockHttpServletResponse},
|
||||
* {@link MockServletConfig}.
|
||||
*/
|
||||
public MockPageContext() {
|
||||
this(null, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new MockPageContext with a default {@link MockHttpServletRequest},
|
||||
* {@link MockHttpServletResponse}, {@link MockServletConfig}.
|
||||
* @param servletContext the ServletContext that the JSP page runs in
|
||||
* (only necessary when actually accessing the ServletContext)
|
||||
*/
|
||||
public MockPageContext(ServletContext servletContext) {
|
||||
this(servletContext, null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new MockPageContext with a MockHttpServletResponse,
|
||||
* MockServletConfig.
|
||||
* @param servletContext the ServletContext that the JSP page runs in
|
||||
* @param request the current HttpServletRequest
|
||||
* (only necessary when actually accessing the request)
|
||||
*/
|
||||
public MockPageContext(ServletContext servletContext, HttpServletRequest request) {
|
||||
this(servletContext, request, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new MockPageContext with a MockServletConfig.
|
||||
* @param servletContext the ServletContext that the JSP page runs in
|
||||
* @param request the current HttpServletRequest
|
||||
* @param response the current HttpServletResponse
|
||||
* (only necessary when actually writing to the response)
|
||||
*/
|
||||
public MockPageContext(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) {
|
||||
this(servletContext, request, response, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new MockServletConfig.
|
||||
* @param servletContext the ServletContext that the JSP page runs in
|
||||
* @param request the current HttpServletRequest
|
||||
* @param response the current HttpServletResponse
|
||||
* @param servletConfig the ServletConfig (hardly ever accessed from within a tag)
|
||||
*/
|
||||
public MockPageContext(ServletContext servletContext, HttpServletRequest request,
|
||||
HttpServletResponse response, ServletConfig servletConfig) {
|
||||
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.request = (request != null ? request : new MockHttpServletRequest(servletContext));
|
||||
this.response = (response != null ? response : new MockHttpServletResponse());
|
||||
this.servletConfig = (servletConfig != null ? servletConfig : new MockServletConfig(servletContext));
|
||||
}
|
||||
|
||||
|
||||
public void initialize(
|
||||
Servlet servlet, ServletRequest request, ServletResponse response,
|
||||
String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) {
|
||||
|
||||
throw new UnsupportedOperationException("Use appropriate constructor");
|
||||
}
|
||||
|
||||
public void release() {
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
else {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value, int scope) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
switch (scope) {
|
||||
case PAGE_SCOPE:
|
||||
setAttribute(name, value);
|
||||
break;
|
||||
case REQUEST_SCOPE:
|
||||
this.request.setAttribute(name, value);
|
||||
break;
|
||||
case SESSION_SCOPE:
|
||||
this.request.getSession().setAttribute(name, value);
|
||||
break;
|
||||
case APPLICATION_SCOPE:
|
||||
this.servletContext.setAttribute(name, value);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid scope: " + scope);
|
||||
}
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Object getAttribute(String name, int scope) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
switch (scope) {
|
||||
case PAGE_SCOPE:
|
||||
return getAttribute(name);
|
||||
case REQUEST_SCOPE:
|
||||
return this.request.getAttribute(name);
|
||||
case SESSION_SCOPE:
|
||||
HttpSession session = this.request.getSession(false);
|
||||
return (session != null ? session.getAttribute(name) : null);
|
||||
case APPLICATION_SCOPE:
|
||||
return this.servletContext.getAttribute(name);
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid scope: " + scope);
|
||||
}
|
||||
}
|
||||
|
||||
public Object findAttribute(String name) {
|
||||
Object value = getAttribute(name);
|
||||
if (value == null) {
|
||||
value = getAttribute(name, REQUEST_SCOPE);
|
||||
if (value == null) {
|
||||
value = getAttribute(name, SESSION_SCOPE);
|
||||
if (value == null) {
|
||||
value = getAttribute(name, APPLICATION_SCOPE);
|
||||
}
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
this.removeAttribute(name, PageContext.PAGE_SCOPE);
|
||||
this.removeAttribute(name, PageContext.REQUEST_SCOPE);
|
||||
this.removeAttribute(name, PageContext.SESSION_SCOPE);
|
||||
this.removeAttribute(name, PageContext.APPLICATION_SCOPE);
|
||||
}
|
||||
|
||||
public void removeAttribute(String name, int scope) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
switch (scope) {
|
||||
case PAGE_SCOPE:
|
||||
this.attributes.remove(name);
|
||||
break;
|
||||
case REQUEST_SCOPE:
|
||||
this.request.removeAttribute(name);
|
||||
break;
|
||||
case SESSION_SCOPE:
|
||||
this.request.getSession().removeAttribute(name);
|
||||
break;
|
||||
case APPLICATION_SCOPE:
|
||||
this.servletContext.removeAttribute(name);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid scope: " + scope);
|
||||
}
|
||||
}
|
||||
|
||||
public int getAttributesScope(String name) {
|
||||
if (getAttribute(name) != null) {
|
||||
return PAGE_SCOPE;
|
||||
}
|
||||
else if (getAttribute(name, REQUEST_SCOPE) != null) {
|
||||
return REQUEST_SCOPE;
|
||||
}
|
||||
else if (getAttribute(name, SESSION_SCOPE) != null) {
|
||||
return SESSION_SCOPE;
|
||||
}
|
||||
else if (getAttribute(name, APPLICATION_SCOPE) != null) {
|
||||
return APPLICATION_SCOPE;
|
||||
}
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return Collections.enumeration(this.attributes.keySet());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Enumeration<String> getAttributeNamesInScope(int scope) {
|
||||
switch (scope) {
|
||||
case PAGE_SCOPE:
|
||||
return getAttributeNames();
|
||||
case REQUEST_SCOPE:
|
||||
return this.request.getAttributeNames();
|
||||
case SESSION_SCOPE:
|
||||
HttpSession session = this.request.getSession(false);
|
||||
return (session != null ? session.getAttributeNames() : null);
|
||||
case APPLICATION_SCOPE:
|
||||
return this.servletContext.getAttributeNames();
|
||||
default:
|
||||
throw new IllegalArgumentException("Invalid scope: " + scope);
|
||||
}
|
||||
}
|
||||
|
||||
public JspWriter getOut() {
|
||||
if (this.out == null) {
|
||||
this.out = new MockJspWriter(this.response);
|
||||
}
|
||||
return this.out;
|
||||
}
|
||||
|
||||
public ExpressionEvaluator getExpressionEvaluator() {
|
||||
return new ExpressionEvaluator() {
|
||||
public Expression parseExpression(String expression, Class expectedType, FunctionMapper fMapper) throws ELException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
public Object evaluate(String expression, Class expectedType, VariableResolver vResolver, FunctionMapper fMapper) throws ELException {
|
||||
String key = expression.substring(2, expression.length() - 1);
|
||||
return findAttribute(key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public ELContext getELContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public VariableResolver getVariableResolver() {
|
||||
return new VariableResolver() {
|
||||
public Object resolveVariable(String pName) throws ELException {
|
||||
if (pName.equals("pageContext")) {
|
||||
return this;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public HttpSession getSession() {
|
||||
return this.request.getSession();
|
||||
}
|
||||
|
||||
public Object getPage() {
|
||||
return this;
|
||||
}
|
||||
|
||||
public ServletRequest getRequest() {
|
||||
return this.request;
|
||||
}
|
||||
|
||||
public ServletResponse getResponse() {
|
||||
return this.response;
|
||||
}
|
||||
|
||||
public Exception getException() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public ServletConfig getServletConfig() {
|
||||
return this.servletConfig;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
public void forward(String path) throws ServletException, IOException {
|
||||
this.request.getRequestDispatcher(path).forward(this.request, this.response);
|
||||
}
|
||||
|
||||
public void include(String path) throws ServletException, IOException {
|
||||
this.request.getRequestDispatcher(path).include(this.request, this.response);
|
||||
}
|
||||
|
||||
public void include(String path, boolean flush) throws ServletException, IOException {
|
||||
this.request.getRequestDispatcher(path).include(this.request, this.response);
|
||||
if (flush) {
|
||||
this.response.flushBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] getContentAsByteArray() {
|
||||
Assert.isTrue(this.response instanceof MockHttpServletResponse);
|
||||
return ((MockHttpServletResponse) this.response).getContentAsByteArray();
|
||||
}
|
||||
|
||||
public String getContentAsString() throws UnsupportedEncodingException {
|
||||
Assert.isTrue(this.response instanceof MockHttpServletResponse);
|
||||
return ((MockHttpServletResponse) this.response).getContentAsString();
|
||||
}
|
||||
|
||||
public void handlePageException(Exception ex) throws ServletException, IOException {
|
||||
throw new ServletException("Page exception", ex);
|
||||
}
|
||||
|
||||
public void handlePageException(Throwable ex) throws ServletException, IOException {
|
||||
throw new ServletException("Page exception", ex);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
import javax.servlet.http.Part;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link Part} interface.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @since 3.1
|
||||
* @see MockHttpServletRequest
|
||||
*/
|
||||
public class MockPart implements Part {
|
||||
|
||||
private static final String CONTENT_TYPE = "Content-Type";
|
||||
|
||||
private final String name;
|
||||
|
||||
private String contentType;
|
||||
|
||||
private final byte[] content;
|
||||
|
||||
/**
|
||||
* Create a new MockPart with the given content.
|
||||
* @param name the name of the part
|
||||
* @param content the content for the part
|
||||
*/
|
||||
public MockPart(String name, byte[] content) {
|
||||
this(name, "", content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockPart with the given content.
|
||||
* @param name the name of the part
|
||||
* @param contentStream the content of the part as stream
|
||||
* @throws IOException if reading from the stream failed
|
||||
*/
|
||||
public MockPart(String name, InputStream contentStream) throws IOException {
|
||||
this(name, "", FileCopyUtils.copyToByteArray(contentStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockPart with the given content.
|
||||
* @param name the name of the file
|
||||
* @param contentType the content type (if known)
|
||||
* @param content the content of the file
|
||||
*/
|
||||
public MockPart(String name, String contentType, byte[] content) {
|
||||
Assert.hasLength(name, "Name must not be null");
|
||||
this.name = name;
|
||||
this.contentType = contentType;
|
||||
this.content = (content != null ? content : new byte[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockPart with the given content.
|
||||
* @param name the name of the file
|
||||
* @param contentType the content type (if known)
|
||||
* @param contentStream the content of the part as stream
|
||||
* @throws IOException if reading from the stream failed
|
||||
*/
|
||||
public MockPart(String name, String contentType, InputStream contentStream)
|
||||
throws IOException {
|
||||
|
||||
this(name, contentType, FileCopyUtils.copyToByteArray(contentStream));
|
||||
}
|
||||
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public String getContentType() {
|
||||
return this.contentType;
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
return this.content.length;
|
||||
}
|
||||
|
||||
public InputStream getInputStream() throws IOException {
|
||||
return new ByteArrayInputStream(this.content);
|
||||
}
|
||||
|
||||
public String getHeader(String name) {
|
||||
if (CONTENT_TYPE.equalsIgnoreCase(name)) {
|
||||
return this.contentType;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getHeaders(String name) {
|
||||
if (CONTENT_TYPE.equalsIgnoreCase(name)) {
|
||||
return Collections.singleton(this.contentType);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<String> getHeaderNames() {
|
||||
return Collections.singleton(CONTENT_TYPE);
|
||||
}
|
||||
|
||||
public void write(String fileName) throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void delete() throws IOException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.mock.web;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletResponseWrapper;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.RequestDispatcher} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; typically not necessary for
|
||||
* testing application controllers.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockRequestDispatcher implements RequestDispatcher {
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final String url;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockRequestDispatcher for the given URL.
|
||||
* @param url the URL to dispatch to.
|
||||
*/
|
||||
public MockRequestDispatcher(String url) {
|
||||
Assert.notNull(url, "URL must not be null");
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
|
||||
public void forward(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
if (response.isCommitted()) {
|
||||
throw new IllegalStateException("Cannot perform forward - response is already committed");
|
||||
}
|
||||
getMockHttpServletResponse(response).setForwardedUrl(this.url);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
|
||||
}
|
||||
}
|
||||
|
||||
public void include(ServletRequest request, ServletResponse response) {
|
||||
Assert.notNull(request, "Request must not be null");
|
||||
Assert.notNull(response, "Response must not be null");
|
||||
getMockHttpServletResponse(response).addIncludedUrl(this.url);
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the underlying MockHttpServletResponse,
|
||||
* unwrapping {@link HttpServletResponseWrapper} decorators if necessary.
|
||||
*/
|
||||
protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
|
||||
if (response instanceof MockHttpServletResponse) {
|
||||
return (MockHttpServletResponse) response;
|
||||
}
|
||||
if (response instanceof HttpServletResponseWrapper) {
|
||||
return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
|
||||
}
|
||||
throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.ServletConfig} interface.
|
||||
*
|
||||
* <p>Used for testing the web framework; typically not necessary for
|
||||
* testing application controllers.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
*/
|
||||
public class MockServletConfig implements ServletConfig {
|
||||
|
||||
private final ServletContext servletContext;
|
||||
|
||||
private final String servletName;
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig with a default {@link MockServletContext}.
|
||||
*/
|
||||
public MockServletConfig() {
|
||||
this(null, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig with a default {@link MockServletContext}.
|
||||
* @param servletName the name of the servlet
|
||||
*/
|
||||
public MockServletConfig(String servletName) {
|
||||
this(null, servletName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
*/
|
||||
public MockServletConfig(ServletContext servletContext) {
|
||||
this(servletContext, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletConfig.
|
||||
* @param servletContext the ServletContext that the servlet runs in
|
||||
* @param servletName the name of the servlet
|
||||
*/
|
||||
public MockServletConfig(ServletContext servletContext, String servletName) {
|
||||
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
|
||||
this.servletName = servletName;
|
||||
}
|
||||
|
||||
|
||||
public String getServletName() {
|
||||
return this.servletName;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return this.servletContext;
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.mock.web;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import java.util.EventListener;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import javax.activation.FileTypeMap;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterRegistration;
|
||||
import javax.servlet.FilterRegistration.Dynamic;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
import javax.servlet.SessionCookieConfig;
|
||||
import javax.servlet.SessionTrackingMode;
|
||||
import javax.servlet.descriptor.JspConfigDescriptor;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.core.io.DefaultResourceLoader;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* Mock implementation of the {@link javax.servlet.ServletContext} interface.
|
||||
*
|
||||
* <p>Used for testing the Spring web framework; only rarely necessary for testing
|
||||
* application controllers. As long as application components don't explicitly
|
||||
* access the ServletContext, ClassPathXmlApplicationContext or
|
||||
* FileSystemXmlApplicationContext can be used to load the context files for testing,
|
||||
* even for DispatcherServlet context definitions.
|
||||
*
|
||||
* <p>For setting up a full WebApplicationContext in a test environment, you can
|
||||
* use XmlWebApplicationContext (or GenericWebApplicationContext), passing in an
|
||||
* appropriate MockServletContext instance. You might want to configure your
|
||||
* MockServletContext with a FileSystemResourceLoader in that case, to make your
|
||||
* resource paths interpreted as relative file system locations.
|
||||
*
|
||||
* <p>A common setup is to point your JVM working directory to the root of your
|
||||
* web application directory, in combination with filesystem-based resource loading.
|
||||
* This allows to load the context files as used in the web application, with
|
||||
* relative paths getting interpreted correctly. Such a setup will work with both
|
||||
* FileSystemXmlApplicationContext (which will load straight from the file system)
|
||||
* and XmlWebApplicationContext with an underlying MockServletContext (as long as
|
||||
* the MockServletContext has been configured with a FileSystemResourceLoader).
|
||||
*
|
||||
* Supports the Servlet 3.0 API level, but throws {@link UnsupportedOperationException}
|
||||
* for all methods introduced in Servlet 3.0.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 1.0.2
|
||||
* @see #MockServletContext(org.springframework.core.io.ResourceLoader)
|
||||
* @see org.springframework.web.context.support.XmlWebApplicationContext
|
||||
* @see org.springframework.web.context.support.GenericWebApplicationContext
|
||||
* @see org.springframework.context.support.ClassPathXmlApplicationContext
|
||||
* @see org.springframework.context.support.FileSystemXmlApplicationContext
|
||||
*/
|
||||
public class MockServletContext implements ServletContext {
|
||||
|
||||
private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";
|
||||
|
||||
|
||||
private final Log logger = LogFactory.getLog(getClass());
|
||||
|
||||
private final ResourceLoader resourceLoader;
|
||||
|
||||
private final String resourceBasePath;
|
||||
|
||||
private String contextPath = "";
|
||||
|
||||
private int minorVersion = 5;
|
||||
|
||||
private final Map<String, ServletContext> contexts = new HashMap<String, ServletContext>();
|
||||
|
||||
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
|
||||
|
||||
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
|
||||
|
||||
private String servletContextName = "MockServletContext";
|
||||
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using no base path and a
|
||||
* DefaultResourceLoader (i.e. the classpath root as WAR root).
|
||||
* @see org.springframework.core.io.DefaultResourceLoader
|
||||
*/
|
||||
public MockServletContext() {
|
||||
this("", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using a DefaultResourceLoader.
|
||||
* @param resourceBasePath the WAR root directory (should not end with a slash)
|
||||
* @see org.springframework.core.io.DefaultResourceLoader
|
||||
*/
|
||||
public MockServletContext(String resourceBasePath) {
|
||||
this(resourceBasePath, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext, using the specified ResourceLoader
|
||||
* and no base path.
|
||||
* @param resourceLoader the ResourceLoader to use (or null for the default)
|
||||
*/
|
||||
public MockServletContext(ResourceLoader resourceLoader) {
|
||||
this("", resourceLoader);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new MockServletContext.
|
||||
* @param resourceBasePath the WAR root directory (should not end with a slash)
|
||||
* @param resourceLoader the ResourceLoader to use (or null for the default)
|
||||
*/
|
||||
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
|
||||
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
|
||||
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
|
||||
|
||||
// Use JVM temp dir as ServletContext temp dir.
|
||||
String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
|
||||
if (tempDir != null) {
|
||||
this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build a full resource location for the given path,
|
||||
* prepending the resource base path of this MockServletContext.
|
||||
* @param path the path as specified
|
||||
* @return the full resource path
|
||||
*/
|
||||
protected String getResourceLocation(String path) {
|
||||
if (!path.startsWith("/")) {
|
||||
path = "/" + path;
|
||||
}
|
||||
return this.resourceBasePath + path;
|
||||
}
|
||||
|
||||
|
||||
public void setContextPath(String contextPath) {
|
||||
this.contextPath = (contextPath != null ? contextPath : "");
|
||||
}
|
||||
|
||||
/* This is a Servlet API 2.5 method. */
|
||||
public String getContextPath() {
|
||||
return this.contextPath;
|
||||
}
|
||||
|
||||
public void registerContext(String contextPath, ServletContext context) {
|
||||
this.contexts.put(contextPath, context);
|
||||
}
|
||||
|
||||
public ServletContext getContext(String contextPath) {
|
||||
if (this.contextPath.equals(contextPath)) {
|
||||
return this;
|
||||
}
|
||||
return this.contexts.get(contextPath);
|
||||
}
|
||||
|
||||
public int getMajorVersion() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
public void setMinorVersion(int minorVersion) {
|
||||
if (minorVersion < 3 || minorVersion > 5) {
|
||||
throw new IllegalArgumentException("Only Servlet minor versions between 3 and 5 are supported");
|
||||
}
|
||||
this.minorVersion = minorVersion;
|
||||
}
|
||||
|
||||
public int getMinorVersion() {
|
||||
return this.minorVersion;
|
||||
}
|
||||
|
||||
public String getMimeType(String filePath) {
|
||||
return MimeTypeResolver.getMimeType(filePath);
|
||||
}
|
||||
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
String actualPath = (path.endsWith("/") ? path : path + "/");
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));
|
||||
try {
|
||||
File file = resource.getFile();
|
||||
String[] fileList = file.list();
|
||||
if (ObjectUtils.isEmpty(fileList)) {
|
||||
return null;
|
||||
}
|
||||
Set<String> resourcePaths = new LinkedHashSet<String>(fileList.length);
|
||||
for (String fileEntry : fileList) {
|
||||
String resultPath = actualPath + fileEntry;
|
||||
if (resource.createRelative(fileEntry).getFile().isDirectory()) {
|
||||
resultPath += "/";
|
||||
}
|
||||
resourcePaths.add(resultPath);
|
||||
}
|
||||
return resourcePaths;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't get resource paths for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public URL getResource(String path) throws MalformedURLException {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
if (!resource.exists()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return resource.getURL();
|
||||
}
|
||||
catch (MalformedURLException ex) {
|
||||
throw ex;
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't get URL for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public InputStream getResourceAsStream(String path) {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
if (!resource.exists()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return resource.getInputStream();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't open InputStream for " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public RequestDispatcher getRequestDispatcher(String path) {
|
||||
if (!path.startsWith("/")) {
|
||||
throw new IllegalArgumentException("RequestDispatcher path at ServletContext level must start with '/'");
|
||||
}
|
||||
return new MockRequestDispatcher(path);
|
||||
}
|
||||
|
||||
public RequestDispatcher getNamedDispatcher(String path) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Servlet getServlet(String name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Enumeration<Servlet> getServlets() {
|
||||
return Collections.enumeration(new HashSet<Servlet>());
|
||||
}
|
||||
|
||||
public Enumeration<String> getServletNames() {
|
||||
return Collections.enumeration(new HashSet<String>());
|
||||
}
|
||||
|
||||
public void log(String message) {
|
||||
logger.info(message);
|
||||
}
|
||||
|
||||
public void log(Exception ex, String message) {
|
||||
logger.info(message, ex);
|
||||
}
|
||||
|
||||
public void log(String message, Throwable ex) {
|
||||
logger.info(message, ex);
|
||||
}
|
||||
|
||||
public String getRealPath(String path) {
|
||||
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
|
||||
try {
|
||||
return resource.getFile().getAbsolutePath();
|
||||
}
|
||||
catch (IOException ex) {
|
||||
logger.warn("Couldn't determine real path of resource " + resource, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String getServerInfo() {
|
||||
return "MockServletContext";
|
||||
}
|
||||
|
||||
public String getInitParameter(String name) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
return this.initParameters.get(name);
|
||||
}
|
||||
|
||||
public void addInitParameter(String name, String value) {
|
||||
Assert.notNull(name, "Parameter name must not be null");
|
||||
this.initParameters.put(name, value);
|
||||
}
|
||||
|
||||
public Enumeration<String> getInitParameterNames() {
|
||||
return Collections.enumeration(this.initParameters.keySet());
|
||||
}
|
||||
|
||||
public Object getAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
return this.attributes.get(name);
|
||||
}
|
||||
|
||||
public Enumeration<String> getAttributeNames() {
|
||||
return Collections.enumeration(this.attributes.keySet());
|
||||
}
|
||||
|
||||
public void setAttribute(String name, Object value) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
if (value != null) {
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
else {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String name) {
|
||||
Assert.notNull(name, "Attribute name must not be null");
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
|
||||
public void setServletContextName(String servletContextName) {
|
||||
this.servletContextName = servletContextName;
|
||||
}
|
||||
|
||||
public String getServletContextName() {
|
||||
return this.servletContextName;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Inner factory class used to just introduce a Java Activation Framework
|
||||
* dependency when actually asked to resolve a MIME type.
|
||||
*/
|
||||
private static class MimeTypeResolver {
|
||||
|
||||
public static String getMimeType(String filePath) {
|
||||
return FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//---------------------------------------------------------------------
|
||||
// Methods introduced in Servlet 3.0
|
||||
//---------------------------------------------------------------------
|
||||
|
||||
public Dynamic addFilter(String arg0, String arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Dynamic addFilter(String arg0, Filter arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Dynamic addFilter(String arg0, Class<? extends Filter> arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void addListener(Class<? extends EventListener> arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void addListener(String arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public <T extends EventListener> void addListener(T arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, String arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0,
|
||||
Servlet arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0,
|
||||
Class<? extends Servlet> arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public <T extends Filter> T createFilter(Class<T> arg0)
|
||||
throws ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public <T extends EventListener> T createListener(Class<T> arg0)
|
||||
throws ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public <T extends Servlet> T createServlet(Class<T> arg0)
|
||||
throws ServletException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void declareRoles(String... arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public ClassLoader getClassLoader() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getEffectiveMajorVersion() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public int getEffectiveMinorVersion() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public FilterRegistration getFilterRegistration(String arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public JspConfigDescriptor getJspConfigDescriptor() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public ServletRegistration getServletRegistration(String arg0) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public SessionCookieConfig getSessionCookieConfig() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public boolean setInitParameter(String arg0, String arg1) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
public void setSessionTrackingModes(Set<SessionTrackingMode> arg0)
|
||||
throws IllegalStateException, IllegalArgumentException {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Implementation of the {@link javax.servlet.FilterConfig} interface which
|
||||
* simply passes the call through to a given Filter/FilterChain combo
|
||||
* (indicating the next Filter in the chain along with the FilterChain that it is
|
||||
* supposed to work on) or to a given Servlet (indicating the end of the chain).
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 2.0.3
|
||||
* @see javax.servlet.Filter
|
||||
* @see javax.servlet.Servlet
|
||||
* @see MockFilterChain
|
||||
*/
|
||||
public class PassThroughFilterChain implements FilterChain {
|
||||
|
||||
private Filter filter;
|
||||
|
||||
private FilterChain nextFilterChain;
|
||||
|
||||
private Servlet servlet;
|
||||
|
||||
|
||||
/**
|
||||
* Create a new PassThroughFilterChain that delegates to the given Filter,
|
||||
* calling it with the given FilterChain.
|
||||
* @param filter the Filter to delegate to
|
||||
* @param nextFilterChain the FilterChain to use for that next Filter
|
||||
*/
|
||||
public PassThroughFilterChain(Filter filter, FilterChain nextFilterChain) {
|
||||
Assert.notNull(filter, "Filter must not be null");
|
||||
Assert.notNull(nextFilterChain, "'FilterChain must not be null");
|
||||
this.filter = filter;
|
||||
this.nextFilterChain = nextFilterChain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new PassThroughFilterChain that delegates to the given Servlet.
|
||||
* @param servlet the Servlet to delegate to
|
||||
*/
|
||||
public PassThroughFilterChain(Servlet servlet) {
|
||||
Assert.notNull(servlet, "Servlet must not be null");
|
||||
this.servlet = servlet;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Pass the call on to the Filter/Servlet.
|
||||
*/
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException {
|
||||
if (this.filter != null) {
|
||||
this.filter.doFilter(request, response, this.nextFilterChain);
|
||||
}
|
||||
else {
|
||||
this.servlet.service(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.ui.jasperreports;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class PersonBean {
|
||||
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String street;
|
||||
|
||||
private String city;
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.ui.jasperreports;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class ProductBean {
|
||||
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
|
||||
private float quantity;
|
||||
|
||||
private float price;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public float getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(float quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public float getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(float price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.NotSerializableException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.OutputStream;
|
||||
|
||||
/**
|
||||
* Utilities for testing serializability of objects.
|
||||
* Exposes static methods for use in other test cases.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
*/
|
||||
public class SerializationTestUtils {
|
||||
|
||||
public static void testSerialization(Object o) throws IOException {
|
||||
OutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(o);
|
||||
}
|
||||
|
||||
public static boolean isSerializable(Object o) throws IOException {
|
||||
try {
|
||||
testSerialization(o);
|
||||
return true;
|
||||
}
|
||||
catch (NotSerializableException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(o);
|
||||
oos.flush();
|
||||
baos.flush();
|
||||
byte[] bytes = baos.toByteArray();
|
||||
|
||||
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(is);
|
||||
Object o2 = ois.readObject();
|
||||
return o2;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package org.springframework.web.context;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.LifecycleBean;
|
||||
import org.springframework.context.ACATester;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.BeanThatListens;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.context.TestListener;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests {
|
||||
|
||||
/** Must be supplied as XML */
|
||||
public static final String TEST_NAMESPACE = "testNamespace";
|
||||
|
||||
protected ConfigurableApplicationContext applicationContext;
|
||||
|
||||
/** Subclass must register this */
|
||||
protected TestListener listener = new TestListener();
|
||||
|
||||
protected TestListener parentListener = new TestListener();
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
this.applicationContext = createContext();
|
||||
}
|
||||
|
||||
protected BeanFactory getBeanFactory() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
protected ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must register a TestListener.
|
||||
* Must register standard beans.
|
||||
* Parent must register rod with name Roderick
|
||||
* and father with name Albert.
|
||||
*/
|
||||
protected abstract ConfigurableApplicationContext createContext() throws Exception;
|
||||
|
||||
public void testContextAwareSingletonWasCalledBack() throws Exception {
|
||||
ACATester aca = (ACATester) applicationContext.getBean("aca");
|
||||
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
|
||||
Object aca2 = applicationContext.getBean("aca");
|
||||
assertTrue("Same instance", aca == aca2);
|
||||
assertTrue("Says is singleton", applicationContext.isSingleton("aca"));
|
||||
}
|
||||
|
||||
public void testContextAwarePrototypeWasCalledBack() throws Exception {
|
||||
ACATester aca = (ACATester) applicationContext.getBean("aca-prototype");
|
||||
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
|
||||
Object aca2 = applicationContext.getBean("aca-prototype");
|
||||
assertTrue("NOT Same instance", aca != aca2);
|
||||
assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype"));
|
||||
}
|
||||
|
||||
public void testParentNonNull() {
|
||||
assertTrue("parent isn't null", applicationContext.getParent() != null);
|
||||
}
|
||||
|
||||
public void testGrandparentNull() {
|
||||
assertTrue("grandparent is null", applicationContext.getParent().getParent() == null);
|
||||
}
|
||||
|
||||
public void testOverrideWorked() throws Exception {
|
||||
TestBean rod = (TestBean) applicationContext.getParent().getBean("rod");
|
||||
assertTrue("Parent's name differs", rod.getName().equals("Roderick"));
|
||||
}
|
||||
|
||||
public void testGrandparentDefinitionFound() throws Exception {
|
||||
TestBean dad = (TestBean) applicationContext.getBean("father");
|
||||
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
|
||||
}
|
||||
|
||||
public void testGrandparentTypedDefinitionFound() throws Exception {
|
||||
TestBean dad = (TestBean) applicationContext.getBean("father", TestBean.class);
|
||||
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
|
||||
}
|
||||
|
||||
public void testCloseTriggersDestroy() {
|
||||
LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle");
|
||||
assertTrue("Not destroyed", !lb.isDestroyed());
|
||||
applicationContext.close();
|
||||
if (applicationContext.getParent() != null) {
|
||||
((ConfigurableApplicationContext) applicationContext.getParent()).close();
|
||||
}
|
||||
assertTrue("Destroyed", lb.isDestroyed());
|
||||
applicationContext.close();
|
||||
if (applicationContext.getParent() != null) {
|
||||
((ConfigurableApplicationContext) applicationContext.getParent()).close();
|
||||
}
|
||||
assertTrue("Destroyed", lb.isDestroyed());
|
||||
}
|
||||
|
||||
public void testMessageSource() throws NoSuchMessageException {
|
||||
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
|
||||
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
|
||||
|
||||
try {
|
||||
applicationContext.getMessage("code0", null, Locale.getDefault());
|
||||
fail("looking for code0 should throw a NoSuchMessageException");
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// that's how it should be
|
||||
}
|
||||
}
|
||||
|
||||
public void testEvents() throws Exception {
|
||||
listener.zeroCounter();
|
||||
parentListener.zeroCounter();
|
||||
assertTrue("0 events before publication", listener.getEventCount() == 0);
|
||||
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
|
||||
this.applicationContext.publishEvent(new MyEvent(this));
|
||||
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
|
||||
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
|
||||
}
|
||||
|
||||
public void testBeanAutomaticallyHearsEvents() throws Exception {
|
||||
//String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class);
|
||||
//assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens"));
|
||||
BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens");
|
||||
b.zero();
|
||||
assertTrue("0 events before publication", b.getEventCount() == 0);
|
||||
this.applicationContext.publishEvent(new MyEvent(this));
|
||||
assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1);
|
||||
}
|
||||
|
||||
|
||||
public static class MyEvent extends ApplicationEvent {
|
||||
|
||||
public MyEvent(Object source) {
|
||||
super(source);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/*
|
||||
* Copyright 2002-2009 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.web.context;
|
||||
|
||||
import java.beans.PropertyEditorSupport;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.PropertyBatchUpdateException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanIsNotAFactoryException;
|
||||
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
|
||||
import org.springframework.beans.factory.DummyFactory;
|
||||
import org.springframework.beans.factory.LifecycleBean;
|
||||
import org.springframework.beans.factory.MustBeInitialized;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
|
||||
|
||||
/**
|
||||
* Subclasses must implement setUp() to initialize bean factory
|
||||
* and any other variables they need.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public abstract class AbstractBeanFactoryTests extends TestCase {
|
||||
|
||||
protected abstract BeanFactory getBeanFactory();
|
||||
|
||||
/**
|
||||
* Roderick beans inherits from rod, overriding name only.
|
||||
*/
|
||||
public void testInheritance() {
|
||||
assertTrue(getBeanFactory().containsBean("rod"));
|
||||
assertTrue(getBeanFactory().containsBean("roderick"));
|
||||
TestBean rod = (TestBean) getBeanFactory().getBean("rod");
|
||||
TestBean roderick = (TestBean) getBeanFactory().getBean("roderick");
|
||||
assertTrue("not == ", rod != roderick);
|
||||
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
|
||||
assertTrue("rod.age is 31", rod.getAge() == 31);
|
||||
assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick"));
|
||||
assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
|
||||
}
|
||||
|
||||
public void testGetBeanWithNullArg() {
|
||||
try {
|
||||
getBeanFactory().getBean((String) null);
|
||||
fail("Can't get null bean");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that InitializingBean objects receive the afterPropertiesSet() callback
|
||||
*/
|
||||
public void testInitializingBeanCallback() {
|
||||
MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
|
||||
// The dummy business method will throw an exception if the
|
||||
// afterPropertiesSet() callback wasn't invoked
|
||||
mbi.businessMethod();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
|
||||
* afterPropertiesSet() callback before BeanFactoryAware callbacks
|
||||
*/
|
||||
public void testLifecycleCallbacks() {
|
||||
LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
|
||||
Assert.assertEquals("lifecycle", lb.getBeanName());
|
||||
// The dummy business method will throw an exception if the
|
||||
// necessary callbacks weren't invoked in the right order.
|
||||
lb.businessMethod();
|
||||
assertTrue("Not destroyed", !lb.isDestroyed());
|
||||
}
|
||||
|
||||
public void testFindsValidInstance() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
TestBean rod = (TestBean) o;
|
||||
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
|
||||
assertTrue("rod.age is 31", rod.getAge() == 31);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetInstanceByMatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance with matching class");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetInstanceByNonmatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
|
||||
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
|
||||
}
|
||||
catch (BeanNotOfRequiredTypeException ex) {
|
||||
// So far, so good
|
||||
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
|
||||
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
|
||||
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
|
||||
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByMatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance with matching class");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByMatchingClassNoCatch() {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByNonmatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
|
||||
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
|
||||
}
|
||||
catch (BeanNotOfRequiredTypeException ex) {
|
||||
// So far, so good
|
||||
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
|
||||
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
|
||||
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testSharedInstancesAreEqual() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
|
||||
Object o1 = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
|
||||
assertTrue("Object equals applies", o == o1);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testPrototypeInstancesAreIndependent() {
|
||||
TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
|
||||
assertTrue("ref equal DOES NOT apply", tb1 != tb2);
|
||||
assertTrue("object equal true", tb1.equals(tb2));
|
||||
tb1.setAge(1);
|
||||
tb2.setAge(2);
|
||||
assertTrue("1 age independent = 1", tb1.getAge() == 1);
|
||||
assertTrue("2 age independent = 2", tb2.getAge() == 2);
|
||||
assertTrue("object equal now false", !tb1.equals(tb2));
|
||||
}
|
||||
|
||||
public void testNotThere() {
|
||||
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("Mr Squiggle");
|
||||
fail("Can't find missing bean");
|
||||
}
|
||||
catch (BeansException ex) {
|
||||
//ex.printStackTrace();
|
||||
//fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testValidEmpty() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("validEmpty");
|
||||
assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
|
||||
TestBean ve = (TestBean) o;
|
||||
assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
|
||||
}
|
||||
catch (BeansException ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on valid empty");
|
||||
}
|
||||
}
|
||||
|
||||
public void xtestTypeMismatch() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("typeMismatch");
|
||||
fail("Shouldn't succeed with type mismatch");
|
||||
}
|
||||
catch (BeanCreationException wex) {
|
||||
assertEquals("typeMismatch", wex.getBeanName());
|
||||
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
|
||||
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
|
||||
// Further tests
|
||||
assertTrue("Has one error ", ex.getExceptionCount() == 1);
|
||||
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
|
||||
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
|
||||
}
|
||||
}
|
||||
|
||||
public void testGrandparentDefinitionFoundInBeanFactory() throws Exception {
|
||||
TestBean dad = (TestBean) getBeanFactory().getBean("father");
|
||||
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
|
||||
}
|
||||
|
||||
public void testFactorySingleton() throws Exception {
|
||||
assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
|
||||
assertTrue(getBeanFactory().isSingleton("singletonFactory"));
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
assertTrue("Singleton references ==", tb == tb2);
|
||||
assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
|
||||
}
|
||||
|
||||
public void testFactoryPrototype() throws Exception {
|
||||
assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
|
||||
assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
|
||||
assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
|
||||
assertTrue("Prototype references !=", tb != tb2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that we can get the factory bean itself.
|
||||
* This is only possible if we're dealing with a factory
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testGetFactoryItself() throws Exception {
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
assertTrue(factory != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that afterPropertiesSet gets called on factory
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testFactoryIsInitialized() throws Exception {
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
|
||||
}
|
||||
|
||||
/**
|
||||
* It should be illegal to dereference a normal bean
|
||||
* as a factory
|
||||
*/
|
||||
public void testRejectsFactoryGetOnNormalBean() {
|
||||
try {
|
||||
getBeanFactory().getBean("&rod");
|
||||
fail("Shouldn't permit factory get on normal bean");
|
||||
}
|
||||
catch (BeanIsNotAFactoryException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
|
||||
// and rename this class
|
||||
public void testAliasing() {
|
||||
BeanFactory bf = getBeanFactory();
|
||||
if (!(bf instanceof ConfigurableBeanFactory)) {
|
||||
return;
|
||||
}
|
||||
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
|
||||
|
||||
String alias = "rods alias";
|
||||
try {
|
||||
cbf.getBean(alias);
|
||||
fail("Shouldn't permit factory get on normal bean");
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
// Ok
|
||||
assertTrue(alias.equals(ex.getBeanName()));
|
||||
}
|
||||
|
||||
// Create alias
|
||||
cbf.registerAlias("rod", alias);
|
||||
Object rod = getBeanFactory().getBean("rod");
|
||||
Object aliasRod = getBeanFactory().getBean(alias);
|
||||
assertTrue(rod == aliasRod);
|
||||
}
|
||||
|
||||
|
||||
public static class TestBeanEditor extends PropertyEditorSupport {
|
||||
|
||||
public void setAsText(String text) {
|
||||
TestBean tb = new TestBean();
|
||||
StringTokenizer st = new StringTokenizer(text, "_");
|
||||
tb.setName(st.nextToken());
|
||||
tb.setAge(Integer.parseInt(st.nextToken()));
|
||||
setValue(tb);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package org.springframework.web.context;
|
||||
|
||||
import junit.framework.Assert;
|
||||
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.FactoryBean;
|
||||
import org.springframework.beans.factory.ListableBeanFactory;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests {
|
||||
|
||||
/** Subclasses must initialize this */
|
||||
protected ListableBeanFactory getListableBeanFactory() {
|
||||
BeanFactory bf = getBeanFactory();
|
||||
if (!(bf instanceof ListableBeanFactory)) {
|
||||
throw new IllegalStateException("ListableBeanFactory required");
|
||||
}
|
||||
return (ListableBeanFactory) bf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subclasses can override this.
|
||||
*/
|
||||
public void testCount() {
|
||||
assertCount(13);
|
||||
}
|
||||
|
||||
protected final void assertCount(int count) {
|
||||
String[] defnames = getListableBeanFactory().getBeanDefinitionNames();
|
||||
Assert.assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count);
|
||||
}
|
||||
|
||||
public void assertTestBeanCount(int count) {
|
||||
String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false);
|
||||
Assert.assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " +
|
||||
defNames.length, defNames.length == count);
|
||||
|
||||
int countIncludingFactoryBeans = count + 2;
|
||||
String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true);
|
||||
Assert.assertTrue("We should have " + countIncludingFactoryBeans +
|
||||
" beans for class org.springframework.beans.TestBean, not " + names.length,
|
||||
names.length == countIncludingFactoryBeans);
|
||||
}
|
||||
|
||||
public void testGetDefinitionsForNoSuchClass() {
|
||||
String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class);
|
||||
Assert.assertTrue("No string definitions", defnames.length == 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that count refers to factory class, not bean class. (We don't know
|
||||
* what type factories may return, and it may even change over time.)
|
||||
*/
|
||||
public void testGetCountForFactoryClass() {
|
||||
Assert.assertTrue("Should have 2 factories, not " +
|
||||
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
|
||||
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
|
||||
|
||||
Assert.assertTrue("Should have 2 factories, not " +
|
||||
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
|
||||
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
|
||||
}
|
||||
|
||||
public void testContainsBeanDefinition() {
|
||||
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("rod"));
|
||||
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("roderick"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.notNullValue;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.beans.factory.BeanDefinitionStoreException;
|
||||
import org.springframework.beans.factory.LifecycleBean;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextException;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.PropertySource;
|
||||
import org.springframework.mock.web.MockServletConfig;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
import org.springframework.web.servlet.SimpleWebApplicationContext;
|
||||
|
||||
/**
|
||||
* Tests for {@link ContextLoader} and {@link ContextLoaderListener}.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Sam Brannen
|
||||
* @author Chris Beams
|
||||
* @since 12.08.2003
|
||||
* @see org.springframework.web.context.support.Spr8510Tests
|
||||
*/
|
||||
public final class ContextLoaderTests {
|
||||
|
||||
@Test
|
||||
public void testContextLoaderListenerWithDefaultContext() {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml "
|
||||
+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
listener.contextInitialized(event);
|
||||
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
|
||||
assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
|
||||
assertTrue(ContextLoader.getCurrentWebApplicationContext() instanceof XmlWebApplicationContext);
|
||||
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
|
||||
assertTrue("Has father", context.containsBean("father"));
|
||||
assertTrue("Has rod", context.containsBean("rod"));
|
||||
assertTrue("Has kerry", context.containsBean("kerry"));
|
||||
assertTrue("Not destroyed", !lb.isDestroyed());
|
||||
assertFalse(context.containsBean("beans1.bean1"));
|
||||
assertFalse(context.containsBean("beans1.bean2"));
|
||||
listener.contextDestroyed(event);
|
||||
assertTrue("Destroyed", lb.isDestroyed());
|
||||
assertNull(sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
|
||||
assertNull(ContextLoader.getCurrentWebApplicationContext());
|
||||
}
|
||||
|
||||
/**
|
||||
* Addresses the issues raised in <a
|
||||
* href="http://opensource.atlassian.com/projects/spring/browse/SPR-4008"
|
||||
* target="_blank">SPR-4008</a>: <em>Supply an opportunity to customize
|
||||
* context before calling refresh in ContextLoaders</em>.
|
||||
*/
|
||||
@Test
|
||||
public void testContextLoaderListenerWithCustomizedContextLoader() {
|
||||
final StringBuffer buffer = new StringBuffer();
|
||||
final String expectedContents = "customizeContext() was called";
|
||||
final MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml");
|
||||
final ServletContextListener listener = new ContextLoaderListener() {
|
||||
protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) {
|
||||
assertNotNull("The ServletContext should not be null.", servletContext);
|
||||
assertEquals("Verifying that we received the expected ServletContext.", sc, servletContext);
|
||||
assertFalse("The ApplicationContext should not yet have been refreshed.", applicationContext.isActive());
|
||||
buffer.append(expectedContents);
|
||||
}
|
||||
};
|
||||
listener.contextInitialized(new ServletContextEvent(sc));
|
||||
assertEquals("customizeContext() should have been called.", expectedContents, buffer.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderListenerWithRegisteredContextConfigurer() {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
|
||||
"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
|
||||
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,
|
||||
StringUtils.arrayToCommaDelimitedString(
|
||||
new Object[]{TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
|
||||
ContextLoaderListener listener = new ContextLoaderListener();
|
||||
listener.contextInitialized(new ServletContextEvent(sc));
|
||||
WebApplicationContext wac = ContextLoaderListener.getCurrentWebApplicationContext();
|
||||
TestBean testBean = wac.getBean(TestBean.class);
|
||||
assertThat(testBean.getName(), equalTo("testName"));
|
||||
assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderListenerWithUnkownContextConfigurer() {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
// config file doesn't matter. just a placeholder
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
|
||||
"/org/springframework/web/context/WEB-INF/empty-context.xml");
|
||||
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,
|
||||
StringUtils.arrayToCommaDelimitedString(new Object[]{UnknownContextInitializer.class.getName()}));
|
||||
ContextLoaderListener listener = new ContextLoaderListener();
|
||||
try {
|
||||
listener.contextInitialized(new ServletContextEvent(sc));
|
||||
fail("expected exception");
|
||||
} catch (IllegalArgumentException ex) {
|
||||
assertTrue(ex.getMessage().contains("not assignable"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderWithDefaultContextAndParent() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml "
|
||||
+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
|
||||
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM,
|
||||
"classpath:org/springframework/web/context/ref1.xml");
|
||||
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM, "a.qualified.name.of.some.sort");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
listener.contextInitialized(event);
|
||||
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
|
||||
assertTrue("Correct WebApplicationContext exposed in ServletContext",
|
||||
context instanceof XmlWebApplicationContext);
|
||||
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
|
||||
assertTrue("Has father", context.containsBean("father"));
|
||||
assertTrue("Has rod", context.containsBean("rod"));
|
||||
assertTrue("Has kerry", context.containsBean("kerry"));
|
||||
assertTrue("Not destroyed", !lb.isDestroyed());
|
||||
assertTrue(context.containsBean("beans1.bean1"));
|
||||
assertTrue(context.isTypeMatch("beans1.bean1", org.springframework.beans.factory.access.TestBean.class));
|
||||
assertTrue(context.containsBean("beans1.bean2"));
|
||||
assertTrue(context.isTypeMatch("beans1.bean2", org.springframework.beans.factory.access.TestBean.class));
|
||||
listener.contextDestroyed(event);
|
||||
assertTrue("Destroyed", lb.isDestroyed());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderWithCustomContext() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
|
||||
"org.springframework.web.servlet.SimpleWebApplicationContext");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
listener.contextInitialized(event);
|
||||
WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
|
||||
assertTrue("Correct WebApplicationContext exposed in ServletContext", wc instanceof SimpleWebApplicationContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderWithInvalidLocation() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
try {
|
||||
listener.contextInitialized(event);
|
||||
fail("Should have thrown BeanDefinitionStoreException");
|
||||
}
|
||||
catch (BeanDefinitionStoreException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof FileNotFoundException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderWithInvalidContext() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
|
||||
"org.springframework.web.context.support.InvalidWebApplicationContext");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
try {
|
||||
listener.contextInitialized(event);
|
||||
fail("Should have thrown ApplicationContextException");
|
||||
}
|
||||
catch (ApplicationContextException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof ClassNotFoundException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContextLoaderWithDefaultLocation() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
ServletContextListener listener = new ContextLoaderListener();
|
||||
ServletContextEvent event = new ServletContextEvent(sc);
|
||||
try {
|
||||
listener.contextInitialized(event);
|
||||
fail("Should have thrown BeanDefinitionStoreException");
|
||||
}
|
||||
catch (BeanDefinitionStoreException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof IOException);
|
||||
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFrameworkServletWithDefaultLocation() throws Exception {
|
||||
DispatcherServlet servlet = new DispatcherServlet();
|
||||
servlet.setContextClass(XmlWebApplicationContext.class);
|
||||
try {
|
||||
servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
|
||||
fail("Should have thrown BeanDefinitionStoreException");
|
||||
}
|
||||
catch (BeanDefinitionStoreException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof IOException);
|
||||
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/test-servlet.xml"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFrameworkServletWithCustomLocation() throws Exception {
|
||||
DispatcherServlet servlet = new DispatcherServlet();
|
||||
servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml "
|
||||
+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
|
||||
servlet.init(new MockServletConfig(new MockServletContext(""), "test"));
|
||||
assertTrue(servlet.getWebApplicationContext().containsBean("kerry"));
|
||||
assertTrue(servlet.getWebApplicationContext().containsBean("kerryX"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClassPathXmlApplicationContext() throws IOException {
|
||||
ApplicationContext context = new ClassPathXmlApplicationContext(
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml");
|
||||
assertTrue("Has father", context.containsBean("father"));
|
||||
assertTrue("Has rod", context.containsBean("rod"));
|
||||
assertFalse("Hasn't kerry", context.containsBean("kerry"));
|
||||
assertTrue("Doesn't have spouse", ((TestBean) context.getBean("rod")).getSpouse() == null);
|
||||
assertTrue("myinit not evaluated", "Roderick".equals(((TestBean) context.getBean("rod")).getName()));
|
||||
|
||||
context = new ClassPathXmlApplicationContext(new String[] {
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml",
|
||||
"/org/springframework/web/context/WEB-INF/context-addition.xml" });
|
||||
assertTrue("Has father", context.containsBean("father"));
|
||||
assertTrue("Has rod", context.containsBean("rod"));
|
||||
assertTrue("Has kerry", context.containsBean("kerry"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSingletonDestructionOnStartupFailure() throws IOException {
|
||||
try {
|
||||
new ClassPathXmlApplicationContext(new String[] {
|
||||
"/org/springframework/web/context/WEB-INF/applicationContext.xml",
|
||||
"/org/springframework/web/context/WEB-INF/fail.xml" }) {
|
||||
|
||||
public void refresh() throws BeansException {
|
||||
try {
|
||||
super.refresh();
|
||||
}
|
||||
catch (BeanCreationException ex) {
|
||||
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) getBeanFactory();
|
||||
assertEquals(0, factory.getSingletonCount());
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
};
|
||||
fail("Should have thrown BeanCreationException");
|
||||
}
|
||||
catch (BeanCreationException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
ConfigurableEnvironment environment = applicationContext.getEnvironment();
|
||||
environment.getPropertySources().addFirst(new PropertySource<Object>("testPropertySource") {
|
||||
@Override
|
||||
public Object getProperty(String key) {
|
||||
return "name".equals(key) ? "testName" : null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestWebContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
|
||||
public void initialize(ConfigurableWebApplicationContext applicationContext) {
|
||||
ServletContext ctx = applicationContext.getServletContext(); // type-safe access to servlet-specific methods
|
||||
ctx.setAttribute("initialized", true);
|
||||
}
|
||||
}
|
||||
|
||||
private static interface UnknownApplicationContext extends ConfigurableApplicationContext {
|
||||
void unheardOf();
|
||||
}
|
||||
|
||||
private static class UnknownContextInitializer implements ApplicationContextInitializer<UnknownApplicationContext> {
|
||||
public void initialize(UnknownApplicationContext applicationContext) {
|
||||
applicationContext.unheardOf();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.web.context;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.context.support.AbstractMessageSource;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.ui.context.Theme;
|
||||
import org.springframework.ui.context.ThemeSource;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.theme.AbstractThemeResolver;
|
||||
|
||||
/**
|
||||
* Creates a WebApplicationContext that points to a "web.xml" file that
|
||||
* contains the entry for what file to use for the applicationContext
|
||||
* (file "org/springframework/web/context/WEB-INF/applicationContext.xml").
|
||||
* That file then has an entry for a bean called "messageSource".
|
||||
* Whatever the basename property is set to for this bean is what the name of
|
||||
* a properties file in the classpath must be (in our case the name is
|
||||
* "messages" - note no package names).
|
||||
* Thus the catalog filename will be in the root of where the classes are compiled
|
||||
* to and will be called "messages_XX_YY.properties" where "XX" and "YY" are the
|
||||
* language and country codes known by the ResourceBundle class.
|
||||
*
|
||||
* <p>NOTE: The main method of this class is the "createWebApplicationContext(...)" method,
|
||||
* and it was copied from org.springframework.web.context.XmlWebApplicationContextTests.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Jean-Pierre Pawlak
|
||||
*/
|
||||
public class ResourceBundleMessageSourceTests extends AbstractApplicationContextTests {
|
||||
|
||||
/**
|
||||
* We use ticket WAR root for file structure.
|
||||
* We don't attempt to read web.xml.
|
||||
*/
|
||||
public static final String WAR_ROOT = "/org/springframework/web/context";
|
||||
|
||||
private ConfigurableWebApplicationContext root;
|
||||
|
||||
private MessageSource themeMsgSource;
|
||||
|
||||
protected ConfigurableApplicationContext createContext() throws Exception {
|
||||
root = new XmlWebApplicationContext();
|
||||
MockServletContext sc = new MockServletContext();
|
||||
root.setServletContext(sc);
|
||||
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
|
||||
root.refresh();
|
||||
|
||||
ConfigurableWebApplicationContext wac = new XmlWebApplicationContext();
|
||||
wac.setParent(root);
|
||||
wac.setServletContext(sc);
|
||||
wac.setNamespace("test-servlet");
|
||||
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
|
||||
wac.refresh();
|
||||
|
||||
Theme theme = ((ThemeSource) wac).getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME);
|
||||
assertNotNull(theme);
|
||||
assertTrue("Theme name has to be the default theme name", AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(theme.getName()));
|
||||
themeMsgSource = theme.getMessageSource();
|
||||
assertNotNull(themeMsgSource);
|
||||
return wac;
|
||||
}
|
||||
|
||||
public void testCount() {
|
||||
assertTrue("should have 14 beans, not " +
|
||||
this.applicationContext.getBeanDefinitionCount(),
|
||||
this.applicationContext.getBeanDefinitionCount() == 14);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden as we can't trust superclass method.
|
||||
* @see org.springframework.context.AbstractApplicationContextTests#testEvents()
|
||||
*/
|
||||
public void testEvents() throws Exception {
|
||||
// Do nothing
|
||||
}
|
||||
|
||||
public void testRootMessageSourceWithUseCodeAsDefaultMessage() throws NoSuchMessageException {
|
||||
AbstractMessageSource messageSource = (AbstractMessageSource) root.getBean("messageSource");
|
||||
messageSource.setUseCodeAsDefaultMessage(true);
|
||||
|
||||
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
|
||||
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
|
||||
|
||||
try {
|
||||
applicationContext.getMessage("code0", null, Locale.getDefault());
|
||||
fail("looking for code0 should throw a NoSuchMessageException");
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// that's how it should be
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
|
||||
*/
|
||||
public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() {
|
||||
assertTrue("valid msg from resourcebundle with default msg passed in returned default msg. Expected msg from catalog.",
|
||||
getApplicationContext().getMessage("message.format.example2", null, "This is a default msg if not found in msg.cat.", Locale.US
|
||||
)
|
||||
.equals("This is a test message in the message catalog with no args."));
|
||||
// getApplicationContext().getTheme("theme").getMessageSource().getMessage()
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
|
||||
*/
|
||||
public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() {
|
||||
assertTrue("bogus msg from resourcebundle with default msg passed in returned default msg",
|
||||
getApplicationContext().getMessage("bogus.message", null, "This is a default msg if not found in msg.cat.", Locale.UK
|
||||
)
|
||||
.equals("This is a default msg if not found in msg.cat."));
|
||||
}
|
||||
|
||||
/**
|
||||
* The underlying implementation uses a hashMap to cache messageFormats
|
||||
* once a message has been asked for. This test is an attempt to
|
||||
* make sure the cache is being used properly.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
*/
|
||||
public void testGetMessageWithMessageAlreadyLookedFor() throws Exception {
|
||||
Object[] arguments = {
|
||||
new Integer(7), new Date(System.currentTimeMillis()),
|
||||
"a disturbance in the Force"
|
||||
};
|
||||
|
||||
// The first time searching, we don't care about for this test
|
||||
getApplicationContext().getMessage("message.format.example1", arguments, Locale.US);
|
||||
|
||||
// Now msg better be as expected
|
||||
assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US",
|
||||
getApplicationContext().getMessage("message.format.example1", arguments, Locale.US
|
||||
)
|
||||
.indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
|
||||
|
||||
Object[] newArguments = {
|
||||
new Integer(8), new Date(System.currentTimeMillis()),
|
||||
"a disturbance in the Force"
|
||||
};
|
||||
|
||||
// Now msg better be as expected even with different args
|
||||
assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US",
|
||||
getApplicationContext().getMessage("message.format.example1", newArguments, Locale.US
|
||||
)
|
||||
.indexOf("there was \"a disturbance in the Force\" on planet 8.") != -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
|
||||
* Example taken from the javadocs for the java.text.MessageFormat class
|
||||
*/
|
||||
public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog() throws Exception {
|
||||
Object[] arguments = {
|
||||
new Integer(7), new Date(System.currentTimeMillis()),
|
||||
"a disturbance in the Force"
|
||||
};
|
||||
|
||||
/*
|
||||
Try with Locale.US
|
||||
Since the msg has a time value in it, we will use String.indexOf(...)
|
||||
to just look for a substring without the time. This is because it is
|
||||
possible that by the time we store a time variable in this method
|
||||
and the time the ResourceBundleMessageSource resolves the msg the
|
||||
minutes of the time might not be the same.
|
||||
*/
|
||||
assertTrue("msg from resourcebundle for Locale.US substituting args for placeholders is as expected",
|
||||
getApplicationContext().getMessage("message.format.example1", arguments, Locale.US
|
||||
)
|
||||
.indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
|
||||
|
||||
// Try with Locale.UK
|
||||
assertTrue("msg from resourcebundle for Locale.UK substituting args for placeholders is as expected",
|
||||
getApplicationContext().getMessage("message.format.example1", arguments, Locale.UK
|
||||
)
|
||||
.indexOf("there was \"a disturbance in the Force\" on station number 7.") != -1);
|
||||
|
||||
// Try with Locale.US - different test msg that requires no args
|
||||
assertTrue("msg from resourcebundle that requires no args for Locale.US is as expected",
|
||||
getApplicationContext().getMessage("message.format.example2", null, Locale.US)
|
||||
.equals("This is a test message in the message catalog with no args."));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files.
|
||||
*/
|
||||
public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() {
|
||||
// Expecting an exception
|
||||
try {
|
||||
getApplicationContext().getMessage("bogus.message", null, Locale.UK);
|
||||
fail("bogus msg from resourcebundle without default msg should have thrown exception");
|
||||
}
|
||||
catch (NoSuchMessageException tExcept) {
|
||||
assertTrue("bogus msg from resourcebundle without default msg threw expected exception",
|
||||
true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetMultipleBasenamesForMessageSource() throws NoSuchMessageException {
|
||||
assertEquals("message1", getApplicationContext().getMessage("code1", null, Locale.UK));
|
||||
assertEquals("message2", getApplicationContext().getMessage("code2", null, Locale.UK));
|
||||
assertEquals("message3", getApplicationContext().getMessage("code3", null, Locale.UK));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files.
|
||||
*/
|
||||
public void testGetMessageWithDefaultPassedInAndFoundInThemeCatalog() {
|
||||
// Try with Locale.US
|
||||
String msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.US);
|
||||
assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog. Received: " + msg,
|
||||
msg.equals("This is a test message in the theme message catalog."));
|
||||
// Try with Locale.UK
|
||||
msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.UK);
|
||||
assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog.",
|
||||
msg.equals("This is a test message in the theme message catalog with no args."));
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.context.support.AbstractMessageSource for more details.
|
||||
* NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files.
|
||||
*/
|
||||
public void testGetMessageWithDefaultPassedInAndNotFoundInThemeCatalog() {
|
||||
assertTrue("bogus msg from theme resourcebundle with default msg passed in returned default msg",
|
||||
getThemeMessage("bogus.message", null, "This is a default msg if not found in theme cat.", Locale.UK
|
||||
)
|
||||
.equals("This is a default msg if not found in theme cat."));
|
||||
}
|
||||
|
||||
public void testThemeSourceNesting() throws NoSuchMessageException {
|
||||
String overriddenMsg = getThemeMessage("theme.example2", null, null, Locale.UK);
|
||||
MessageSource ms = ((ThemeSource) root).getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME).getMessageSource();
|
||||
String originalMsg = ms.getMessage("theme.example2", null, Locale.UK);
|
||||
assertTrue("correct overridden msg", "test-message2".equals(overriddenMsg));
|
||||
assertTrue("correct original msg", "message2".equals(originalMsg));
|
||||
}
|
||||
|
||||
public void testThemeSourceNestingWithParentDefault() throws NoSuchMessageException {
|
||||
StaticWebApplicationContext leaf = new StaticWebApplicationContext();
|
||||
leaf.setParent(getApplicationContext());
|
||||
leaf.refresh();
|
||||
assertNotNull("theme still found", leaf.getTheme("theme"));
|
||||
MessageSource ms = leaf.getTheme("theme").getMessageSource();
|
||||
String msg = ms.getMessage("theme.example2", null, null, Locale.UK);
|
||||
assertEquals("correct overridden msg", "test-message2", msg);
|
||||
}
|
||||
|
||||
private String getThemeMessage(String code, Object args[], String defaultMessage, Locale locale) {
|
||||
return themeMsgSource.getMessage(code, args, defaultMessage, locale);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.web.context;
|
||||
|
||||
import javax.servlet.ServletConfig;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class ServletConfigAwareBean implements ServletConfigAware {
|
||||
|
||||
private ServletConfig servletConfig;
|
||||
|
||||
public void setServletConfig(ServletConfig servletConfig) {
|
||||
this.servletConfig = servletConfig;
|
||||
}
|
||||
|
||||
public ServletConfig getServletConfig() {
|
||||
return servletConfig;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.web.context;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class ServletContextAwareBean implements ServletContextAware {
|
||||
|
||||
private ServletContext servletContext;
|
||||
|
||||
public void setServletContext(ServletContext servletContext) {
|
||||
this.servletContext = servletContext;
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
return servletContext;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.web.context;
|
||||
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.mock.web.MockServletConfig;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.support.ServletContextAwareProcessor;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Mark Fisher
|
||||
*/
|
||||
public class ServletContextAwareProcessorTests extends TestCase {
|
||||
|
||||
public void testServletContextAwareWithServletContext() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletContext should have been set", bean.getServletContext());
|
||||
assertEquals(servletContext, bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletContextAwareWithServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletContext should have been set", bean.getServletContext());
|
||||
assertEquals(servletContext, bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletContextAwareWithServletContextAndServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletContext should have been set", bean.getServletContext());
|
||||
assertEquals(servletContext, bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletContextAwareWithNullServletContextAndNonNullServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletContext should have been set", bean.getServletContext());
|
||||
assertEquals(servletContext, bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletContextAwareWithNonNullServletContextAndNullServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletContext should have been set", bean.getServletContext());
|
||||
assertEquals(servletContext, bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletContextAwareWithNullServletContext() {
|
||||
ServletContext servletContext = null;
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
|
||||
ServletContextAwareBean bean = new ServletContextAwareBean();
|
||||
assertNull(bean.getServletContext());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNull(bean.getServletContext());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithServletContextOnly() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNull(bean.getServletConfig());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletConfig should have been set", bean.getServletConfig());
|
||||
assertEquals(servletConfig, bean.getServletConfig());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithServletContextAndServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletConfig should have been set", bean.getServletConfig());
|
||||
assertEquals(servletConfig, bean.getServletConfig());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithNullServletContextAndNonNullServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletConfig servletConfig = new MockServletConfig(servletContext);
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNotNull("ServletConfig should have been set", bean.getServletConfig());
|
||||
assertEquals(servletConfig, bean.getServletConfig());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithNonNullServletContextAndNullServletConfig() {
|
||||
ServletContext servletContext = new MockServletContext();
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNull(bean.getServletConfig());
|
||||
}
|
||||
|
||||
public void testServletConfigAwareWithNullServletContext() {
|
||||
ServletContext servletContext = null;
|
||||
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
|
||||
ServletConfigAwareBean bean = new ServletConfigAwareBean();
|
||||
assertNull(bean.getServletConfig());
|
||||
processor.postProcessBeforeInitialization(bean, "testBean");
|
||||
assertNull(bean.getServletConfig());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?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 class="org.springframework.beans.TestBean">
|
||||
<constructor-arg value="${name}"/>
|
||||
</bean>
|
||||
|
||||
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,82 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
|
||||
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
|
||||
]>
|
||||
|
||||
<beans>
|
||||
|
||||
<import resource="resources/messageSource.xml"/>
|
||||
|
||||
<import resource="/resources/../resources/themeSource.xml"/>
|
||||
|
||||
<bean id="lifecyclePostProcessor" class="org.springframework.beans.factory.LifecycleBean$PostProcessor"/>
|
||||
|
||||
<!--
|
||||
<bean
|
||||
name="performanceMonitor" class="org.springframework.context.support.TestListener"
|
||||
/>
|
||||
-->
|
||||
|
||||
<!--
|
||||
<bean name="aca" class="org.springframework.context.ACATest">
|
||||
</bean>
|
||||
|
||||
<bean name="aca-prototype" class="org.springframework.context.ACATest" scope="prototype">
|
||||
</bean>
|
||||
-->
|
||||
|
||||
<bean id="beanThatListens" class="org.springframework.context.BeanThatListens"/>
|
||||
|
||||
<bean id="parentListener" class="org.springframework.context.TestListener"/>
|
||||
|
||||
<!-- Inherited tests -->
|
||||
|
||||
<!-- name and age values will be overridden by myinit.properties" -->
|
||||
<bean id="rod" class="org.springframework.beans.TestBean">
|
||||
<property name="name">
|
||||
<value>dummy</value>
|
||||
</property>
|
||||
<property name="age">
|
||||
<value>-1</value>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<!--
|
||||
Tests of lifecycle callbacks
|
||||
-->
|
||||
<bean id="mustBeInitialized"
|
||||
class="org.springframework.beans.factory.MustBeInitialized">
|
||||
</bean>
|
||||
|
||||
<bean id="lifecycle"
|
||||
class="org.springframework.context.LifecycleContextBean"
|
||||
init-method="declaredInitMethod">
|
||||
<property name="initMethodDeclared"><value>true</value></property>
|
||||
</bean>
|
||||
|
||||
&contextInclude;
|
||||
|
||||
<bean id="myOverride" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
|
||||
<property name="location">
|
||||
<value>/org/springframework/web/context/WEB-INF/myoverride.properties</value>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="myPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
|
||||
<property name="locations">
|
||||
<list>
|
||||
<value>classpath:/org/springframework/web/context/WEB-INF/myplace*.properties</value>
|
||||
<value>classpath:/org/springframework/web/context/WEB-INF/myover*.properties</value>
|
||||
<value>${myDir}/myover*.properties</value>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="init-and-ib"
|
||||
class="org.springframework.web.context.XmlWebApplicationContextTests$InitAndIB"
|
||||
lazy-init="true"
|
||||
init-method="customInit"
|
||||
destroy-method="customDestroy"
|
||||
/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="aca" class="org.springframework.context.ACATester"/>
|
||||
|
||||
<bean id="aca-prototype" class="org.springframework.context.ACATester" scope="prototype"/>
|
||||
|
||||
<bean id="testListener" class="org.springframework.context.TestListener"/>
|
||||
|
||||
<bean id="roderick" parent="rod">
|
||||
<property name="name"><value>Roderick</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype"/>
|
||||
|
||||
<bean id="kerry" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Kerry</value></property>
|
||||
<property name="age"><value>34</value></property>
|
||||
<property name="spouse"><ref bean="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
|
||||
<property name="name"><value>typeMismatch</value></property>
|
||||
<property name="age"><value>34x</value></property>
|
||||
<property name="spouse"><ref bean="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<!-- Factory beans are automatically treated
|
||||
differently -->
|
||||
<bean id="singletonFactory"
|
||||
class="org.springframework.beans.factory.DummyFactory">
|
||||
</bean>
|
||||
|
||||
<bean id="prototypeFactory"
|
||||
class="org.springframework.beans.factory.DummyFactory">
|
||||
<property name="singleton"><value>false</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
|
||||
<!-- <listener property="age" beanRef="agistListener" /> -->
|
||||
<property name="name"><value>listenerVeto</value></property>
|
||||
<property name="age"><value>66</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,6 @@
|
||||
code1=message1
|
||||
code2=message2
|
||||
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
|
||||
message.format.example2=This is a test message in the message catalog with no args.
|
||||
@@ -0,0 +1,2 @@
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on station number {0,number,integer}.
|
||||
@@ -0,0 +1,5 @@
|
||||
code1=message1
|
||||
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
|
||||
message.format.example2=This is a test message in the message catalog with no args.
|
||||
@@ -0,0 +1,6 @@
|
||||
<!-- Include snippet to be loaded via entity reference in applicationContext.xml -->
|
||||
|
||||
<bean id="father" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>yetanotherdummy</value></property>
|
||||
</bean>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?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">
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
|
||||
|
||||
<bean id="servletContextAwareBean" class="org.springframework.web.context.ServletContextAwareBean"/>
|
||||
|
||||
<bean id="servletConfigAwareBean" class="org.springframework.web.context.ServletConfigAwareBean"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="fail" class="java.lang.Integer"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,2 @@
|
||||
code1=message1x
|
||||
code3=message3
|
||||
@@ -0,0 +1,3 @@
|
||||
father.name=Albert
|
||||
rod.age=31
|
||||
rod.name=Roderick
|
||||
@@ -0,0 +1,4 @@
|
||||
useCodeAsDefaultMessage=false
|
||||
message-file=context-messages
|
||||
objectName=test:service=myservice
|
||||
theme-base=org/springframework/web/context/WEB-INF/
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
|
||||
<property name="useCodeAsDefaultMessage">
|
||||
<value>${useCodeAsDefaultMessage}</value>
|
||||
</property>
|
||||
<property name="basenames">
|
||||
<list>
|
||||
<value>org/springframework/web/context/WEB-INF/${message-file}</value>
|
||||
<value>org/springframework/web/context/WEB-INF/more-context-messages</value>
|
||||
</list>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<bean id="messageSourceString" factory-bean="messageSource" factory-method="toString"/>
|
||||
|
||||
<bean id="currentTimeMillis" class="javax.management.ObjectName" factory-method="getInstance">
|
||||
<constructor-arg value="${objectName}"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
|
||||
<property name="basenamePrefix">
|
||||
<value>${theme-base}</value>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="rob" class="org.springframework.beans.TestBean">
|
||||
<property name="name" value="dummy"/>
|
||||
<property name="age" value="-1"/>
|
||||
</bean>
|
||||
|
||||
<bean id="rodProto" class="org.springframework.beans.TestBean" scope="prototype">
|
||||
<property name="name" value="dummy"/>
|
||||
<property name="age" value="-1"/>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1 @@
|
||||
code2=message2
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
|
||||
<property name="basename"><value>org/springframework/web/context/WEB-INF/test-messages</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
|
||||
<property name="basenamePrefix"><value>org/springframework/web/context/WEB-INF/test-</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="aca" class="org.springframework.context.ACATester"/>
|
||||
|
||||
<bean id="aca-prototype" class="org.springframework.context.ACATester" scope="prototype"/>
|
||||
|
||||
<bean id="rod" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Rod</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
<property name="spouse"><ref bean="father"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="testListener" class="org.springframework.context.TestListener"/>
|
||||
|
||||
<bean id="roderick" parent="rod">
|
||||
<property name="name"><value>Roderick</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype"/>
|
||||
|
||||
<bean id="kerry" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Kerry</value></property>
|
||||
<property name="age"><value>34</value></property>
|
||||
<property name="spouse"><ref local="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
|
||||
<property name="name"><value>typeMismatch</value></property>
|
||||
<property name="age"><value>34x</value></property>
|
||||
<property name="spouse"><ref local="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
|
||||
</bean>
|
||||
|
||||
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
|
||||
<property name="singleton"><value>false</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>listenerVeto</value></property>
|
||||
<property name="age"><value>66</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1 @@
|
||||
theme.example2=test-message2
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="rod" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Rod</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="kerryX" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Kerry</value></property>
|
||||
<property name="age"><value>34</value></property>
|
||||
<property name="spouse"><ref local="rod"/></property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,2 @@
|
||||
theme.example1=This is a test message in the theme message catalog with no args.
|
||||
theme.example2=message2
|
||||
@@ -0,0 +1 @@
|
||||
theme.example1=This is a test message in the theme message catalog.
|
||||
@@ -0,0 +1,151 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
|
||||
<web-app>
|
||||
<display-name>ticket-webapp</display-name>
|
||||
<description>Web interface for ticket application</description>
|
||||
|
||||
<distributable/>
|
||||
|
||||
<!--
|
||||
<listener>
|
||||
<listener-class>com.wrox.j2eedd.ticket.web.SessionCleanupListener</listener-class>
|
||||
</listener>
|
||||
-->
|
||||
|
||||
|
||||
<!-- This servlet must be loaded first to configure the log4j
|
||||
system and create the WebApplicationContext
|
||||
-->
|
||||
<servlet>
|
||||
<servlet-name>config</servlet-name>
|
||||
<servlet-class>org.springframework.framework.web.context.ContextLoaderServlet</servlet-class>
|
||||
<init-param>
|
||||
<param-name>contextClass</param-name>
|
||||
<param-value>org.springframework.framework.web.context.XMLWebApplicationContext</param-value>
|
||||
</init-param>
|
||||
<init-param>
|
||||
<param-name>log4jPropertiesUrl</param-name>
|
||||
<param-value>/WEB-INF/log4j_PRODUCTION.properties</param-value>
|
||||
</init-param>
|
||||
<!-- This is essential -->
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
|
||||
|
||||
<servlet>
|
||||
<servlet-name>boxOffice</servlet-name>
|
||||
<servlet-class>org.springframework.framework.web.workflow.CommandServlet</servlet-class>
|
||||
</servlet>
|
||||
|
||||
|
||||
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>boxOffice</servlet-name>
|
||||
<url-pattern>/*.html</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
<servlet-mapping>
|
||||
<servlet-name>config</servlet-name>
|
||||
<url-pattern>/context/context.html</url-pattern>
|
||||
</servlet-mapping>
|
||||
|
||||
|
||||
<session-config>
|
||||
<session-timeout>60</session-timeout>
|
||||
</session-config>
|
||||
|
||||
<welcome-file-list>
|
||||
<!-- Simply doesn't work to a servlet -->
|
||||
<welcome-file>/welcome.jsp</welcome-file>
|
||||
</welcome-file-list>
|
||||
|
||||
<error-page>
|
||||
<error-code>403</error-code>
|
||||
<location>/jsp/layout/twocolumn/403-Forbidden.jsp</location>
|
||||
</error-page>
|
||||
|
||||
<error-page>
|
||||
<error-code>404</error-code>
|
||||
<location>/jsp/layout/twocolumn/404-NotFound.jsp</location>
|
||||
</error-page>
|
||||
|
||||
<error-page>
|
||||
<exception-type>java.lang.Throwable</exception-type>
|
||||
<location>/jsp/layout/twocolumn/uncaughtException.jsp</location>
|
||||
</error-page>
|
||||
|
||||
<taglib>
|
||||
<taglib-uri>/bind</taglib-uri>
|
||||
<taglib-location>/WEB-INF/tlds/b11.tld</taglib-location>
|
||||
</taglib>
|
||||
|
||||
<taglib>
|
||||
<taglib-uri>/events</taglib-uri>
|
||||
<taglib-location>/WEB-INF/tlds/event11.tld</taglib-location>
|
||||
</taglib>
|
||||
|
||||
<security-constraint>
|
||||
<web-resource-collection>
|
||||
<web-resource-name>SalesInfo
|
||||
</web-resource-name>
|
||||
<url-pattern>purchase.html</url-pattern>
|
||||
<http-method>GET</http-method>
|
||||
<http-method>POST</http-method>
|
||||
</web-resource-collection>
|
||||
<auth-constraint>
|
||||
<role-name>registeredUsers</role-name>
|
||||
</auth-constraint>
|
||||
<user-data-constraint>
|
||||
<transport-guarantee>NONE</transport-guarantee>
|
||||
</user-data-constraint>
|
||||
</security-constraint>
|
||||
|
||||
|
||||
<login-config>
|
||||
<auth-method>FORM</auth-method>
|
||||
|
||||
<!-- Used only for BASIC authentication: only included because ServletUnit needs it -->
|
||||
<realm-name>ticket</realm-name>
|
||||
|
||||
<form-login-config>
|
||||
<form-login-page>login.jsp</form-login-page>
|
||||
<form-error-page>loginError.jsp</form-error-page>
|
||||
</form-login-config>
|
||||
</login-config>
|
||||
|
||||
|
||||
<security-role>
|
||||
<role-name>registeredUsers</role-name>
|
||||
</security-role>
|
||||
|
||||
|
||||
|
||||
|
||||
<ejb-ref>
|
||||
<ejb-ref-name>ejb/FixtureManager</ejb-ref-name>
|
||||
<ejb-ref-type>Session</ejb-ref-type>
|
||||
<home>com.wrox.j2eedd.ticket.ejb.fixturemanager.FixtureManagerRemoteHome</home>
|
||||
<remote>com.wrox.j2eedd.ticket.ejb.fixturemanager.FixtureManagerRemote</remote>
|
||||
<ejb-link>FixtureManager</ejb-link>
|
||||
</ejb-ref>
|
||||
|
||||
|
||||
<ejb-ref>
|
||||
<ejb-ref-name>ejb/BoxOffice</ejb-ref-name>
|
||||
<ejb-ref-type>Session</ejb-ref-type>
|
||||
<home>com.wrox.j2eedd.ticket.ejb.booking.BoxOfficeRemoteHome</home>
|
||||
<remote>com.wrox.j2eedd.ticket.ejb.booking.BoxOfficeRemote</remote>
|
||||
<ejb-link>BookingManager</ejb-link>
|
||||
</ejb-ref>
|
||||
|
||||
<ejb-ref>
|
||||
<ejb-ref-name>ejb/CustomerManager</ejb-ref-name>
|
||||
<ejb-ref-type>Session</ejb-ref-type>
|
||||
<home>com.wrox.j2eedd.ticket.ejb.customer.CustomerManagerRemoteHoms</home>
|
||||
<remote>com.wrox.j2eedd.ticket.ejb.customer.CustomerManagerRemote</remote>
|
||||
<ejb-link>CustomerManager</ejb-link>
|
||||
</ejb-ref>
|
||||
|
||||
</web-app>
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.web.context;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.sameInstance;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.context.TestListener;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class XmlWebApplicationContextTests extends AbstractApplicationContextTests {
|
||||
|
||||
private ConfigurableWebApplicationContext root;
|
||||
|
||||
protected ConfigurableApplicationContext createContext() throws Exception {
|
||||
InitAndIB.constructed = false;
|
||||
root = new XmlWebApplicationContext();
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
root.setServletContext(sc);
|
||||
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
|
||||
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
|
||||
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
|
||||
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof TestBean) {
|
||||
((TestBean) bean).getFriends().add("myFriend");
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
root.refresh();
|
||||
XmlWebApplicationContext wac = new XmlWebApplicationContext();
|
||||
wac.setParent(root);
|
||||
wac.setServletContext(sc);
|
||||
wac.setNamespace("test-servlet");
|
||||
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
|
||||
wac.refresh();
|
||||
return wac;
|
||||
}
|
||||
|
||||
public void testEnvironmentInheritance() {
|
||||
assertThat(this.applicationContext.getEnvironment(), sameInstance(this.root.getEnvironment()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden as we can't trust superclass method
|
||||
* @see org.springframework.context.AbstractApplicationContextTests#testEvents()
|
||||
*/
|
||||
public void testEvents() throws Exception {
|
||||
TestListener listener = (TestListener) this.applicationContext.getBean("testListener");
|
||||
listener.zeroCounter();
|
||||
TestListener parentListener = (TestListener) this.applicationContext.getParent().getBean("parentListener");
|
||||
parentListener.zeroCounter();
|
||||
|
||||
parentListener.zeroCounter();
|
||||
assertTrue("0 events before publication", listener.getEventCount() == 0);
|
||||
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
|
||||
this.applicationContext.publishEvent(new MyEvent(this));
|
||||
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
|
||||
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
|
||||
}
|
||||
|
||||
public void testCount() {
|
||||
assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
|
||||
this.applicationContext.getBeanDefinitionCount() == 14);
|
||||
}
|
||||
|
||||
public void testWithoutMessageSource() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
XmlWebApplicationContext wac = new XmlWebApplicationContext();
|
||||
wac.setParent(root);
|
||||
wac.setServletContext(sc);
|
||||
wac.setNamespace("testNamespace");
|
||||
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
|
||||
wac.refresh();
|
||||
try {
|
||||
wac.getMessage("someMessage", null, Locale.getDefault());
|
||||
fail("Should have thrown NoSuchMessageException");
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// expected;
|
||||
}
|
||||
String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault());
|
||||
assertTrue("Default message returned", "default".equals(msg));
|
||||
}
|
||||
|
||||
public void testContextNesting() {
|
||||
TestBean father = (TestBean) this.applicationContext.getBean("father");
|
||||
assertTrue("Bean from root context", father != null);
|
||||
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
|
||||
|
||||
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
|
||||
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
|
||||
assertTrue("Bean has external reference", rod.getSpouse() == father);
|
||||
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
|
||||
|
||||
rod = (TestBean) this.root.getBean("rod");
|
||||
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
|
||||
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
|
||||
}
|
||||
|
||||
public void testInitializingBeanAndInitMethod() throws Exception {
|
||||
assertFalse(InitAndIB.constructed);
|
||||
InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
|
||||
assertTrue(InitAndIB.constructed);
|
||||
assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked);
|
||||
assertTrue(!iib.destroyed && !iib.customDestroyed);
|
||||
this.applicationContext.close();
|
||||
assertTrue(!iib.destroyed && !iib.customDestroyed);
|
||||
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent();
|
||||
parent.close();
|
||||
assertTrue(iib.destroyed && iib.customDestroyed);
|
||||
parent.close();
|
||||
assertTrue(iib.destroyed && iib.customDestroyed);
|
||||
}
|
||||
|
||||
|
||||
public static class InitAndIB implements InitializingBean, DisposableBean {
|
||||
|
||||
public static boolean constructed;
|
||||
|
||||
public boolean afterPropertiesSetInvoked, initMethodInvoked, destroyed, customDestroyed;
|
||||
|
||||
public InitAndIB() {
|
||||
constructed = true;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (this.initMethodInvoked)
|
||||
fail();
|
||||
this.afterPropertiesSetInvoked = true;
|
||||
}
|
||||
|
||||
/** Init method */
|
||||
public void customInit() throws ServletException {
|
||||
if (!this.afterPropertiesSetInvoked)
|
||||
fail();
|
||||
this.initMethodInvoked = true;
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (this.customDestroyed)
|
||||
fail();
|
||||
if (this.destroyed) {
|
||||
throw new IllegalStateException("Already destroyed");
|
||||
}
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public void customDestroy() {
|
||||
if (!this.destroyed)
|
||||
fail();
|
||||
if (this.customDestroyed) {
|
||||
throw new IllegalStateException("Already customDestroyed");
|
||||
}
|
||||
this.customDestroyed = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- $Id: beans1.xml,v 1.3 2006/08/20 19:08:40 jhoeller Exp $ -->
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="beans1.bean1" class="org.springframework.beans.factory.access.TestBean">
|
||||
<property name="name"><value>beans1.bean1</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="beans1.bean2" class="org.springframework.beans.factory.access.TestBean">
|
||||
<property name="name"><value>bean2</value></property>
|
||||
<property name="objRef"><ref bean="beans1.bean2"/></property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<!-- We are only using one definition file for the purposes of this test, since we do not have multiple
|
||||
classloaders available in the environment to allow combining multiple files of the same name, but
|
||||
of course the contents within could be spread out across multiple files of the same name withing
|
||||
different jars -->
|
||||
|
||||
<beans>
|
||||
|
||||
<!-- this definition could be inside one beanRefFactory.xml file -->
|
||||
<bean id="a.qualified.name.of.some.sort"
|
||||
class="org.springframework.context.support.ClassPathXmlApplicationContext">
|
||||
<property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
|
||||
</bean>
|
||||
|
||||
<!-- while the following two could be inside another, also on the classpath,
|
||||
perhaps coming from another component jar -->
|
||||
<bean id="another.qualified.name"
|
||||
class="org.springframework.context.support.ClassPathXmlApplicationContext">
|
||||
<property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
|
||||
<property name="parent" ref="a.qualified.name.of.some.sort"/>
|
||||
</bean>
|
||||
|
||||
<alias name="another.qualified.name" alias="a.qualified.name.which.is.an.alias"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* Copyright 2002-2006 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.web.context.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletConfig;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.HttpRequestHandler;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 2.0
|
||||
*/
|
||||
public class HttpRequestHandlerTests {
|
||||
|
||||
@Test
|
||||
public void testHttpRequestHandlerServletPassThrough() throws Exception {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.getBeanFactory().registerSingleton("myHandler", new HttpRequestHandler() {
|
||||
public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
|
||||
assertSame(request, req);
|
||||
assertSame(response, res);
|
||||
String exception = request.getParameter("exception");
|
||||
if ("ServletException".equals(exception)) {
|
||||
throw new ServletException("test");
|
||||
}
|
||||
if ("IOException".equals(exception)) {
|
||||
throw new IOException("test");
|
||||
}
|
||||
res.getWriter().write("myResponse");
|
||||
}
|
||||
});
|
||||
wac.setServletContext(servletContext);
|
||||
wac.refresh();
|
||||
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
|
||||
Servlet servlet = new HttpRequestHandlerServlet();
|
||||
servlet.init(new MockServletConfig(servletContext, "myHandler"));
|
||||
|
||||
servlet.service(request, response);
|
||||
assertEquals("myResponse", response.getContentAsString());
|
||||
|
||||
try {
|
||||
request.setParameter("exception", "ServletException");
|
||||
servlet.service(request, response);
|
||||
fail("Should have thrown ServletException");
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
assertEquals("test", ex.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
request.setParameter("exception", "IOException");
|
||||
servlet.service(request, response);
|
||||
fail("Should have thrown IOException");
|
||||
}
|
||||
catch (IOException ex) {
|
||||
assertEquals("test", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
/*
|
||||
* Copyright 2002-2008 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.web.context.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.BeanCreationException;
|
||||
import org.springframework.beans.factory.config.BeanDefinitionHolder;
|
||||
import org.springframework.beans.factory.config.ConstructorArgumentValues;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
import org.springframework.beans.factory.support.ChildBeanDefinition;
|
||||
import org.springframework.beans.factory.support.ManagedList;
|
||||
import org.springframework.beans.factory.support.ManagedMap;
|
||||
import org.springframework.beans.factory.support.ManagedSet;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
|
||||
/**
|
||||
* Tests for various ServletContext-related support classes.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 22.12.2004
|
||||
*/
|
||||
public class ServletContextSupportTests {
|
||||
|
||||
@Test
|
||||
public void testServletContextFactoryBean() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
wac.registerSingleton("servletContext", ServletContextFactoryBean.class, pvs);
|
||||
wac.refresh();
|
||||
|
||||
Object value = wac.getBean("servletContext");
|
||||
assertEquals(sc, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextAttributeFactoryBean() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.setAttribute("myAttr", "myValue");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("attributeName", "myAttr");
|
||||
wac.registerSingleton("importedAttr", ServletContextAttributeFactoryBean.class, pvs);
|
||||
wac.refresh();
|
||||
|
||||
Object value = wac.getBean("importedAttr");
|
||||
assertEquals("myValue", value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextAttributeFactoryBeanWithAttributeNotFound() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("attributeName", "myAttr");
|
||||
wac.registerSingleton("importedAttr", ServletContextAttributeFactoryBean.class, pvs);
|
||||
|
||||
try {
|
||||
wac.refresh();
|
||||
fail("Should have thrown BeanCreationException");
|
||||
}
|
||||
catch (BeanCreationException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof IllegalStateException);
|
||||
assertTrue(ex.getCause().getMessage().indexOf("myAttr") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextParameterFactoryBean() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("myParam", "myValue");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("initParamName", "myParam");
|
||||
wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs);
|
||||
wac.refresh();
|
||||
|
||||
Object value = wac.getBean("importedParam");
|
||||
assertEquals("myValue", value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextParameterFactoryBeanWithAttributeNotFound() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("initParamName", "myParam");
|
||||
wac.registerSingleton("importedParam", ServletContextParameterFactoryBean.class, pvs);
|
||||
|
||||
try {
|
||||
wac.refresh();
|
||||
fail("Should have thrown BeanCreationException");
|
||||
}
|
||||
catch (BeanCreationException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getCause() instanceof IllegalStateException);
|
||||
assertTrue(ex.getCause().getMessage().indexOf("myParam") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextAttributeExporter() {
|
||||
TestBean tb = new TestBean();
|
||||
Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
attributes.put("attr1", "value1");
|
||||
attributes.put("attr2", tb);
|
||||
|
||||
MockServletContext sc = new MockServletContext();
|
||||
ServletContextAttributeExporter exporter = new ServletContextAttributeExporter();
|
||||
exporter.setAttributes(attributes);
|
||||
exporter.setServletContext(sc);
|
||||
|
||||
assertEquals("value1", sc.getAttribute("attr1"));
|
||||
assertSame(tb, sc.getAttribute("attr2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextPropertyPlaceholderConfigurer() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("key4", "mykey4");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("age", "${age}");
|
||||
pvs.add("name", "${key4}name${var}${var}${");
|
||||
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
|
||||
wac.registerSingleton("tb1", TestBean.class, pvs);
|
||||
|
||||
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, null);
|
||||
wac.getDefaultListableBeanFactory().registerBeanDefinition("tb2", bd);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("properties", "age=98\nvar=${m}var\nref=tb2\nm=my");
|
||||
wac.registerSingleton("configurer", ServletContextPropertyPlaceholderConfigurer.class, pvs);
|
||||
|
||||
wac.refresh();
|
||||
|
||||
TestBean tb1 = (TestBean) wac.getBean("tb1");
|
||||
TestBean tb2 = (TestBean) wac.getBean("tb2");
|
||||
assertEquals(98, tb1.getAge());
|
||||
assertEquals("mykey4namemyvarmyvar${", tb1.getName());
|
||||
assertEquals(tb2, tb1.getSpouse());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextPropertyPlaceholderConfigurerWithLocalOverriding() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("key4", "mykey4");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("age", "${age}");
|
||||
pvs.add("name", "${key4}name${var}${var}${");
|
||||
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
|
||||
wac.registerSingleton("tb1", TestBean.class, pvs);
|
||||
|
||||
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, null);
|
||||
wac.getDefaultListableBeanFactory().registerBeanDefinition("tb2", bd);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("properties", "age=98\nvar=${m}var\nref=tb2\nm=my\nkey4=yourkey4");
|
||||
wac.registerSingleton("configurer", ServletContextPropertyPlaceholderConfigurer.class, pvs);
|
||||
|
||||
wac.refresh();
|
||||
|
||||
TestBean tb1 = (TestBean) wac.getBean("tb1");
|
||||
TestBean tb2 = (TestBean) wac.getBean("tb2");
|
||||
assertEquals(98, tb1.getAge());
|
||||
assertEquals("yourkey4namemyvarmyvar${", tb1.getName());
|
||||
assertEquals(tb2, tb1.getSpouse());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextPropertyPlaceholderConfigurerWithContextOverride() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("key4", "mykey4");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("age", "${age}");
|
||||
pvs.add("name", "${key4}name${var}${var}${");
|
||||
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
|
||||
wac.registerSingleton("tb1", TestBean.class, pvs);
|
||||
|
||||
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, null);
|
||||
wac.getDefaultListableBeanFactory().registerBeanDefinition("tb2", bd);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("properties", "age=98\nvar=${m}var\nref=tb2\nm=my\nkey4=yourkey4");
|
||||
pvs.add("contextOverride", Boolean.TRUE);
|
||||
wac.registerSingleton("configurer", ServletContextPropertyPlaceholderConfigurer.class, pvs);
|
||||
|
||||
wac.refresh();
|
||||
|
||||
TestBean tb1 = (TestBean) wac.getBean("tb1");
|
||||
TestBean tb2 = (TestBean) wac.getBean("tb2");
|
||||
assertEquals(98, tb1.getAge());
|
||||
assertEquals("mykey4namemyvarmyvar${", tb1.getName());
|
||||
assertEquals(tb2, tb1.getSpouse());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextPropertyPlaceholderConfigurerWithContextOverrideAndAttributes() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("key4", "mykey4");
|
||||
sc.setAttribute("key4", "attrkey4");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("age", "${age}");
|
||||
pvs.add("name", "${key4}name${var}${var}${");
|
||||
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
|
||||
wac.registerSingleton("tb1", TestBean.class, pvs);
|
||||
|
||||
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, null);
|
||||
wac.getDefaultListableBeanFactory().registerBeanDefinition("tb2", bd);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("properties", "age=98\nvar=${m}var\nref=tb2\nm=my\nkey4=yourkey4");
|
||||
pvs.add("contextOverride", Boolean.TRUE);
|
||||
pvs.add("searchContextAttributes", Boolean.TRUE);
|
||||
wac.registerSingleton("configurer", ServletContextPropertyPlaceholderConfigurer.class, pvs);
|
||||
|
||||
wac.refresh();
|
||||
|
||||
TestBean tb1 = (TestBean) wac.getBean("tb1");
|
||||
TestBean tb2 = (TestBean) wac.getBean("tb2");
|
||||
assertEquals(98, tb1.getAge());
|
||||
assertEquals("attrkey4namemyvarmyvar${", tb1.getName());
|
||||
assertEquals(tb2, tb1.getSpouse());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextPropertyPlaceholderConfigurerWithAttributes() {
|
||||
MockServletContext sc = new MockServletContext();
|
||||
sc.addInitParameter("key4", "mykey4");
|
||||
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("age", "${age}");
|
||||
pvs.add("name", "name${var}${var}${");
|
||||
pvs.add("spouse", new RuntimeBeanReference("${ref}"));
|
||||
wac.registerSingleton("tb1", TestBean.class, pvs);
|
||||
|
||||
ConstructorArgumentValues cas = new ConstructorArgumentValues();
|
||||
cas.addIndexedArgumentValue(1, "${age}");
|
||||
cas.addGenericArgumentValue("${var}name${age}");
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
List<Object> friends = new ManagedList<Object>();
|
||||
friends.add("na${age}me");
|
||||
friends.add(new RuntimeBeanReference("${ref}"));
|
||||
pvs.add("friends", friends);
|
||||
|
||||
Set<Object> someSet = new ManagedSet<Object>();
|
||||
someSet.add("na${age}me");
|
||||
someSet.add(new RuntimeBeanReference("${ref}"));
|
||||
pvs.add("someSet", someSet);
|
||||
|
||||
Map<String, Object> someMap = new ManagedMap<String, Object>();
|
||||
someMap.put("key1", new RuntimeBeanReference("${ref}"));
|
||||
someMap.put("key2", "${age}name");
|
||||
MutablePropertyValues innerPvs = new MutablePropertyValues();
|
||||
innerPvs.add("touchy", "${os.name}");
|
||||
someMap.put("key3", new RootBeanDefinition(TestBean.class, innerPvs));
|
||||
MutablePropertyValues innerPvs2 = new MutablePropertyValues(innerPvs);
|
||||
someMap.put("${key4}", new BeanDefinitionHolder(new ChildBeanDefinition("tb1", innerPvs2), "child"));
|
||||
pvs.add("someMap", someMap);
|
||||
|
||||
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class, cas, pvs);
|
||||
wac.getDefaultListableBeanFactory().registerBeanDefinition("tb2", bd);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("properties", "var=${m}var\nref=tb2\nm=my");
|
||||
pvs.add("searchContextAttributes", Boolean.TRUE);
|
||||
wac.registerSingleton("configurer", ServletContextPropertyPlaceholderConfigurer.class, pvs);
|
||||
sc.setAttribute("age", new Integer(98));
|
||||
|
||||
wac.refresh();
|
||||
|
||||
TestBean tb1 = (TestBean) wac.getBean("tb1");
|
||||
TestBean tb2 = (TestBean) wac.getBean("tb2");
|
||||
assertEquals(98, tb1.getAge());
|
||||
assertEquals(98, tb2.getAge());
|
||||
assertEquals("namemyvarmyvar${", tb1.getName());
|
||||
assertEquals("myvarname98", tb2.getName());
|
||||
assertEquals(tb2, tb1.getSpouse());
|
||||
assertEquals(2, tb2.getFriends().size());
|
||||
assertEquals("na98me", tb2.getFriends().iterator().next());
|
||||
assertEquals(tb2, tb2.getFriends().toArray()[1]);
|
||||
assertEquals(2, tb2.getSomeSet().size());
|
||||
assertTrue(tb2.getSomeSet().contains("na98me"));
|
||||
assertTrue(tb2.getSomeSet().contains(tb2));
|
||||
assertEquals(4, tb2.getSomeMap().size());
|
||||
assertEquals(tb2, tb2.getSomeMap().get("key1"));
|
||||
assertEquals("98name", tb2.getSomeMap().get("key2"));
|
||||
TestBean inner1 = (TestBean) tb2.getSomeMap().get("key3");
|
||||
TestBean inner2 = (TestBean) tb2.getSomeMap().get("mykey4");
|
||||
assertEquals(0, inner1.getAge());
|
||||
assertEquals(null, inner1.getName());
|
||||
assertEquals(System.getProperty("os.name"), inner1.getTouchy());
|
||||
assertEquals(98, inner2.getAge());
|
||||
assertEquals("namemyvarmyvar${", inner2.getName());
|
||||
assertEquals(System.getProperty("os.name"), inner2.getTouchy());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextResourceLoader() {
|
||||
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context");
|
||||
ServletContextResourceLoader rl = new ServletContextResourceLoader(sc);
|
||||
assertTrue(rl.getResource("/WEB-INF/web.xml").exists());
|
||||
assertTrue(rl.getResource("WEB-INF/web.xml").exists());
|
||||
assertTrue(rl.getResource("../context/WEB-INF/web.xml").exists());
|
||||
assertTrue(rl.getResource("/../context/WEB-INF/web.xml").exists());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextResourcePatternResolver() throws IOException {
|
||||
final Set<String> paths = new HashSet<String>();
|
||||
paths.add("/WEB-INF/context1.xml");
|
||||
paths.add("/WEB-INF/context2.xml");
|
||||
|
||||
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
if ("/WEB-INF/".equals(path)) {
|
||||
return paths;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
|
||||
Resource[] found = rpr.getResources("/WEB-INF/*.xml");
|
||||
Set<String> foundPaths = new HashSet<String>();
|
||||
for (int i = 0; i < found.length; i++) {
|
||||
foundPaths.add(((ServletContextResource) found[i]).getPath());
|
||||
}
|
||||
assertEquals(2, foundPaths.size());
|
||||
assertTrue(foundPaths.contains("/WEB-INF/context1.xml"));
|
||||
assertTrue(foundPaths.contains("/WEB-INF/context2.xml"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextResourcePatternResolverWithPatternPath() throws IOException {
|
||||
final Set<String> dirs = new HashSet<String>();
|
||||
dirs.add("/WEB-INF/mydir1/");
|
||||
dirs.add("/WEB-INF/mydir2/");
|
||||
|
||||
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
if ("/WEB-INF/".equals(path)) {
|
||||
return dirs;
|
||||
}
|
||||
if ("/WEB-INF/mydir1/".equals(path)) {
|
||||
return Collections.singleton("/WEB-INF/mydir1/context1.xml");
|
||||
}
|
||||
if ("/WEB-INF/mydir2/".equals(path)) {
|
||||
return Collections.singleton("/WEB-INF/mydir2/context2.xml");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
|
||||
Resource[] found = rpr.getResources("/WEB-INF/*/*.xml");
|
||||
Set<String> foundPaths = new HashSet<String>();
|
||||
for (int i = 0; i < found.length; i++) {
|
||||
foundPaths.add(((ServletContextResource) found[i]).getPath());
|
||||
}
|
||||
assertEquals(2, foundPaths.size());
|
||||
assertTrue(foundPaths.contains("/WEB-INF/mydir1/context1.xml"));
|
||||
assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextResourcePatternResolverWithUnboundedPatternPath() throws IOException {
|
||||
final Set<String> dirs = new HashSet<String>();
|
||||
dirs.add("/WEB-INF/mydir1/");
|
||||
dirs.add("/WEB-INF/mydir2/");
|
||||
|
||||
final Set<String> paths = new HashSet<String>();
|
||||
paths.add("/WEB-INF/mydir2/context2.xml");
|
||||
paths.add("/WEB-INF/mydir2/mydir3/");
|
||||
|
||||
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
if ("/WEB-INF/".equals(path)) {
|
||||
return dirs;
|
||||
}
|
||||
if ("/WEB-INF/mydir1/".equals(path)) {
|
||||
return Collections.singleton("/WEB-INF/mydir1/context1.xml");
|
||||
}
|
||||
if ("/WEB-INF/mydir2/".equals(path)) {
|
||||
return paths;
|
||||
}
|
||||
if ("/WEB-INF/mydir2/mydir3/".equals(path)) {
|
||||
return Collections.singleton("/WEB-INF/mydir2/mydir3/context3.xml");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
|
||||
Resource[] found = rpr.getResources("/WEB-INF/**/*.xml");
|
||||
Set<String> foundPaths = new HashSet<String>();
|
||||
for (int i = 0; i < found.length; i++) {
|
||||
foundPaths.add(((ServletContextResource) found[i]).getPath());
|
||||
}
|
||||
assertEquals(3, foundPaths.size());
|
||||
assertTrue(foundPaths.contains("/WEB-INF/mydir1/context1.xml"));
|
||||
assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml"));
|
||||
assertTrue(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServletContextResourcePatternResolverWithAbsolutePaths() throws IOException {
|
||||
final Set<String> paths = new HashSet<String>();
|
||||
paths.add("C:/webroot/WEB-INF/context1.xml");
|
||||
paths.add("C:/webroot/WEB-INF/context2.xml");
|
||||
paths.add("C:/webroot/someOtherDirThatDoesntContainPath");
|
||||
|
||||
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
|
||||
public Set<String> getResourcePaths(String path) {
|
||||
if ("/WEB-INF/".equals(path)) {
|
||||
return paths;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
|
||||
Resource[] found = rpr.getResources("/WEB-INF/*.xml");
|
||||
Set<String> foundPaths = new HashSet<String>();
|
||||
for (int i = 0; i < found.length; i++) {
|
||||
foundPaths.add(((ServletContextResource) found[i]).getPath());
|
||||
}
|
||||
assertEquals(2, foundPaths.size());
|
||||
assertTrue(foundPaths.contains("/WEB-INF/context1.xml"));
|
||||
assertTrue(foundPaths.contains("/WEB-INF/context2.xml"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.web.context.support;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @author Chris Beams
|
||||
* @since 28.08.2003
|
||||
*/
|
||||
public class WebApplicationObjectSupportTests {
|
||||
|
||||
@Test
|
||||
public void testWebApplicationObjectSupport() {
|
||||
StaticWebApplicationContext wac = new StaticWebApplicationContext();
|
||||
wac.setServletContext(new MockServletContext());
|
||||
File tempDir = new File("");
|
||||
wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, tempDir);
|
||||
wac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class));
|
||||
wac.refresh();
|
||||
WebApplicationObjectSupport wao = (WebApplicationObjectSupport) wac.getBean("test");
|
||||
assertEquals(wao.getServletContext(), wac.getServletContext());
|
||||
assertEquals(wao.getTempDir(), tempDir);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWebApplicationObjectSupportWithWrongContext() {
|
||||
StaticApplicationContext ac = new StaticApplicationContext();
|
||||
ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class));
|
||||
WebApplicationObjectSupport wao = (WebApplicationObjectSupport) ac.getBean("test");
|
||||
try {
|
||||
wao.getWebApplicationContext();
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class TestWebApplicationObject extends WebApplicationObjectSupport {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
import org.springframework.beans.factory.support.ManagedList;
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.context.support.ApplicationObjectSupport;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.web.bind.ServletRequestBindingException;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.context.request.WebRequestInterceptor;
|
||||
import org.springframework.web.context.support.RequestHandledEvent;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
|
||||
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
|
||||
import org.springframework.web.servlet.handler.SimpleServletHandlerAdapter;
|
||||
import org.springframework.web.servlet.handler.SimpleServletPostProcessor;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
import org.springframework.web.servlet.mvc.Controller;
|
||||
import org.springframework.web.servlet.mvc.ParameterizableViewController;
|
||||
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.SimpleFormController;
|
||||
import org.springframework.web.servlet.support.RequestContextUtils;
|
||||
import org.springframework.web.servlet.theme.SessionThemeResolver;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 21.05.2003
|
||||
*/
|
||||
public class ComplexWebApplicationContext extends StaticWebApplicationContext {
|
||||
|
||||
public void refresh() throws BeansException {
|
||||
registerSingleton(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, SessionLocaleResolver.class);
|
||||
registerSingleton(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, SessionThemeResolver.class);
|
||||
|
||||
LocaleChangeInterceptor interceptor1 = new LocaleChangeInterceptor();
|
||||
LocaleChangeInterceptor interceptor2 = new LocaleChangeInterceptor();
|
||||
interceptor2.setParamName("locale2");
|
||||
ThemeChangeInterceptor interceptor3 = new ThemeChangeInterceptor();
|
||||
ThemeChangeInterceptor interceptor4 = new ThemeChangeInterceptor();
|
||||
interceptor4.setParamName("theme2");
|
||||
UserRoleAuthorizationInterceptor interceptor5 = new UserRoleAuthorizationInterceptor();
|
||||
interceptor5.setAuthorizedRoles(new String[] {"role1", "role2"});
|
||||
|
||||
List interceptors = new ArrayList();
|
||||
interceptors.add(interceptor5);
|
||||
interceptors.add(interceptor1);
|
||||
interceptors.add(interceptor2);
|
||||
interceptors.add(interceptor3);
|
||||
interceptors.add(interceptor4);
|
||||
interceptors.add(new MyHandlerInterceptor1());
|
||||
interceptors.add(new MyHandlerInterceptor2());
|
||||
interceptors.add(new MyWebRequestInterceptor());
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add(
|
||||
"mappings", "/view.do=viewHandler\n/locale.do=localeHandler\nloc.do=anotherLocaleHandler");
|
||||
pvs.add("interceptors", interceptors);
|
||||
registerSingleton("myUrlMapping1", SimpleUrlHandlerMapping.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add(
|
||||
"mappings", "/form.do=localeHandler\n/unknown.do=unknownHandler\nservlet.do=myServlet");
|
||||
pvs.add("order", "2");
|
||||
registerSingleton("myUrlMapping2", SimpleUrlHandlerMapping.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add(
|
||||
"mappings", "/form.do=formHandler\n/head.do=headController\n" +
|
||||
"body.do=bodyController\n/noview*=noviewController\n/noview/simple*=noviewController");
|
||||
pvs.add("order", "1");
|
||||
registerSingleton("handlerMapping", SimpleUrlHandlerMapping.class, pvs);
|
||||
|
||||
registerSingleton("myDummyAdapter", MyDummyAdapter.class);
|
||||
registerSingleton("myHandlerAdapter", MyHandlerAdapter.class);
|
||||
registerSingleton("standardHandlerAdapter", SimpleControllerHandlerAdapter.class);
|
||||
registerSingleton("noviewController", NoViewController.class);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("order", new Integer(0));
|
||||
pvs.add("basename", "org.springframework.web.servlet.complexviews");
|
||||
registerSingleton("viewResolver", ResourceBundleViewResolver.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("suffix", ".jsp");
|
||||
registerSingleton("viewResolver2", InternalResourceViewResolver.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("commandClass", "org.springframework.beans.TestBean");
|
||||
pvs.add("formView", "form");
|
||||
registerSingleton("formHandler", SimpleFormController.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("viewName", "form");
|
||||
registerSingleton("viewHandler", ParameterizableViewController.class, pvs);
|
||||
|
||||
registerSingleton("localeHandler", ComplexLocaleChecker.class);
|
||||
registerSingleton("anotherLocaleHandler", ComplexLocaleChecker.class);
|
||||
registerSingleton("unknownHandler", Object.class);
|
||||
|
||||
registerSingleton("headController", HeadController.class);
|
||||
registerSingleton("bodyController", BodyController.class);
|
||||
|
||||
registerSingleton("servletPostProcessor", SimpleServletPostProcessor.class);
|
||||
registerSingleton("handlerAdapter", SimpleServletHandlerAdapter.class);
|
||||
registerSingleton("myServlet", MyServlet.class);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("order", "1");
|
||||
pvs.add("exceptionMappings",
|
||||
"java.lang.IllegalAccessException=failed2\n" +
|
||||
"ServletRequestBindingException=failed3");
|
||||
pvs.add("defaultErrorView", "failed0");
|
||||
registerSingleton("exceptionResolver1", SimpleMappingExceptionResolver.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("order", "0");
|
||||
pvs.add("exceptionMappings", "java.lang.Exception=failed1");
|
||||
List mappedHandlers = new ManagedList();
|
||||
mappedHandlers.add(new RuntimeBeanReference("anotherLocaleHandler"));
|
||||
pvs.add("mappedHandlers", mappedHandlers);
|
||||
pvs.add("defaultStatusCode", "500");
|
||||
pvs.add("defaultErrorView", "failed2");
|
||||
registerSingleton("handlerExceptionResolver", SimpleMappingExceptionResolver.class, pvs);
|
||||
|
||||
registerSingleton("multipartResolver", MockMultipartResolver.class);
|
||||
registerSingleton("testListener", TestApplicationListener.class);
|
||||
|
||||
addMessage("test", Locale.ENGLISH, "test message");
|
||||
addMessage("test", Locale.CANADA, "Canadian & test message");
|
||||
|
||||
super.refresh();
|
||||
}
|
||||
|
||||
|
||||
public static class HeadController implements Controller {
|
||||
|
||||
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
if ("HEAD".equals(request.getMethod())) {
|
||||
response.setContentLength(5);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class BodyController implements Controller {
|
||||
|
||||
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
response.getOutputStream().write("body".getBytes());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class NoViewController implements Controller {
|
||||
|
||||
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return new ModelAndView();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MyServlet implements Servlet {
|
||||
|
||||
private ServletConfig servletConfig;
|
||||
|
||||
public void init(ServletConfig servletConfig) throws ServletException {
|
||||
this.servletConfig = servletConfig;
|
||||
}
|
||||
|
||||
public ServletConfig getServletConfig() {
|
||||
return servletConfig;
|
||||
}
|
||||
|
||||
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
|
||||
servletResponse.getOutputStream().write("body".getBytes());
|
||||
}
|
||||
|
||||
public String getServletInfo() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
this.servletConfig = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static interface MyHandler {
|
||||
|
||||
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException;
|
||||
|
||||
public long lastModified();
|
||||
}
|
||||
|
||||
|
||||
public static class MyHandlerAdapter extends ApplicationObjectSupport implements HandlerAdapter, Ordered {
|
||||
|
||||
public int getOrder() {
|
||||
return 99;
|
||||
}
|
||||
|
||||
public boolean supports(Object handler) {
|
||||
return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
|
||||
}
|
||||
|
||||
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object delegate)
|
||||
throws ServletException, IllegalAccessException {
|
||||
((MyHandler) delegate).doSomething(request);
|
||||
return null;
|
||||
}
|
||||
|
||||
public long getLastModified(HttpServletRequest request, Object delegate) {
|
||||
return ((MyHandler) delegate).lastModified();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MyDummyAdapter extends ApplicationObjectSupport implements HandlerAdapter {
|
||||
|
||||
public boolean supports(Object handler) {
|
||||
return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
|
||||
}
|
||||
|
||||
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object delegate)
|
||||
throws IOException, ServletException {
|
||||
throw new ServletException("dummy");
|
||||
}
|
||||
|
||||
public long getLastModified(HttpServletRequest request, Object delegate) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MyHandlerInterceptor1 implements HandlerInterceptor {
|
||||
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
|
||||
throws ServletException {
|
||||
if (request.getAttribute("test2") != null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
request.setAttribute("test1", "test1");
|
||||
request.setAttribute("test1x", "test1x");
|
||||
request.setAttribute("test1y", "test1y");
|
||||
return true;
|
||||
}
|
||||
|
||||
public void postHandle(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
|
||||
throws ServletException {
|
||||
if (request.getAttribute("test2x") != null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
if (!"test1x".equals(request.getAttribute("test1x"))) {
|
||||
throw new ServletException("Incorrect request attribute");
|
||||
}
|
||||
request.removeAttribute("test1x");
|
||||
}
|
||||
|
||||
public void afterCompletion(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
|
||||
throws ServletException {
|
||||
if (request.getAttribute("test2y") != null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
request.removeAttribute("test1y");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MyHandlerInterceptor2 implements HandlerInterceptor {
|
||||
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
|
||||
throws ServletException {
|
||||
if (request.getAttribute("test1x") == null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
if (request.getParameter("abort") != null) {
|
||||
return false;
|
||||
}
|
||||
request.setAttribute("test2", "test2");
|
||||
request.setAttribute("test2x", "test2x");
|
||||
request.setAttribute("test2y", "test2y");
|
||||
return true;
|
||||
}
|
||||
|
||||
public void postHandle(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
|
||||
throws ServletException {
|
||||
if (request.getParameter("noView") != null) {
|
||||
modelAndView.clear();
|
||||
}
|
||||
if (request.getAttribute("test1x") == null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
if (!"test2x".equals(request.getAttribute("test2x"))) {
|
||||
throw new ServletException("Incorrect request attribute");
|
||||
}
|
||||
request.removeAttribute("test2x");
|
||||
}
|
||||
|
||||
public void afterCompletion(
|
||||
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
|
||||
throws Exception {
|
||||
if (request.getAttribute("test1y") == null) {
|
||||
throw new ServletException("Wrong interceptor order");
|
||||
}
|
||||
request.removeAttribute("test2y");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MyWebRequestInterceptor implements WebRequestInterceptor {
|
||||
|
||||
public void preHandle(WebRequest request) throws Exception {
|
||||
request.setAttribute("test3", "test3", WebRequest.SCOPE_REQUEST);
|
||||
}
|
||||
|
||||
public void postHandle(WebRequest request, ModelMap model) throws Exception {
|
||||
request.setAttribute("test3x", "test3x", WebRequest.SCOPE_REQUEST);
|
||||
}
|
||||
|
||||
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
|
||||
request.setAttribute("test3y", "test3y", WebRequest.SCOPE_REQUEST);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class ComplexLocaleChecker implements MyHandler {
|
||||
|
||||
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
|
||||
WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
|
||||
if (!(wac instanceof ComplexWebApplicationContext)) {
|
||||
throw new ServletException("Incorrect WebApplicationContext");
|
||||
}
|
||||
if (!(request instanceof MultipartHttpServletRequest)) {
|
||||
throw new ServletException("Not in a MultipartHttpServletRequest");
|
||||
}
|
||||
if (!(RequestContextUtils.getLocaleResolver(request) instanceof SessionLocaleResolver)) {
|
||||
throw new ServletException("Incorrect LocaleResolver");
|
||||
}
|
||||
if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
|
||||
throw new ServletException("Incorrect Locale");
|
||||
}
|
||||
if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
|
||||
throw new ServletException("Incorrect Locale");
|
||||
}
|
||||
if (!(RequestContextUtils.getThemeResolver(request) instanceof SessionThemeResolver)) {
|
||||
throw new ServletException("Incorrect ThemeResolver");
|
||||
}
|
||||
if (!"theme".equals(RequestContextUtils.getThemeResolver(request).resolveThemeName(request))) {
|
||||
throw new ServletException("Incorrect theme name");
|
||||
}
|
||||
if (request.getParameter("fail") != null) {
|
||||
throw new ModelAndViewDefiningException(new ModelAndView("failed1"));
|
||||
}
|
||||
if (request.getParameter("access") != null) {
|
||||
throw new IllegalAccessException("illegal access");
|
||||
}
|
||||
if (request.getParameter("servlet") != null) {
|
||||
throw new ServletRequestBindingException("servlet");
|
||||
}
|
||||
if (request.getParameter("exception") != null) {
|
||||
throw new RuntimeException("servlet");
|
||||
}
|
||||
}
|
||||
|
||||
public long lastModified() {
|
||||
return 99;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class MockMultipartResolver implements MultipartResolver {
|
||||
|
||||
public boolean isMultipart(HttpServletRequest request) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
|
||||
if (request.getAttribute("fail") != null) {
|
||||
throw new MaxUploadSizeExceededException(1000);
|
||||
}
|
||||
if (request instanceof MultipartHttpServletRequest) {
|
||||
throw new IllegalStateException("Already a multipart request");
|
||||
}
|
||||
if (request.getAttribute("resolved") != null) {
|
||||
throw new IllegalStateException("Already resolved");
|
||||
}
|
||||
request.setAttribute("resolved", Boolean.TRUE);
|
||||
return new AbstractMultipartHttpServletRequest(request) {
|
||||
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
|
||||
return null;
|
||||
}
|
||||
public String getMultipartContentType(String paramOrFileName) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void cleanupMultipart(MultipartHttpServletRequest request) {
|
||||
if (request.getAttribute("cleanedUp") != null) {
|
||||
throw new IllegalStateException("Already cleaned up");
|
||||
}
|
||||
request.setAttribute("cleanedUp", Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class TestApplicationListener implements ApplicationListener {
|
||||
|
||||
public int counter = 0;
|
||||
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
if (event instanceof RequestHandledEvent) {
|
||||
this.counter++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,834 @@
|
||||
/*
|
||||
* Copyright 2002-2010 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.web.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import javax.servlet.Servlet;
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import junit.framework.Assert;
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.beans.PropertyValue;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletConfig;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.bind.EscapedErrors;
|
||||
import org.springframework.web.context.ServletConfigAwareBean;
|
||||
import org.springframework.web.context.ServletContextAwareBean;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
import org.springframework.web.multipart.MultipartResolver;
|
||||
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.mvc.BaseCommandController;
|
||||
import org.springframework.web.servlet.mvc.Controller;
|
||||
import org.springframework.web.servlet.support.RequestContext;
|
||||
import org.springframework.web.servlet.support.RequestContextUtils;
|
||||
import org.springframework.web.servlet.theme.AbstractThemeResolver;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class DispatcherServletTests extends TestCase {
|
||||
|
||||
private static final String URL_KNOWN_ONLY_PARENT = "/knownOnlyToParent.do";
|
||||
|
||||
private MockServletConfig servletConfig;
|
||||
|
||||
private DispatcherServlet simpleDispatcherServlet;
|
||||
|
||||
private DispatcherServlet complexDispatcherServlet;
|
||||
|
||||
protected void setUp() throws ServletException {
|
||||
servletConfig = new MockServletConfig(new MockServletContext(), "simple");
|
||||
MockServletConfig complexConfig = new MockServletConfig(servletConfig.getServletContext(), "complex");
|
||||
complexConfig.addInitParameter("publishContext", "false");
|
||||
complexConfig.addInitParameter("class", "notWritable");
|
||||
complexConfig.addInitParameter("unknownParam", "someValue");
|
||||
|
||||
simpleDispatcherServlet = new DispatcherServlet();
|
||||
simpleDispatcherServlet.setContextClass(SimpleWebApplicationContext.class);
|
||||
simpleDispatcherServlet.init(servletConfig);
|
||||
|
||||
complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.addRequiredProperty("publishContext");
|
||||
complexDispatcherServlet.init(complexConfig);
|
||||
}
|
||||
|
||||
private ServletContext getServletContext() {
|
||||
return servletConfig.getServletContext();
|
||||
}
|
||||
|
||||
public void testDispatcherServletGetServletNameDoesNotFailWithoutConfig() {
|
||||
DispatcherServlet ds = new DispatcherServlet();
|
||||
assertNull(ds.getServletConfig());
|
||||
assertNull(ds.getServletName());
|
||||
assertNull(ds.getServletContext());
|
||||
}
|
||||
|
||||
public void testConfiguredDispatcherServlets() {
|
||||
assertTrue("Correct namespace",
|
||||
("simple" + FrameworkServlet.DEFAULT_NAMESPACE_SUFFIX).equals(simpleDispatcherServlet.getNamespace()));
|
||||
assertTrue("Correct attribute", (FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple").equals(
|
||||
simpleDispatcherServlet.getServletContextAttributeName()));
|
||||
assertTrue("Context published", simpleDispatcherServlet.getWebApplicationContext() ==
|
||||
getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple"));
|
||||
|
||||
assertTrue("Correct namespace", "test".equals(complexDispatcherServlet.getNamespace()));
|
||||
assertTrue("Correct attribute", (FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex").equals(
|
||||
complexDispatcherServlet.getServletContextAttributeName()));
|
||||
assertTrue("Context not published",
|
||||
getServletContext().getAttribute(FrameworkServlet.SERVLET_CONTEXT_PREFIX + "complex") == null);
|
||||
|
||||
simpleDispatcherServlet.destroy();
|
||||
complexDispatcherServlet.destroy();
|
||||
}
|
||||
|
||||
public void testInvalidRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/invalid.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
assertTrue("correct error code", response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
|
||||
}
|
||||
|
||||
public void testRequestHandledEvent() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
ComplexWebApplicationContext.TestApplicationListener listener =
|
||||
(ComplexWebApplicationContext.TestApplicationListener) complexDispatcherServlet
|
||||
.getWebApplicationContext().getBean("testListener");
|
||||
Assert.assertEquals(1, listener.counter);
|
||||
}
|
||||
|
||||
public void testPublishEventsOff() throws Exception {
|
||||
complexDispatcherServlet.setPublishEvents(false);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
ComplexWebApplicationContext.TestApplicationListener listener =
|
||||
(ComplexWebApplicationContext.TestApplicationListener) complexDispatcherServlet
|
||||
.getWebApplicationContext().getBean("testListener");
|
||||
Assert.assertEquals(0, listener.counter);
|
||||
}
|
||||
|
||||
public void testFormRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "form".equals(response.getForwardedUrl()));
|
||||
DefaultMessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[]{"test"});
|
||||
RequestContext rc = new RequestContext(request);
|
||||
|
||||
assertTrue("hasn't RequestContext attribute", request.getAttribute("rc") == null);
|
||||
assertTrue("Correct WebApplicationContext",
|
||||
RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext);
|
||||
assertTrue("Correct context path", rc.getContextPath().equals(request.getContextPath()));
|
||||
assertTrue("Correct locale", Locale.CANADA.equals(RequestContextUtils.getLocale(request)));
|
||||
assertTrue("Correct theme", AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(
|
||||
RequestContextUtils.getTheme(request).getName()));
|
||||
assertTrue("Correct message", "Canadian & test message".equals(rc.getMessage("test")));
|
||||
|
||||
assertTrue("Correct WebApplicationContext",
|
||||
rc.getWebApplicationContext() == simpleDispatcherServlet.getWebApplicationContext());
|
||||
assertTrue("Correct Errors",
|
||||
!(rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME) instanceof EscapedErrors));
|
||||
assertTrue("Correct Errors",
|
||||
!(rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, false) instanceof EscapedErrors));
|
||||
assertTrue("Correct Errors",
|
||||
rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, true) instanceof EscapedErrors);
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test"));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, true));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, true));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", "default"));
|
||||
assertEquals("Correct message", "default", rc.getMessage("testa", "default"));
|
||||
assertEquals("Correct message", "default &", rc.getMessage("testa", null, "default &", true));
|
||||
}
|
||||
|
||||
public void testParameterizableViewController() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/view.do");
|
||||
request.addUserRole("role1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "myform.jsp".equals(response.getForwardedUrl()));
|
||||
}
|
||||
|
||||
public void testHandlerInterceptorSuppressesView() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/view.do");
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("noView", "true");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
}
|
||||
|
||||
public void testLocaleRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
assertEquals("98", response.getHeader("Last-Modified"));
|
||||
}
|
||||
|
||||
public void testUnknownRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
|
||||
}
|
||||
|
||||
public void testAnotherFormRequest() throws Exception {
|
||||
MockHttpServletRequest request =
|
||||
new MockHttpServletRequest(getServletContext(), "GET", "/form.do;jsessionid=xxx");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "myform.jsp".equals(response.getForwardedUrl()));
|
||||
assertTrue("has RequestContext attribute", request.getAttribute("rc") != null);
|
||||
DefaultMessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[]{"test"});
|
||||
|
||||
RequestContext rc = (RequestContext) request.getAttribute("rc");
|
||||
assertTrue("Not in HTML escaping mode", !rc.isDefaultHtmlEscape());
|
||||
assertTrue("Correct WebApplicationContext",
|
||||
rc.getWebApplicationContext() == complexDispatcherServlet.getWebApplicationContext());
|
||||
assertTrue("Correct context path", rc.getContextPath().equals(request.getContextPath()));
|
||||
assertTrue("Correct locale", Locale.CANADA.equals(rc.getLocale()));
|
||||
assertTrue("Correct Errors",
|
||||
!(rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME) instanceof EscapedErrors));
|
||||
assertTrue("Correct Errors",
|
||||
!(rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, false) instanceof EscapedErrors));
|
||||
assertTrue("Correct Errors",
|
||||
rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, true) instanceof EscapedErrors);
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test"));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, true));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, true));
|
||||
|
||||
rc.setDefaultHtmlEscape(true);
|
||||
assertTrue("Is in HTML escaping mode", rc.isDefaultHtmlEscape());
|
||||
assertTrue("Correct Errors", rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME) instanceof EscapedErrors);
|
||||
assertTrue("Correct Errors",
|
||||
!(rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, false) instanceof EscapedErrors));
|
||||
assertTrue("Correct Errors",
|
||||
rc.getErrors(BaseCommandController.DEFAULT_COMMAND_NAME, true) instanceof EscapedErrors);
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test"));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage("test", null, true));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, false));
|
||||
assertEquals("Correct message", "Canadian & test message", rc.getMessage(resolvable, true));
|
||||
}
|
||||
|
||||
public void testAnotherLocaleRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
assertTrue(request.getAttribute("test1") != null);
|
||||
assertTrue(request.getAttribute("test1x") == null);
|
||||
assertTrue(request.getAttribute("test1y") == null);
|
||||
assertTrue(request.getAttribute("test2") != null);
|
||||
assertTrue(request.getAttribute("test2x") == null);
|
||||
assertTrue(request.getAttribute("test2y") == null);
|
||||
assertTrue(request.getAttribute("test3") != null);
|
||||
assertTrue(request.getAttribute("test3x") != null);
|
||||
assertTrue(request.getAttribute("test3y") != null);
|
||||
assertEquals("99", response.getHeader("Last-Modified"));
|
||||
}
|
||||
|
||||
public void testExistingMultipartRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ComplexWebApplicationContext.MockMultipartResolver multipartResolver =
|
||||
(ComplexWebApplicationContext.MockMultipartResolver) complexDispatcherServlet.getWebApplicationContext()
|
||||
.getBean("multipartResolver");
|
||||
MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request);
|
||||
complexDispatcherServlet.service(multipartRequest, response);
|
||||
multipartResolver.cleanupMultipart(multipartRequest);
|
||||
assertNotNull(request.getAttribute("cleanedUp"));
|
||||
}
|
||||
|
||||
public void testMultipartResolutionFailed() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.setAttribute("fail", Boolean.TRUE);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to failed", "failed0.jsp".equals(response.getForwardedUrl()));
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue("correct exception", request.getAttribute(
|
||||
SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException);
|
||||
}
|
||||
|
||||
public void testHandlerInterceptorAbort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addParameter("abort", "true");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
assertTrue(request.getAttribute("test1") != null);
|
||||
assertTrue(request.getAttribute("test1x") != null);
|
||||
assertTrue(request.getAttribute("test1y") == null);
|
||||
assertTrue(request.getAttribute("test2") == null);
|
||||
assertTrue(request.getAttribute("test2x") == null);
|
||||
assertTrue(request.getAttribute("test2y") == null);
|
||||
}
|
||||
|
||||
public void testModelAndViewDefiningException() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("fail", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl()));
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
fail("Should not have thrown ServletException: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testSimpleMappingExceptionResolverWithSpecificHandler1() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("access", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed2.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException);
|
||||
}
|
||||
|
||||
public void testSimpleMappingExceptionResolverWithSpecificHandler2() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("servlet", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed3.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException);
|
||||
}
|
||||
|
||||
public void testSimpleMappingExceptionResolverWithAllHandlers1() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/loc.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("access", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed1.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException);
|
||||
}
|
||||
|
||||
public void testSimpleMappingExceptionResolverWithAllHandlers2() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/loc.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("servlet", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed1.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException);
|
||||
}
|
||||
|
||||
public void testSimpleMappingExceptionResolverWithDefaultErrorView() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("exception", "yes");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(RuntimeException.class));
|
||||
}
|
||||
|
||||
public void testLocaleChangeInterceptor1() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.GERMAN);
|
||||
request.addUserRole("role2");
|
||||
request.addParameter("locale", "en");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
|
||||
}
|
||||
|
||||
public void testLocaleChangeInterceptor2() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.GERMAN);
|
||||
request.addUserRole("role2");
|
||||
request.addParameter("locale", "en");
|
||||
request.addParameter("locale2", "en_CA");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
}
|
||||
|
||||
public void testThemeChangeInterceptor1() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("theme", "mytheme");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
|
||||
}
|
||||
|
||||
public void testThemeChangeInterceptor2() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
request.addUserRole("role1");
|
||||
request.addParameter("theme", "mytheme");
|
||||
request.addParameter("theme2", "theme");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("Not forwarded", response.getForwardedUrl() == null);
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
fail("Should not have thrown ServletException: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testNotAuthorized() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
|
||||
request.addPreferredLocale(Locale.CANADA);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("Correct response", response.getStatus() == HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
fail("Should not have thrown ServletException: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testHeadMethodWithExplicitHandling() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/head.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(5, response.getContentLength());
|
||||
|
||||
request = new MockHttpServletRequest(getServletContext(), "GET", "/head.do");
|
||||
response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("", response.getContentAsString());
|
||||
}
|
||||
|
||||
public void testHeadMethodWithNoBodyResponse() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/body.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(4, response.getContentLength());
|
||||
|
||||
request = new MockHttpServletRequest(getServletContext(), "GET", "/body.do");
|
||||
response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("body", response.getContentAsString());
|
||||
}
|
||||
|
||||
public void testNotDetectAllHandlerMappings() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.setDetectAllHandlerMappings(false);
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue(response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
|
||||
}
|
||||
|
||||
public void testHandlerNotMappedWithAutodetect() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
// no parent
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", URL_KNOWN_ONLY_PARENT);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
|
||||
}
|
||||
|
||||
public void testDetectHandlerMappingFromParent() throws ServletException, IOException {
|
||||
// create a parent context that includes a mapping
|
||||
StaticWebApplicationContext parent = new StaticWebApplicationContext();
|
||||
parent.setServletContext(servletConfig.getServletContext());
|
||||
parent.registerSingleton("parentHandler", ControllerFromParent.class, new MutablePropertyValues());
|
||||
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.addPropertyValue(new PropertyValue("mappings", URL_KNOWN_ONLY_PARENT + "=parentHandler"));
|
||||
|
||||
parent.registerSingleton("parentMapping", SimpleUrlHandlerMapping.class, pvs);
|
||||
parent.refresh();
|
||||
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
// will have parent
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
|
||||
ServletConfig config = new MockServletConfig(getServletContext(), "complex");
|
||||
config.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, parent);
|
||||
complexDispatcherServlet.init(config);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", URL_KNOWN_ONLY_PARENT);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
|
||||
assertFalse("Matched through parent controller/handler pair: not response=" + response.getStatus(),
|
||||
response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
|
||||
}
|
||||
|
||||
public void testDetectAllHandlerAdapters() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("body", response.getContentAsString());
|
||||
|
||||
request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do");
|
||||
response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "myform.jsp".equals(response.getForwardedUrl()));
|
||||
}
|
||||
|
||||
public void testNotDetectAllHandlerAdapters() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.setDetectAllHandlerAdapters(false);
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
// only ServletHandlerAdapter with bean name "handlerAdapter" detected
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("body", response.getContentAsString());
|
||||
|
||||
// SimpleControllerHandlerAdapter not detected
|
||||
request = new MockHttpServletRequest(getServletContext(), "GET", "/form.do");
|
||||
response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("forwarded to failed", "failed0.jsp", response.getForwardedUrl());
|
||||
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
|
||||
}
|
||||
|
||||
public void testNotDetectAllHandlerExceptionResolvers() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.setDetectAllHandlerExceptionResolvers(false);
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
fail("Should have thrown ServletException");
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getMessage().indexOf("No adapter for handler") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
public void testNotDetectAllViewResolvers() throws ServletException, IOException {
|
||||
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
|
||||
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
|
||||
complexDispatcherServlet.setNamespace("test");
|
||||
complexDispatcherServlet.setDetectAllViewResolvers(false);
|
||||
complexDispatcherServlet.init(new MockServletConfig(getServletContext(), "complex"));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
fail("Should have thrown ServletException");
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
// expected
|
||||
assertTrue(ex.getMessage().indexOf("failed0") != -1);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCleanupAfterIncludeWithRemove() throws ServletException, IOException {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setAttribute("test1", "value1");
|
||||
request.setAttribute("test2", "value2");
|
||||
WebApplicationContext wac = new StaticWebApplicationContext();
|
||||
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
|
||||
request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "form".equals(response.getIncludedUrl()));
|
||||
|
||||
assertEquals("value1", request.getAttribute("test1"));
|
||||
assertEquals("value2", request.getAttribute("test2"));
|
||||
assertEquals(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
|
||||
assertNull(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
assertNull(request.getAttribute("command"));
|
||||
}
|
||||
|
||||
public void testCleanupAfterIncludeWithRestore() throws ServletException, IOException {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setAttribute("test1", "value1");
|
||||
request.setAttribute("test2", "value2");
|
||||
WebApplicationContext wac = new StaticWebApplicationContext();
|
||||
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
TestBean command = new TestBean();
|
||||
request.setAttribute("command", command);
|
||||
|
||||
request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "form".equals(response.getIncludedUrl()));
|
||||
|
||||
assertEquals("value1", request.getAttribute("test1"));
|
||||
assertEquals("value2", request.getAttribute("test2"));
|
||||
assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
|
||||
assertSame(command, request.getAttribute("command"));
|
||||
}
|
||||
|
||||
public void testNoCleanupAfterInclude() throws ServletException, IOException {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setAttribute("test1", "value1");
|
||||
request.setAttribute("test2", "value2");
|
||||
WebApplicationContext wac = new StaticWebApplicationContext();
|
||||
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
|
||||
TestBean command = new TestBean();
|
||||
request.setAttribute("command", command);
|
||||
|
||||
request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
|
||||
simpleDispatcherServlet.setCleanupAfterInclude(false);
|
||||
simpleDispatcherServlet.service(request, response);
|
||||
assertTrue("forwarded to form", "form".equals(response.getIncludedUrl()));
|
||||
|
||||
assertEquals("value1", request.getAttribute("test1"));
|
||||
assertEquals("value2", request.getAttribute("test2"));
|
||||
assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
|
||||
assertNotSame(command, request.getAttribute("command"));
|
||||
}
|
||||
|
||||
public void testServletHandlerAdapter() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("body", response.getContentAsString());
|
||||
|
||||
Servlet myServlet = (Servlet) complexDispatcherServlet.getWebApplicationContext().getBean("myServlet");
|
||||
assertEquals("complex", myServlet.getServletConfig().getServletName());
|
||||
assertEquals(getServletContext(), myServlet.getServletConfig().getServletContext());
|
||||
complexDispatcherServlet.destroy();
|
||||
assertNull(myServlet.getServletConfig());
|
||||
}
|
||||
|
||||
public void testWebApplicationContextLookup() {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/invalid.do");
|
||||
|
||||
try {
|
||||
RequestContextUtils.getWebApplicationContext(request);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
try {
|
||||
RequestContextUtils.getWebApplicationContext(request, servletContext);
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
|
||||
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
|
||||
new StaticWebApplicationContext());
|
||||
try {
|
||||
RequestContextUtils.getWebApplicationContext(request, servletContext);
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
fail("Should not have thrown IllegalStateException: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testWithNoView() throws Exception {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("noview.jsp", response.getForwardedUrl());
|
||||
}
|
||||
|
||||
public void testWithNoViewNested() throws Exception {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview/simple.do");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
complexDispatcherServlet.service(request, response);
|
||||
assertEquals("noview/simple.jsp", response.getForwardedUrl());
|
||||
}
|
||||
|
||||
public void testWithNoViewAndSamePath() throws Exception {
|
||||
InternalResourceViewResolver vr = (InternalResourceViewResolver) complexDispatcherServlet
|
||||
.getWebApplicationContext().getBean("viewResolver2");
|
||||
vr.setSuffix("");
|
||||
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
try {
|
||||
complexDispatcherServlet.service(request, response);
|
||||
fail("Should have thrown ServletException");
|
||||
}
|
||||
catch (ServletException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void testDispatcherServletRefresh() throws ServletException {
|
||||
MockServletContext servletContext = new MockServletContext("org/springframework/web/context");
|
||||
DispatcherServlet servlet = new DispatcherServlet();
|
||||
|
||||
servlet.init(new MockServletConfig(servletContext, "empty"));
|
||||
ServletContextAwareBean contextBean =
|
||||
(ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean");
|
||||
ServletConfigAwareBean configBean =
|
||||
(ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean");
|
||||
assertSame(servletContext, contextBean.getServletContext());
|
||||
assertSame(servlet.getServletConfig(), configBean.getServletConfig());
|
||||
MultipartResolver multipartResolver = servlet.getMultipartResolver();
|
||||
assertNotNull(multipartResolver);
|
||||
|
||||
servlet.refresh();
|
||||
|
||||
ServletContextAwareBean contextBean2 =
|
||||
(ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean");
|
||||
ServletConfigAwareBean configBean2 =
|
||||
(ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean");
|
||||
assertSame(servletContext, contextBean2.getServletContext());
|
||||
assertSame(servlet.getServletConfig(), configBean2.getServletConfig());
|
||||
assertNotSame(contextBean, contextBean2);
|
||||
assertNotSame(configBean, configBean2);
|
||||
MultipartResolver multipartResolver2 = servlet.getMultipartResolver();
|
||||
assertNotSame(multipartResolver, multipartResolver2);
|
||||
|
||||
servlet.destroy();
|
||||
}
|
||||
|
||||
public void testDispatcherServletContextRefresh() throws ServletException {
|
||||
MockServletContext servletContext = new MockServletContext("org/springframework/web/context");
|
||||
DispatcherServlet servlet = new DispatcherServlet();
|
||||
|
||||
servlet.init(new MockServletConfig(servletContext, "empty"));
|
||||
ServletContextAwareBean contextBean =
|
||||
(ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean");
|
||||
ServletConfigAwareBean configBean =
|
||||
(ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean");
|
||||
assertSame(servletContext, contextBean.getServletContext());
|
||||
assertSame(servlet.getServletConfig(), configBean.getServletConfig());
|
||||
MultipartResolver multipartResolver = servlet.getMultipartResolver();
|
||||
assertNotNull(multipartResolver);
|
||||
|
||||
((ConfigurableApplicationContext) servlet.getWebApplicationContext()).refresh();
|
||||
|
||||
ServletContextAwareBean contextBean2 =
|
||||
(ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean");
|
||||
ServletConfigAwareBean configBean2 =
|
||||
(ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean");
|
||||
assertSame(servletContext, contextBean2.getServletContext());
|
||||
assertSame(servlet.getServletConfig(), configBean2.getServletConfig());
|
||||
assertTrue(contextBean != contextBean2);
|
||||
assertTrue(configBean != configBean2);
|
||||
MultipartResolver multipartResolver2 = servlet.getMultipartResolver();
|
||||
assertTrue(multipartResolver != multipartResolver2);
|
||||
|
||||
servlet.destroy();
|
||||
}
|
||||
|
||||
|
||||
public static class ControllerFromParent implements Controller {
|
||||
|
||||
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
|
||||
return new ModelAndView(ControllerFromParent.class.getName());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
|
||||
/**
|
||||
* Test fixture for {@link FlashMap} tests.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class FlashMapTests {
|
||||
|
||||
@Test
|
||||
public void isExpired() throws InterruptedException {
|
||||
assertFalse(new FlashMap().isExpired());
|
||||
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.startExpirationPeriod(0);
|
||||
Thread.sleep(100);
|
||||
|
||||
assertTrue(flashMap.isExpired());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notExpired() throws InterruptedException {
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.startExpirationPeriod(10);
|
||||
Thread.sleep(100);
|
||||
|
||||
assertFalse(flashMap.isExpired());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void compareTo() {
|
||||
FlashMap flashMap1 = new FlashMap();
|
||||
FlashMap flashMap2 = new FlashMap();
|
||||
assertEquals(0, flashMap1.compareTo(flashMap2));
|
||||
|
||||
flashMap1.setTargetRequestPath("/path1");
|
||||
assertEquals(-1, flashMap1.compareTo(flashMap2));
|
||||
assertEquals(1, flashMap2.compareTo(flashMap1));
|
||||
|
||||
flashMap2.setTargetRequestPath("/path2");
|
||||
assertEquals(0, flashMap1.compareTo(flashMap2));
|
||||
|
||||
flashMap1.addTargetRequestParam("id", "1");
|
||||
assertEquals(-1, flashMap1.compareTo(flashMap2));
|
||||
assertEquals(1, flashMap2.compareTo(flashMap1));
|
||||
|
||||
flashMap2.addTargetRequestParam("id", "2");
|
||||
assertEquals(0, flashMap1.compareTo(flashMap2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTargetRequestParamNullValue() {
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.addTargetRequestParam("text", "abc");
|
||||
flashMap.addTargetRequestParam("empty", " ");
|
||||
flashMap.addTargetRequestParam("null", null);
|
||||
|
||||
assertEquals(1, flashMap.getTargetRequestParams().size());
|
||||
assertEquals("abc", flashMap.getTargetRequestParams().getFirst("text"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTargetRequestParamsNullValue() {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
|
||||
params.add("key", "abc");
|
||||
params.add("key", " ");
|
||||
params.add("key", null);
|
||||
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.addTargetRequestParams(params);
|
||||
|
||||
assertEquals(1, flashMap.getTargetRequestParams().size());
|
||||
assertEquals(1, flashMap.getTargetRequestParams().get("key").size());
|
||||
assertEquals("abc", flashMap.getTargetRequestParams().getFirst("key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTargetRequestParamNullKey() {
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.addTargetRequestParam(" ", "abc");
|
||||
flashMap.addTargetRequestParam(null, "abc");
|
||||
|
||||
assertTrue(flashMap.getTargetRequestParams().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTargetRequestParamsNullKey() {
|
||||
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
|
||||
params.add(" ", "abc");
|
||||
params.add(null, " ");
|
||||
|
||||
FlashMap flashMap = new FlashMap();
|
||||
flashMap.addTargetRequestParams(params);
|
||||
|
||||
assertTrue(flashMap.getTargetRequestParams().isEmpty());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* Copyright 2002-2005 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.web.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.MutablePropertyValues;
|
||||
import org.springframework.context.support.StaticMessageSource;
|
||||
import org.springframework.ui.context.Theme;
|
||||
import org.springframework.ui.context.ThemeSource;
|
||||
import org.springframework.ui.context.support.SimpleTheme;
|
||||
import org.springframework.ui.context.support.UiApplicationContextUtils;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
|
||||
import org.springframework.web.servlet.mvc.Controller;
|
||||
import org.springframework.web.servlet.mvc.LastModified;
|
||||
import org.springframework.web.servlet.mvc.SimpleFormController;
|
||||
import org.springframework.web.servlet.support.RequestContextUtils;
|
||||
import org.springframework.web.servlet.theme.AbstractThemeResolver;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
import org.springframework.web.servlet.view.XmlViewResolver;
|
||||
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 21.05.2003
|
||||
*/
|
||||
public class SimpleWebApplicationContext extends StaticWebApplicationContext {
|
||||
|
||||
public void refresh() throws BeansException {
|
||||
MutablePropertyValues pvs = new MutablePropertyValues();
|
||||
pvs.add("commandClass", "org.springframework.beans.TestBean");
|
||||
pvs.add("formView", "form");
|
||||
registerSingleton("/form.do", SimpleFormController.class, pvs);
|
||||
|
||||
registerSingleton("/locale.do", LocaleChecker.class);
|
||||
|
||||
addMessage("test", Locale.ENGLISH, "test message");
|
||||
addMessage("test", Locale.CANADA, "Canadian & test message");
|
||||
addMessage("testArgs", Locale.ENGLISH, "test {0} message {1}");
|
||||
addMessage("testArgsFormat", Locale.ENGLISH, "test {0} message {1,number,#.##} X");
|
||||
|
||||
registerSingleton(UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME, DummyThemeSource.class);
|
||||
|
||||
registerSingleton("handlerMapping", BeanNameUrlHandlerMapping.class);
|
||||
registerSingleton("viewResolver", InternalResourceViewResolver.class);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.add("location", "org/springframework/web/context/WEB-INF/sessionContext.xml");
|
||||
registerSingleton("viewResolver2", XmlViewResolver.class, pvs);
|
||||
|
||||
super.refresh();
|
||||
}
|
||||
|
||||
|
||||
public static class LocaleChecker implements Controller, LastModified {
|
||||
|
||||
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
|
||||
throws ServletException, IOException {
|
||||
if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
|
||||
throw new ServletException("Incorrect WebApplicationContext");
|
||||
}
|
||||
if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {
|
||||
throw new ServletException("Incorrect LocaleResolver");
|
||||
}
|
||||
if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
|
||||
throw new ServletException("Incorrect Locale");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public long getLastModified(HttpServletRequest request) {
|
||||
return 98;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static class DummyThemeSource implements ThemeSource {
|
||||
|
||||
private StaticMessageSource messageSource;
|
||||
|
||||
public DummyThemeSource() {
|
||||
this.messageSource = new StaticMessageSource();
|
||||
this.messageSource.addMessage("themetest", Locale.ENGLISH, "theme test message");
|
||||
this.messageSource.addMessage("themetestArgs", Locale.ENGLISH, "theme test message {0}");
|
||||
}
|
||||
|
||||
public Theme getTheme(String themeName) {
|
||||
if (AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(themeName)) {
|
||||
return new SimpleTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME, this.messageSource);
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
form.(class)=org.springframework.web.servlet.view.InternalResourceView
|
||||
form.requestContextAttribute=rc
|
||||
form.url=myform.jsp
|
||||
@@ -0,0 +1,193 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.DirectFieldAccessor;
|
||||
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.ResourceHttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.validation.MessageCodesResolver;
|
||||
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
|
||||
import org.springframework.web.bind.support.WebArgumentResolver;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentResolverAdapter;
|
||||
|
||||
/**
|
||||
* Test fixture for the configuration in mvc-config-annotation-driven.xml.
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class AnnotationDrivenBeanDefinitionParserTests {
|
||||
|
||||
private GenericWebApplicationContext appContext;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
appContext = new GenericWebApplicationContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMessageCodesResolver() {
|
||||
loadBeanDefinitions("mvc-config-message-codes-resolver.xml");
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
Object initializer = adapter.getWebBindingInitializer();
|
||||
assertNotNull(initializer);
|
||||
MessageCodesResolver resolver = ((ConfigurableWebBindingInitializer) initializer).getMessageCodesResolver();
|
||||
assertNotNull(resolver);
|
||||
assertEquals(TestMessageCodesResolver.class, resolver.getClass());
|
||||
assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMessageConverters() {
|
||||
loadBeanDefinitions("mvc-config-message-converters.xml");
|
||||
verifyMessageConverters(appContext.getBean(RequestMappingHandlerAdapter.class), true);
|
||||
verifyMessageConverters(appContext.getBean(ExceptionHandlerExceptionResolver.class), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMessageConvertersWithoutDefaultRegistrations() {
|
||||
loadBeanDefinitions("mvc-config-message-converters-defaults-off.xml");
|
||||
verifyMessageConverters(appContext.getBean(RequestMappingHandlerAdapter.class), false);
|
||||
verifyMessageConverters(appContext.getBean(ExceptionHandlerExceptionResolver.class), false);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testArgumentResolvers() {
|
||||
loadBeanDefinitions("mvc-config-argument-resolvers.xml");
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
Object value = new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
|
||||
assertNotNull(value);
|
||||
assertTrue(value instanceof List);
|
||||
List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) value;
|
||||
assertEquals(2, resolvers.size());
|
||||
assertTrue(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter);
|
||||
assertTrue(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testReturnValueHandlers() {
|
||||
loadBeanDefinitions("mvc-config-return-value-handlers.xml");
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
Object value = new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers");
|
||||
assertNotNull(value);
|
||||
assertTrue(value instanceof List);
|
||||
List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>) value;
|
||||
assertEquals(1, handlers.size());
|
||||
assertEquals(TestHandlerMethodReturnValueHandler.class, handlers.get(0).getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beanNameUrlHandlerMapping() {
|
||||
loadBeanDefinitions("mvc-config.xml");
|
||||
BeanNameUrlHandlerMapping mapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(2, mapping.getOrder());
|
||||
}
|
||||
|
||||
private void loadBeanDefinitions(String fileName) {
|
||||
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
|
||||
ClassPathResource resource = new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
|
||||
reader.loadBeanDefinitions(resource);
|
||||
appContext.refresh();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void verifyMessageConverters(Object bean, boolean hasDefaultRegistrations) {
|
||||
assertNotNull(bean);
|
||||
Object value = new DirectFieldAccessor(bean).getPropertyValue("messageConverters");
|
||||
assertNotNull(value);
|
||||
assertTrue(value instanceof List);
|
||||
List<HttpMessageConverter<?>> converters = (List<HttpMessageConverter<?>>) value;
|
||||
if (hasDefaultRegistrations) {
|
||||
assertTrue("Default converters are registered in addition to custom ones", converters.size() > 2);
|
||||
} else {
|
||||
assertTrue("Default converters should not be registered", converters.size() == 2);
|
||||
}
|
||||
assertTrue(converters.get(0) instanceof StringHttpMessageConverter);
|
||||
assertTrue(converters.get(1) instanceof ResourceHttpMessageConverter);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestWebArgumentResolver implements WebArgumentResolver {
|
||||
|
||||
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
public boolean supportsParameter(MethodParameter parameter) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class TestHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
|
||||
|
||||
public boolean supportsReturnType(MethodParameter returnType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void handleReturnValue(Object returnValue,
|
||||
MethodParameter returnType, ModelAndViewContainer mavContainer,
|
||||
NativeWebRequest webRequest) throws Exception {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class TestMessageCodesResolver implements MessageCodesResolver {
|
||||
|
||||
public String[] resolveMessageCodes(String errorCode, String objectName) {
|
||||
return new String[] { "test.foo.bar" };
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) {
|
||||
return new String[] { "test.foo.bar" };
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import javax.servlet.RequestDispatcher;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import org.springframework.beans.DirectFieldAccessor;
|
||||
import org.springframework.beans.TypeMismatchException;
|
||||
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.format.annotation.DateTimeFormat.ISO;
|
||||
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockRequestDispatcher;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.method.support.InvocableHandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
|
||||
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Keith Donald
|
||||
* @author Arjen Poutsma
|
||||
* @author Jeremy Grelle
|
||||
*/
|
||||
public class MvcNamespaceTests {
|
||||
|
||||
private GenericWebApplicationContext appContext;
|
||||
|
||||
private TestController handler;
|
||||
|
||||
private HandlerMethod handlerMethod;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
appContext = new GenericWebApplicationContext();
|
||||
appContext.setServletContext(new TestMockServletContext());
|
||||
LocaleContextHolder.setLocale(Locale.US);
|
||||
|
||||
handler = new TestController();
|
||||
Method method = TestController.class.getMethod("testBind", Date.class, TestBean.class, BindingResult.class);
|
||||
handlerMethod = new InvocableHandlerMethod(handler, method);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultConfig() throws Exception {
|
||||
loadBeanDefinitions("mvc-config.xml", 11);
|
||||
|
||||
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(0, mapping.getOrder());
|
||||
mapping.setDefaultHandler(handlerMethod);
|
||||
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
|
||||
|
||||
List<HttpMessageConverter<?>> messageConverters = adapter.getMessageConverters();
|
||||
assertTrue(messageConverters.size() > 0);
|
||||
|
||||
assertNotNull(appContext.getBean(FormattingConversionServiceFactoryBean.class));
|
||||
assertNotNull(appContext.getBean(ConversionService.class));
|
||||
assertNotNull(appContext.getBean(LocalValidatorFactoryBean.class));
|
||||
assertNotNull(appContext.getBean(Validator.class));
|
||||
|
||||
// default web binding initializer behavior test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
|
||||
request.addParameter("date", "2009-10-31");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertEquals(1, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
|
||||
ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
|
||||
interceptor.preHandle(request, response, handlerMethod);
|
||||
assertSame(appContext.getBean(ConversionService.class), request.getAttribute(ConversionService.class.getName()));
|
||||
|
||||
adapter.handle(request, response, handlerMethod);
|
||||
assertTrue(handler.recordedValidationError);
|
||||
}
|
||||
|
||||
@Test(expected=TypeMismatchException.class)
|
||||
public void testCustomConversionService() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 11);
|
||||
|
||||
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
mapping.setDefaultHandler(handlerMethod);
|
||||
|
||||
// default web binding initializer behavior test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
|
||||
request.setRequestURI("/accounts/12345");
|
||||
request.addParameter("date", "2009-10-31");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertEquals(1, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
|
||||
ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptors()[0];
|
||||
interceptor.preHandle(request, response, handler);
|
||||
assertSame(appContext.getBean("conversionService"), request.getAttribute(ConversionService.class.getName()));
|
||||
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
adapter.handle(request, response, handlerMethod);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCustomValidator() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-custom-validator.xml", 11);
|
||||
|
||||
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
|
||||
|
||||
// default web binding initializer behavior test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter("date", "2009-10-31");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
adapter.handle(request, response, handlerMethod);
|
||||
|
||||
assertTrue(appContext.getBean(TestValidator.class).validatorInvoked);
|
||||
assertFalse(handler.recordedValidationError);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInterceptors() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-interceptors.xml", 16);
|
||||
|
||||
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
mapping.setDefaultHandler(handlerMethod);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
|
||||
request.setRequestURI("/accounts/12345");
|
||||
request.addParameter("locale", "en");
|
||||
request.addParameter("theme", "green");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof WebRequestHandlerInterceptorAdapter);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
|
||||
request.setRequestURI("/logged/accounts/12345");
|
||||
chain = mapping.getHandler(request);
|
||||
assertEquals(5, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[4] instanceof WebRequestHandlerInterceptorAdapter);
|
||||
|
||||
request.setRequestURI("/foo/logged");
|
||||
chain = mapping.getHandler(request);
|
||||
assertEquals(5, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[4] instanceof WebRequestHandlerInterceptorAdapter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResources() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-resources.xml", 5);
|
||||
|
||||
HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
|
||||
ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class);
|
||||
assertNotNull(handler);
|
||||
|
||||
SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(Ordered.LOWEST_PRECEDENCE - 1, mapping.getOrder());
|
||||
|
||||
BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
|
||||
assertNotNull(beanNameMapping);
|
||||
assertEquals(2, beanNameMapping.getOrder());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/resources/foo.css");
|
||||
request.setMethod("GET");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertTrue(chain.getHandler() instanceof ResourceHttpRequestHandler);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
for (HandlerInterceptor interceptor : chain.getInterceptors()) {
|
||||
interceptor.preHandle(request, response, chain.getHandler());
|
||||
}
|
||||
ModelAndView mv = adapter.handle(request, response, chain.getHandler());
|
||||
assertNull(mv);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testResourcesWithOptionalAttributes() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-resources-optional-attrs.xml", 5);
|
||||
|
||||
SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(5, mapping.getOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultServletHandler() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-default-servlet.xml", 5);
|
||||
|
||||
HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
|
||||
DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class);
|
||||
assertNotNull(handler);
|
||||
|
||||
SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/foo.css");
|
||||
request.setMethod("GET");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ModelAndView mv = adapter.handle(request, response, chain.getHandler());
|
||||
assertNull(mv);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultServletHandlerWithOptionalAttributes() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml", 5);
|
||||
|
||||
HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
|
||||
DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class);
|
||||
assertNotNull(handler);
|
||||
|
||||
SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/foo.css");
|
||||
request.setMethod("GET");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ModelAndView mv = adapter.handle(request, response, chain.getHandler());
|
||||
assertNull(mv);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBeanDecoration() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-bean-decoration.xml", 13);
|
||||
|
||||
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
mapping.setDefaultHandler(handlerMethod);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertEquals(3, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor);
|
||||
LocaleChangeInterceptor interceptor = (LocaleChangeInterceptor) chain.getInterceptors()[1];
|
||||
assertEquals("lang", interceptor.getParamName());
|
||||
ThemeChangeInterceptor interceptor2 = (ThemeChangeInterceptor) chain.getInterceptors()[2];
|
||||
assertEquals("style", interceptor2.getParamName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testViewControllers() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-view-controllers.xml", 14);
|
||||
|
||||
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
|
||||
assertNotNull(mapping);
|
||||
mapping.setDefaultHandler(handlerMethod);
|
||||
|
||||
BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
|
||||
assertNotNull(beanNameMapping);
|
||||
assertEquals(2, beanNameMapping.getOrder());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
|
||||
HandlerExecutionChain chain = mapping.getHandler(request);
|
||||
assertEquals(3, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[0] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof ThemeChangeInterceptor);
|
||||
|
||||
SimpleUrlHandlerMapping mapping2 = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
assertNotNull(mapping2);
|
||||
|
||||
SimpleControllerHandlerAdapter adapter = appContext.getBean(SimpleControllerHandlerAdapter.class);
|
||||
assertNotNull(adapter);
|
||||
|
||||
request.setRequestURI("/foo");
|
||||
chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
ModelAndView mv = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertNull(mv.getViewName());
|
||||
|
||||
request.setRequestURI("/myapp/app/bar");
|
||||
request.setContextPath("/myapp");
|
||||
request.setServletPath("/app");
|
||||
chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
ModelAndView mv2 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertEquals("baz", mv2.getViewName());
|
||||
|
||||
request.setRequestURI("/myapp/app/");
|
||||
request.setContextPath("/myapp");
|
||||
request.setServletPath("/app");
|
||||
chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
ModelAndView mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertEquals("root", mv3.getViewName());
|
||||
}
|
||||
|
||||
/** WebSphere gives trailing servlet path slashes by default!! */
|
||||
@Test
|
||||
public void testViewControllersOnWebSphere() throws Exception {
|
||||
loadBeanDefinitions("mvc-config-view-controllers.xml", 14);
|
||||
|
||||
SimpleUrlHandlerMapping mapping2 = appContext.getBean(SimpleUrlHandlerMapping.class);
|
||||
SimpleControllerHandlerAdapter adapter = appContext.getBean(SimpleControllerHandlerAdapter.class);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
request.setRequestURI("/myapp/app/bar");
|
||||
request.setContextPath("/myapp");
|
||||
request.setServletPath("/app/");
|
||||
request.setAttribute("com.ibm.websphere.servlet.uri_non_decoded", "/myapp/app/bar");
|
||||
HandlerExecutionChain chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
ModelAndView mv2 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertEquals("baz", mv2.getViewName());
|
||||
|
||||
request.setRequestURI("/myapp/app/");
|
||||
request.setContextPath("/myapp");
|
||||
request.setServletPath("/app/");
|
||||
chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
ModelAndView mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertEquals("root", mv3.getViewName());
|
||||
|
||||
request.setRequestURI("/myapp/");
|
||||
request.setContextPath("/myapp");
|
||||
request.setServletPath("/");
|
||||
chain = mapping2.getHandler(request);
|
||||
assertEquals(4, chain.getInterceptors().length);
|
||||
assertTrue(chain.getInterceptors()[1] instanceof ConversionServiceExposingInterceptor);
|
||||
assertTrue(chain.getInterceptors()[2] instanceof LocaleChangeInterceptor);
|
||||
assertTrue(chain.getInterceptors()[3] instanceof ThemeChangeInterceptor);
|
||||
mv3 = adapter.handle(request, new MockHttpServletResponse(), chain.getHandler());
|
||||
assertEquals("root", mv3.getViewName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testViewControllersDefaultConfig() {
|
||||
loadBeanDefinitions("mvc-config-view-controllers-minimal.xml", 4);
|
||||
|
||||
BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
|
||||
assertNotNull(beanNameMapping);
|
||||
assertEquals(2, beanNameMapping.getOrder());
|
||||
}
|
||||
|
||||
private void loadBeanDefinitions(String fileName, int expectedBeanCount) {
|
||||
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
|
||||
ClassPathResource resource = new ClassPathResource(fileName, AnnotationDrivenBeanDefinitionParserTests.class);
|
||||
reader.loadBeanDefinitions(resource);
|
||||
assertEquals(expectedBeanCount, appContext.getBeanDefinitionCount());
|
||||
appContext.refresh();
|
||||
}
|
||||
|
||||
@Controller
|
||||
public static class TestController {
|
||||
|
||||
private boolean recordedValidationError;
|
||||
|
||||
@RequestMapping
|
||||
public void testBind(@RequestParam @DateTimeFormat(iso=ISO.DATE) Date date, @Validated(MyGroup.class) TestBean bean, BindingResult result) {
|
||||
this.recordedValidationError = (result.getErrorCount() == 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static class TestValidator implements Validator {
|
||||
|
||||
boolean validatorInvoked;
|
||||
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void validate(Object target, Errors errors) {
|
||||
this.validatorInvoked = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface MyGroup {
|
||||
}
|
||||
|
||||
private static class TestBean {
|
||||
|
||||
@NotNull(groups=MyGroup.class)
|
||||
private String field;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public String getField() {
|
||||
return field;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public void setField(String field) {
|
||||
this.field = field;
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestMockServletContext extends MockServletContext {
|
||||
|
||||
@Override
|
||||
public RequestDispatcher getNamedDispatcher(String path) {
|
||||
if (path.equals("default") || path.equals("custom")) {
|
||||
return new MockRequestDispatcher("/");
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import javax.servlet.RequestDispatcher;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockRequestDispatcher;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
|
||||
|
||||
/**
|
||||
* Test fixture with a {@link DefaultServletHandlerConfigurer}.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class DefaultServletHandlerConfigurerTests {
|
||||
|
||||
private DefaultServletHandlerConfigurer configurer;
|
||||
|
||||
private DispatchingMockServletContext servletContext;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
response = new MockHttpServletResponse();
|
||||
servletContext = new DispatchingMockServletContext();
|
||||
configurer = new DefaultServletHandlerConfigurer(servletContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void notEnabled() {
|
||||
assertNull(configurer.getHandlerMapping());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void enable() throws Exception {
|
||||
configurer.enable();
|
||||
SimpleUrlHandlerMapping getHandlerMapping = getHandlerMapping();
|
||||
SimpleUrlHandlerMapping handlerMapping = getHandlerMapping;
|
||||
DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**");
|
||||
|
||||
assertNotNull(handler);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
|
||||
handler.handleRequest(new MockHttpServletRequest(), response);
|
||||
|
||||
String expected = "default";
|
||||
assertEquals("The ServletContext was not called with the default servlet name", expected, servletContext.url);
|
||||
assertEquals("The request was not forwarded", expected, response.getForwardedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void enableWithServletName() throws Exception {
|
||||
configurer.enable("defaultServlet");
|
||||
SimpleUrlHandlerMapping handlerMapping = getHandlerMapping();
|
||||
DefaultServletHttpRequestHandler handler = (DefaultServletHttpRequestHandler) handlerMapping.getUrlMap().get("/**");
|
||||
|
||||
assertNotNull(handler);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
|
||||
handler.handleRequest(new MockHttpServletRequest(), response);
|
||||
|
||||
String expected = "defaultServlet";
|
||||
assertEquals("The ServletContext was not called with the default servlet name", expected, servletContext.url);
|
||||
assertEquals("The request was not forwarded", expected, response.getForwardedUrl());
|
||||
}
|
||||
|
||||
private static class DispatchingMockServletContext extends MockServletContext {
|
||||
|
||||
private String url;
|
||||
|
||||
@Override
|
||||
public RequestDispatcher getNamedDispatcher(String url) {
|
||||
this.url = url;
|
||||
return new MockRequestDispatcher(url);
|
||||
}
|
||||
}
|
||||
|
||||
private SimpleUrlHandlerMapping getHandlerMapping() {
|
||||
return (SimpleUrlHandlerMapping) configurer.getHandlerMapping();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.easymock.EasyMock.capture;
|
||||
import static org.easymock.EasyMock.expect;
|
||||
import static org.easymock.EasyMock.replay;
|
||||
import static org.easymock.EasyMock.verify;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.easymock.Capture;
|
||||
import org.easymock.EasyMock;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.format.support.FormattingConversionService;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;
|
||||
import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
|
||||
|
||||
/**
|
||||
* A test fixture for {@link DelegatingWebMvcConfiguration} tests.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class DelegatingWebMvcConfigurationTests {
|
||||
|
||||
private DelegatingWebMvcConfiguration mvcConfiguration;
|
||||
|
||||
private WebMvcConfigurer configurer;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
configurer = EasyMock.createMock(WebMvcConfigurer.class);
|
||||
mvcConfiguration = new DelegatingWebMvcConfiguration();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMappingHandlerAdapter() throws Exception {
|
||||
Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>();
|
||||
Capture<FormattingConversionService> conversionService = new Capture<FormattingConversionService>();
|
||||
Capture<List<HandlerMethodArgumentResolver>> resolvers = new Capture<List<HandlerMethodArgumentResolver>>();
|
||||
Capture<List<HandlerMethodReturnValueHandler>> handlers = new Capture<List<HandlerMethodReturnValueHandler>>();
|
||||
|
||||
configurer.configureMessageConverters(capture(converters));
|
||||
expect(configurer.getValidator()).andReturn(null);
|
||||
configurer.addFormatters(capture(conversionService));
|
||||
configurer.addArgumentResolvers(capture(resolvers));
|
||||
configurer.addReturnValueHandlers(capture(handlers));
|
||||
replay(configurer);
|
||||
|
||||
mvcConfiguration.setConfigurers(Arrays.asList(configurer));
|
||||
RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter();
|
||||
|
||||
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
|
||||
assertSame(conversionService.getValue(), initializer.getConversionService());
|
||||
assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
|
||||
|
||||
assertEquals(0, resolvers.getValue().size());
|
||||
assertEquals(0, handlers.getValue().size());
|
||||
assertEquals(converters.getValue(), adapter.getMessageConverters());
|
||||
|
||||
verify(configurer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureMessageConverters() {
|
||||
List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>();
|
||||
configurers.add(new WebMvcConfigurerAdapter() {
|
||||
@Override
|
||||
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new StringHttpMessageConverter());
|
||||
}
|
||||
});
|
||||
mvcConfiguration = new DelegatingWebMvcConfiguration();
|
||||
mvcConfiguration.setConfigurers(configurers);
|
||||
|
||||
RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter();
|
||||
assertEquals("Only one custom converter should be registered", 1, adapter.getMessageConverters().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getCustomValidator() {
|
||||
expect(configurer.getValidator()).andReturn(new LocalValidatorFactoryBean());
|
||||
replay(configurer);
|
||||
|
||||
mvcConfiguration.setConfigurers(Arrays.asList(configurer));
|
||||
mvcConfiguration.mvcValidator();
|
||||
|
||||
verify(configurer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlerExceptionResolver() throws Exception {
|
||||
Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>();
|
||||
Capture<List<HandlerExceptionResolver>> exceptionResolvers = new Capture<List<HandlerExceptionResolver>>();
|
||||
|
||||
configurer.configureMessageConverters(capture(converters));
|
||||
configurer.configureHandlerExceptionResolvers(capture(exceptionResolvers));
|
||||
replay(configurer);
|
||||
|
||||
mvcConfiguration.setConfigurers(Arrays.asList(configurer));
|
||||
mvcConfiguration.handlerExceptionResolver();
|
||||
|
||||
assertEquals(3, exceptionResolvers.getValue().size());
|
||||
assertTrue(exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver);
|
||||
assertTrue(exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver);
|
||||
assertTrue(exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver);
|
||||
assertTrue(converters.getValue().size() > 0);
|
||||
|
||||
verify(configurer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureExceptionResolvers() throws Exception {
|
||||
List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>();
|
||||
configurers.add(new WebMvcConfigurerAdapter() {
|
||||
@Override
|
||||
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
|
||||
exceptionResolvers.add(new DefaultHandlerExceptionResolver());
|
||||
}
|
||||
});
|
||||
mvcConfiguration.setConfigurers(configurers);
|
||||
|
||||
HandlerExceptionResolverComposite composite =
|
||||
(HandlerExceptionResolverComposite) mvcConfiguration.handlerExceptionResolver();
|
||||
assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.ui.ModelMap;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.context.request.WebRequestInterceptor;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.handler.MappedInterceptor;
|
||||
import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
|
||||
|
||||
/**
|
||||
* Test fixture with a {@link InterceptorRegistry}, two {@link HandlerInterceptor}s and two
|
||||
* {@link WebRequestInterceptor}s.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class InterceptorRegistryTests {
|
||||
|
||||
private InterceptorRegistry registry;
|
||||
|
||||
private final HandlerInterceptor interceptor1 = new LocaleChangeInterceptor();
|
||||
|
||||
private final HandlerInterceptor interceptor2 = new ThemeChangeInterceptor();
|
||||
|
||||
private TestWebRequestInterceptor webRequestInterceptor1;
|
||||
|
||||
private TestWebRequestInterceptor webRequestInterceptor2;
|
||||
|
||||
private final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
private final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
registry = new InterceptorRegistry();
|
||||
webRequestInterceptor1 = new TestWebRequestInterceptor();
|
||||
webRequestInterceptor2 = new TestWebRequestInterceptor();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addInterceptor() {
|
||||
registry.addInterceptor(interceptor1);
|
||||
List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
|
||||
|
||||
assertEquals(Arrays.asList(interceptor1), interceptors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addTwoInterceptors() {
|
||||
registry.addInterceptor(interceptor1);
|
||||
registry.addInterceptor(interceptor2);
|
||||
List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
|
||||
|
||||
assertEquals(Arrays.asList(interceptor1, interceptor2), interceptors);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addInterceptorsWithUrlPatterns() {
|
||||
registry.addInterceptor(interceptor1).addPathPatterns("/path1");
|
||||
registry.addInterceptor(interceptor2).addPathPatterns("/path2");
|
||||
|
||||
assertEquals(Arrays.asList(interceptor1), getInterceptorsForPath("/path1"));
|
||||
assertEquals(Arrays.asList(interceptor2), getInterceptorsForPath("/path2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addWebRequestInterceptor() throws Exception {
|
||||
registry.addWebRequestInterceptor(webRequestInterceptor1);
|
||||
List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
|
||||
|
||||
assertEquals(1, interceptors.size());
|
||||
verifyAdaptedInterceptor(interceptors.get(0), webRequestInterceptor1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addWebRequestInterceptors() throws Exception {
|
||||
registry.addWebRequestInterceptor(webRequestInterceptor1);
|
||||
registry.addWebRequestInterceptor(webRequestInterceptor2);
|
||||
List<HandlerInterceptor> interceptors = getInterceptorsForPath(null);
|
||||
|
||||
assertEquals(2, interceptors.size());
|
||||
verifyAdaptedInterceptor(interceptors.get(0), webRequestInterceptor1);
|
||||
verifyAdaptedInterceptor(interceptors.get(1), webRequestInterceptor2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addWebRequestInterceptorsWithUrlPatterns() throws Exception {
|
||||
registry.addWebRequestInterceptor(webRequestInterceptor1).addPathPatterns("/path1");
|
||||
registry.addWebRequestInterceptor(webRequestInterceptor2).addPathPatterns("/path2");
|
||||
|
||||
List<HandlerInterceptor> interceptors = getInterceptorsForPath("/path1");
|
||||
assertEquals(1, interceptors.size());
|
||||
verifyAdaptedInterceptor(interceptors.get(0), webRequestInterceptor1);
|
||||
|
||||
interceptors = getInterceptorsForPath("/path2");
|
||||
assertEquals(1, interceptors.size());
|
||||
verifyAdaptedInterceptor(interceptors.get(0), webRequestInterceptor2);
|
||||
}
|
||||
|
||||
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
|
||||
PathMatcher pathMatcher = new AntPathMatcher();
|
||||
List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>();
|
||||
for (Object i : registry.getInterceptors()) {
|
||||
if (i instanceof MappedInterceptor) {
|
||||
MappedInterceptor mappedInterceptor = (MappedInterceptor) i;
|
||||
if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
|
||||
result.add(mappedInterceptor.getInterceptor());
|
||||
}
|
||||
}
|
||||
else if (i instanceof HandlerInterceptor){
|
||||
result.add((HandlerInterceptor) i);
|
||||
}
|
||||
else {
|
||||
fail("Unexpected interceptor type: " + i.getClass().getName());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void verifyAdaptedInterceptor(HandlerInterceptor interceptor, TestWebRequestInterceptor webInterceptor)
|
||||
throws Exception {
|
||||
assertTrue(interceptor instanceof WebRequestHandlerInterceptorAdapter);
|
||||
interceptor.preHandle(request, response, null);
|
||||
assertTrue(webInterceptor.preHandleInvoked);
|
||||
}
|
||||
|
||||
private static class TestWebRequestInterceptor implements WebRequestInterceptor {
|
||||
|
||||
private boolean preHandleInvoked = false;
|
||||
|
||||
public void preHandle(WebRequest request) throws Exception {
|
||||
preHandleInvoked = true;
|
||||
}
|
||||
|
||||
public void postHandle(WebRequest request, ModelMap model) throws Exception {
|
||||
}
|
||||
|
||||
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.support.GenericWebApplicationContext;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
|
||||
|
||||
/**
|
||||
* Test fixture with a {@link ResourceHandlerRegistry}.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class ResourceHandlerRegistryTests {
|
||||
|
||||
private ResourceHandlerRegistry registry;
|
||||
|
||||
private ResourceHandlerRegistration registration;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
registry = new ResourceHandlerRegistry(new GenericWebApplicationContext(), new MockServletContext());
|
||||
registration = registry.addResourceHandler("/resources/**");
|
||||
registration.addResourceLocations("classpath:org/springframework/web/servlet/config/annotation/");
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noResourceHandlers() throws Exception {
|
||||
registry = new ResourceHandlerRegistry(new GenericWebApplicationContext(), new MockServletContext());
|
||||
assertNull(registry.getHandlerMapping());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mapPathToLocation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css");
|
||||
|
||||
ResourceHttpRequestHandler handler = getHandler("/resources/**");
|
||||
handler.handleRequest(request, response);
|
||||
|
||||
assertEquals("test stylesheet content", response.getContentAsString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cachePeriod() {
|
||||
assertEquals(-1, getHandler("/resources/**").getCacheSeconds());
|
||||
|
||||
registration.setCachePeriod(0);
|
||||
assertEquals(0, getHandler("/resources/**").getCacheSeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void order() {
|
||||
assertEquals(Integer.MAX_VALUE -1, registry.getHandlerMapping().getOrder());
|
||||
|
||||
registry.setOrder(0);
|
||||
assertEquals(0, registry.getHandlerMapping().getOrder());
|
||||
}
|
||||
|
||||
private ResourceHttpRequestHandler getHandler(String pathPattern) {
|
||||
SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) registry.getHandlerMapping();
|
||||
return (ResourceHttpRequestHandler) handlerMapping.getUrlMap().get(pathPattern);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.mvc.ParameterizableViewController;
|
||||
|
||||
/**
|
||||
* Test fixture with a {@link ViewControllerRegistry}.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class ViewControllerRegistryTests {
|
||||
|
||||
private ViewControllerRegistry registry;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
registry = new ViewControllerRegistry();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noViewControllers() throws Exception {
|
||||
assertNull(registry.getHandlerMapping());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addViewController() {
|
||||
registry.addViewController("/path");
|
||||
Map<String, ?> urlMap = getHandlerMapping().getUrlMap();
|
||||
ParameterizableViewController controller = (ParameterizableViewController) urlMap.get("/path");
|
||||
assertNotNull(controller);
|
||||
assertNull(controller.getViewName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addViewControllerWithViewName() {
|
||||
registry.addViewController("/path").setViewName("viewName");
|
||||
Map<String, ?> urlMap = getHandlerMapping().getUrlMap();
|
||||
ParameterizableViewController controller = (ParameterizableViewController) urlMap.get("/path");
|
||||
assertNotNull(controller);
|
||||
assertEquals("viewName", controller.getViewName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void order() {
|
||||
registry.addViewController("/path");
|
||||
SimpleUrlHandlerMapping handlerMapping = getHandlerMapping();
|
||||
assertEquals(1, handlerMapping.getOrder());
|
||||
|
||||
registry.setOrder(2);
|
||||
handlerMapping = getHandlerMapping();
|
||||
assertEquals(2, handlerMapping.getOrder());
|
||||
}
|
||||
|
||||
private SimpleUrlHandlerMapping getHandlerMapping() {
|
||||
return (SimpleUrlHandlerMapping) registry.getHandlerMapping();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.config.annotation;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.DirectFieldAccessor;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.core.convert.ConversionService;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.io.FileSystemResourceLoader;
|
||||
import org.springframework.format.FormatterRegistry;
|
||||
import org.springframework.format.support.FormattingConversionService;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.validation.BeanPropertyBindingResult;
|
||||
import org.springframework.validation.Errors;
|
||||
import org.springframework.validation.Validator;
|
||||
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
|
||||
import org.springframework.web.context.support.StaticWebApplicationContext;
|
||||
import org.springframework.web.method.annotation.ModelAttributeMethodProcessor;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
|
||||
import org.springframework.web.servlet.HandlerExceptionResolver;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
|
||||
import org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor;
|
||||
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;
|
||||
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
|
||||
/**
|
||||
* A test fixture for {@link WebMvcConfigurationSupport}.
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
*/
|
||||
public class WebMvcConfigurationSupportTests {
|
||||
|
||||
private TestWebMvcConfiguration mvcConfiguration;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mvcConfiguration = new TestWebMvcConfiguration();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMappingHandlerMapping() throws Exception {
|
||||
StaticWebApplicationContext cxt = new StaticWebApplicationContext();
|
||||
cxt.registerSingleton("controller", TestController.class);
|
||||
|
||||
RequestMappingHandlerMapping handlerMapping = mvcConfiguration.requestMappingHandlerMapping();
|
||||
assertEquals(0, handlerMapping.getOrder());
|
||||
|
||||
handlerMapping.setApplicationContext(cxt);
|
||||
HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
|
||||
assertNotNull(chain.getInterceptors());
|
||||
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyViewControllerHandlerMapping() {
|
||||
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.viewControllerHandlerMapping();
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void beanNameHandlerMapping() throws Exception {
|
||||
StaticWebApplicationContext cxt = new StaticWebApplicationContext();
|
||||
cxt.registerSingleton("/controller", TestController.class);
|
||||
|
||||
HttpServletRequest request = new MockHttpServletRequest("GET", "/controller");
|
||||
|
||||
BeanNameUrlHandlerMapping handlerMapping = mvcConfiguration.beanNameHandlerMapping();
|
||||
assertEquals(2, handlerMapping.getOrder());
|
||||
|
||||
handlerMapping.setApplicationContext(cxt);
|
||||
HandlerExecutionChain chain = handlerMapping.getHandler(request);
|
||||
assertNotNull(chain.getInterceptors());
|
||||
assertEquals(2, chain.getInterceptors().length);
|
||||
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyResourceHandlerMapping() {
|
||||
mvcConfiguration.setApplicationContext(new StaticWebApplicationContext());
|
||||
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.resourceHandlerMapping();
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyDefaultServletHandlerMapping() {
|
||||
mvcConfiguration.setServletContext(new MockServletContext());
|
||||
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.defaultServletHandlerMapping();
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMappingHandlerAdapter() throws Exception {
|
||||
RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter();
|
||||
|
||||
List<HttpMessageConverter<?>> expectedConverters = new ArrayList<HttpMessageConverter<?>>();
|
||||
mvcConfiguration.addDefaultHttpMessageConverters(expectedConverters);
|
||||
assertEquals(expectedConverters.size(), adapter.getMessageConverters().size());
|
||||
|
||||
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
|
||||
assertNotNull(initializer);
|
||||
|
||||
ConversionService conversionService = initializer.getConversionService();
|
||||
assertNotNull(conversionService);
|
||||
assertTrue(conversionService instanceof FormattingConversionService);
|
||||
|
||||
Validator validator = initializer.getValidator();
|
||||
assertNotNull(validator);
|
||||
assertTrue(validator instanceof LocalValidatorFactoryBean);
|
||||
|
||||
assertEquals(false, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlerExceptionResolver() throws Exception {
|
||||
HandlerExceptionResolverComposite compositeResolver =
|
||||
(HandlerExceptionResolverComposite) mvcConfiguration.handlerExceptionResolver();
|
||||
|
||||
assertEquals(0, compositeResolver.getOrder());
|
||||
|
||||
List<HandlerExceptionResolver> expectedResolvers = new ArrayList<HandlerExceptionResolver>();
|
||||
mvcConfiguration.addDefaultHandlerExceptionResolvers(expectedResolvers);
|
||||
assertEquals(expectedResolvers.size(), compositeResolver.getExceptionResolvers().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void webMvcConfigurerExtensionHooks() throws Exception {
|
||||
|
||||
StaticWebApplicationContext appCxt = new StaticWebApplicationContext();
|
||||
appCxt.setServletContext(new MockServletContext(new FileSystemResourceLoader()));
|
||||
appCxt.registerSingleton("controller", TestController.class);
|
||||
|
||||
WebConfig webConfig = new WebConfig();
|
||||
webConfig.setApplicationContext(appCxt);
|
||||
webConfig.setServletContext(appCxt.getServletContext());
|
||||
|
||||
String actual = webConfig.mvcConversionService().convert(new TestBean(), String.class);
|
||||
assertEquals("converted", actual);
|
||||
|
||||
RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter();
|
||||
assertEquals(1, adapter.getMessageConverters().size());
|
||||
|
||||
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
|
||||
assertNotNull(initializer);
|
||||
|
||||
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");
|
||||
initializer.getValidator().validate(null, bindingResult);
|
||||
assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<HandlerMethodArgumentResolver> argResolvers= (List<HandlerMethodArgumentResolver>)
|
||||
new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
|
||||
assertEquals(1, argResolvers.size());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
List<HandlerMethodReturnValueHandler> handlers = (List<HandlerMethodReturnValueHandler>)
|
||||
new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers");
|
||||
assertEquals(1, handlers.size());
|
||||
|
||||
HandlerExceptionResolverComposite composite = (HandlerExceptionResolverComposite) webConfig.handlerExceptionResolver();
|
||||
assertEquals(1, composite.getExceptionResolvers().size());
|
||||
|
||||
RequestMappingHandlerMapping rmHandlerMapping = webConfig.requestMappingHandlerMapping();
|
||||
rmHandlerMapping.setApplicationContext(appCxt);
|
||||
HandlerExecutionChain chain = rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
|
||||
assertNotNull(chain.getInterceptors());
|
||||
assertEquals(2, chain.getInterceptors().length);
|
||||
assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[0].getClass());
|
||||
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());
|
||||
|
||||
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) webConfig.viewControllerHandlerMapping();
|
||||
handlerMapping.setApplicationContext(appCxt);
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(1, handlerMapping.getOrder());
|
||||
HandlerExecutionChain handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path"));
|
||||
assertNotNull(handler.getHandler());
|
||||
|
||||
handlerMapping = (AbstractHandlerMapping) webConfig.resourceHandlerMapping();
|
||||
handlerMapping.setApplicationContext(appCxt);
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(Integer.MAX_VALUE-1, handlerMapping.getOrder());
|
||||
handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
|
||||
assertNotNull(handler.getHandler());
|
||||
|
||||
handlerMapping = (AbstractHandlerMapping) webConfig.defaultServletHandlerMapping();
|
||||
handlerMapping.setApplicationContext(appCxt);
|
||||
assertNotNull(handlerMapping);
|
||||
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
|
||||
handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath"));
|
||||
assertNotNull(handler.getHandler());
|
||||
}
|
||||
|
||||
@Controller
|
||||
private static class TestController {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
@RequestMapping("/")
|
||||
public void handle() {
|
||||
}
|
||||
}
|
||||
|
||||
private static class TestWebMvcConfiguration extends WebMvcConfigurationSupport {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The purpose of this class is to test that an implementation of a {@link WebMvcConfigurer}
|
||||
* can also apply customizations by extension from {@link WebMvcConfigurationSupport}.
|
||||
*/
|
||||
private class WebConfig extends WebMvcConfigurationSupport implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addConverter(new Converter<TestBean, String>() {
|
||||
public String convert(TestBean source) {
|
||||
return "converted";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
|
||||
converters.add(new MappingJacksonHttpMessageConverter());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Validator getValidator() {
|
||||
return new Validator() {
|
||||
public void validate(Object target, Errors errors) {
|
||||
errors.reject("invalid");
|
||||
}
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new ModelAttributeMethodProcessor(true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
|
||||
returnValueHandlers.add(new ModelAttributeMethodProcessor(true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
|
||||
exceptionResolvers.add(new SimpleMappingExceptionResolver());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new LocaleChangeInterceptor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/path");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("src/test/java");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable("default");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.web.servlet.handler;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
/**
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanNameUrlHandlerMappingTests extends TestCase {
|
||||
|
||||
public static final String CONF = "/org/springframework/web/servlet/handler/map1.xml";
|
||||
|
||||
private ConfigurableWebApplicationContext wac;
|
||||
|
||||
public void setUp() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
wac = new XmlWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.setConfigLocations(new String[] {CONF});
|
||||
wac.refresh();
|
||||
}
|
||||
|
||||
public void testRequestsWithoutHandlers() throws Exception {
|
||||
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/nonsense.html");
|
||||
req.setContextPath("/myapp");
|
||||
Object h = hm.getHandler(req);
|
||||
assertTrue("Handler is null", h == null);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/foo/bar/baz.html");
|
||||
h = hm.getHandler(req);
|
||||
assertTrue("Handler is null", h == null);
|
||||
}
|
||||
|
||||
public void testRequestsWithSubPaths() throws Exception {
|
||||
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
|
||||
doTestRequestsWithSubPaths(hm);
|
||||
}
|
||||
|
||||
public void testRequestsWithSubPathsInParentContext() throws Exception {
|
||||
BeanNameUrlHandlerMapping hm = new BeanNameUrlHandlerMapping();
|
||||
hm.setDetectHandlersInAncestorContexts(true);
|
||||
hm.setApplicationContext(new StaticApplicationContext(wac));
|
||||
doTestRequestsWithSubPaths(hm);
|
||||
}
|
||||
|
||||
private void doTestRequestsWithSubPaths(HandlerMapping hm) throws Exception {
|
||||
Object bean = wac.getBean("godCtrl");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/welcome.html");
|
||||
HandlerExecutionChain hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
req.setServletPath("/mypath/welcome.html");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/myapp/myservlet/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
req.setServletPath("/myservlet");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/myapp/myapp/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
req.setServletPath("/myapp");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/show.html");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/bookseats.html");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
}
|
||||
|
||||
public void testRequestsWithFullPaths() throws Exception {
|
||||
BeanNameUrlHandlerMapping hm = new BeanNameUrlHandlerMapping();
|
||||
hm.setAlwaysUseFullPath(true);
|
||||
hm.setApplicationContext(wac);
|
||||
Object bean = wac.getBean("godCtrl");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/welcome.html");
|
||||
HandlerExecutionChain hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/myapp/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/welcome.html");
|
||||
req.setContextPath("");
|
||||
req.setServletPath("/mypath");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/Myapp/mypath/welcome.html");
|
||||
req.setContextPath("/myapp");
|
||||
req.setServletPath("/mypath");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
}
|
||||
|
||||
public void testAsteriskMatches() throws Exception {
|
||||
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
|
||||
Object bean = wac.getBean("godCtrl");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html");
|
||||
HandlerExecutionChain hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/testarossa");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/tes");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec == null);
|
||||
}
|
||||
|
||||
public void testOverlappingMappings() throws Exception {
|
||||
BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping");
|
||||
Object anotherHandler = new Object();
|
||||
hm.registerHandler("/mypath/testaross*", anotherHandler);
|
||||
Object bean = wac.getBean("godCtrl");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/test.html");
|
||||
HandlerExecutionChain hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/testarossa");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == anotherHandler);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/mypath/tes");
|
||||
hec = hm.getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec == null);
|
||||
}
|
||||
|
||||
public void testDoubleMappings() throws ServletException {
|
||||
BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping");
|
||||
try {
|
||||
hm.registerHandler("/mypath/welcome.html", new Object());
|
||||
fail("Should have thrown IllegalStateException");
|
||||
}
|
||||
catch (IllegalStateException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright 2002-2011 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.web.servlet.handler;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.util.AntPathMatcher;
|
||||
import org.springframework.util.PathMatcher;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.util.UrlPathHelper;
|
||||
|
||||
/**
|
||||
* Test for {@link AbstractHandlerMethodMapping}.
|
||||
*
|
||||
* @author Arjen Poutsma
|
||||
*/
|
||||
public class HandlerMethodMappingTests {
|
||||
|
||||
private AbstractHandlerMethodMapping<String> mapping;
|
||||
|
||||
private MyHandler handler;
|
||||
|
||||
private Method method1;
|
||||
|
||||
private Method method2;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
mapping = new MyHandlerMethodMapping();
|
||||
handler = new MyHandler();
|
||||
method1 = handler.getClass().getMethod("handlerMethod1");
|
||||
method2 = handler.getClass().getMethod("handlerMethod2");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void registerDuplicates() {
|
||||
mapping.registerHandlerMethod(handler, method1, "foo");
|
||||
mapping.registerHandlerMethod(handler, method2, "foo");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void directMatch() throws Exception {
|
||||
String key = "foo";
|
||||
mapping.registerHandlerMethod(handler, method1, key);
|
||||
|
||||
HandlerMethod result = mapping.getHandlerInternal(new MockHttpServletRequest("GET", key));
|
||||
assertEquals(method1, result.getMethod());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void patternMatch() throws Exception {
|
||||
mapping.registerHandlerMethod(handler, method1, "/fo*");
|
||||
mapping.registerHandlerMethod(handler, method1, "/f*");
|
||||
|
||||
HandlerMethod result = mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo"));
|
||||
assertEquals(method1, result.getMethod());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void ambiguousMatch() throws Exception {
|
||||
mapping.registerHandlerMethod(handler, method1, "/f?o");
|
||||
mapping.registerHandlerMethod(handler, method2, "/fo?");
|
||||
|
||||
mapping.getHandlerInternal(new MockHttpServletRequest("GET", "/foo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectHandlerMethodsInAncestorContexts() {
|
||||
StaticApplicationContext cxt = new StaticApplicationContext();
|
||||
cxt.registerSingleton("myHandler", MyHandler.class);
|
||||
|
||||
AbstractHandlerMethodMapping<String> mapping1 = new MyHandlerMethodMapping();
|
||||
mapping1.setApplicationContext(new StaticApplicationContext(cxt));
|
||||
|
||||
assertEquals(0, mapping1.getHandlerMethods().size());
|
||||
|
||||
AbstractHandlerMethodMapping<String> mapping2 = new MyHandlerMethodMapping();
|
||||
mapping2.setDetectHandlerMethodsInAncestorContexts(true);
|
||||
mapping2.setApplicationContext(new StaticApplicationContext(cxt));
|
||||
|
||||
assertEquals(2, mapping2.getHandlerMethods().size());
|
||||
}
|
||||
|
||||
|
||||
private static class MyHandlerMethodMapping extends AbstractHandlerMethodMapping<String> {
|
||||
|
||||
private UrlPathHelper pathHelper = new UrlPathHelper();
|
||||
|
||||
private PathMatcher pathMatcher = new AntPathMatcher();
|
||||
|
||||
@Override
|
||||
protected String getMatchingMapping(String pattern, HttpServletRequest request) {
|
||||
String lookupPath = pathHelper.getLookupPathForRequest(request);
|
||||
return pathMatcher.match(pattern, lookupPath) ? pattern : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getMappingForMethod(Method method, Class<?> handlerType) {
|
||||
String methodName = method.getName();
|
||||
return methodName.startsWith("handler") ? methodName : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Comparator<String> getMappingComparator(HttpServletRequest request) {
|
||||
String lookupPath = pathHelper.getLookupPathForRequest(request);
|
||||
return pathMatcher.getPatternComparator(lookupPath);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean isHandler(Class<?> beanType) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Set<String> getMappingPathPatterns(String key) {
|
||||
return new HashSet<String>();
|
||||
}
|
||||
}
|
||||
|
||||
@Controller
|
||||
static class MyHandler {
|
||||
|
||||
@RequestMapping
|
||||
public void handlerMethod1() {
|
||||
}
|
||||
|
||||
@RequestMapping
|
||||
public void handlerMethod2() {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/*
|
||||
* Copyright 2002-2007 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.web.servlet.handler;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.ConfigurableWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.HandlerExecutionChain;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
* @author Alef Arendsen
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class PathMatchingUrlHandlerMappingTests {
|
||||
|
||||
public static final String CONF = "/org/springframework/web/servlet/handler/map3.xml";
|
||||
|
||||
private HandlerMapping hm;
|
||||
|
||||
private ConfigurableWebApplicationContext wac;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
wac = new XmlWebApplicationContext();
|
||||
wac.setServletContext(sc);
|
||||
wac.setConfigLocations(new String[] {CONF});
|
||||
wac.refresh();
|
||||
hm = (HandlerMapping) wac.getBean("urlMapping");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestsWithHandlers() throws Exception {
|
||||
Object bean = wac.getBean("mainController");
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/welcome.html");
|
||||
HandlerExecutionChain hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/show.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/bookseats.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void actualPathMatching() throws Exception {
|
||||
// there a couple of mappings defined with which we can test the
|
||||
// path matching, let's do that...
|
||||
|
||||
Object bean = wac.getBean("mainController");
|
||||
Object defaultBean = wac.getBean("starController");
|
||||
|
||||
// testing some normal behavior
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/pathmatchingTest.html");
|
||||
HandlerExecutionChain hec = getHandler(req);
|
||||
assertTrue("Handler is null", hec != null);
|
||||
assertTrue("Handler is correct bean", hec.getHandler() == bean);
|
||||
assertEquals("pathmatchingTest.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
|
||||
// no match, no forward slash included
|
||||
req = new MockHttpServletRequest("GET", "welcome.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
assertEquals("welcome.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
|
||||
// testing some ????? behavior
|
||||
req = new MockHttpServletRequest("GET", "/pathmatchingAA.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
assertEquals("pathmatchingAA.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
|
||||
// testing some ????? behavior
|
||||
req = new MockHttpServletRequest("GET", "/pathmatchingA.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
assertEquals("/pathmatchingA.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
|
||||
// testing some ????? behavior
|
||||
req = new MockHttpServletRequest("GET", "/administrator/pathmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// testing simple /**/behavior
|
||||
req = new MockHttpServletRequest("GET", "/administrator/test/pathmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// this should not match because of the administratorT
|
||||
req = new MockHttpServletRequest("GET", "/administratort/pathmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
// this should match because of *.jsp
|
||||
req = new MockHttpServletRequest("GET", "/bla.jsp");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// this as well, because there's a **/in there as well
|
||||
req = new MockHttpServletRequest("GET", "/testing/bla.jsp");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// should match because because exact pattern is there
|
||||
req = new MockHttpServletRequest("GET", "/administrator/another/bla.xml");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// should not match, because there's not .gif extension in there
|
||||
req = new MockHttpServletRequest("GET", "/administrator/another/bla.gif");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
// should match because there testlast* in there
|
||||
req = new MockHttpServletRequest("GET", "/administrator/test/testlastbit");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
// but this not, because it's testlast and not testla
|
||||
req = new MockHttpServletRequest("GET", "/administrator/test/testla");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/administrator/testing/longer/bla");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/administrator/testing/longer/test.jsp");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/administrator/testing/longer2/notmatching/notmatching");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/shortpattern/testing/toolong");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/XXpathXXmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/pathXXmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/XpathXXmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/XXpathmatching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/show12.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/show123.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/show1.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/reallyGood-test-is-this.jpeg");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/reallyGood-tst-is-this.jpeg");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/testing/test.jpeg");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/testing/test.jpg");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/anotherTest");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/stillAnotherTest");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
// there outofpattern*yeah in the pattern, so this should fail
|
||||
req = new MockHttpServletRequest("GET", "/outofpattern*ye");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/test't est/path'm atching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
|
||||
req = new MockHttpServletRequest("GET", "/test%26t%20est/path%26m%20atching.html");
|
||||
hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == defaultBean);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultMapping() throws Exception {
|
||||
Object bean = wac.getBean("starController");
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/goggog.html");
|
||||
HandlerExecutionChain hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mappingExposedInRequest() throws Exception {
|
||||
Object bean = wac.getBean("mainController");
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/show.html");
|
||||
HandlerExecutionChain hec = getHandler(req);
|
||||
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
|
||||
assertEquals("Mapping not exposed", "show.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
|
||||
}
|
||||
|
||||
private HandlerExecutionChain getHandler(MockHttpServletRequest req) throws Exception {
|
||||
HandlerExecutionChain hec = hm.getHandler(req);
|
||||
HandlerInterceptor[] interceptors = hec.getInterceptors();
|
||||
if (interceptors != null) {
|
||||
for (HandlerInterceptor interceptor : interceptors) {
|
||||
interceptor.preHandle(req, null, hec.getHandler());
|
||||
}
|
||||
}
|
||||
return hec;
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user