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:
Chris Beams
2012-01-20 22:51:02 +01:00
parent b6cb514d38
commit 02a4473c62
5671 changed files with 20 additions and 32 deletions

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -0,0 +1,87 @@
/*
* 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.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);
Integer[][] getNestedIntegerArray();
Integer[] getSomeIntegerArray();
void setSomeIntegerArray(Integer[] someIntegerArray);
void setNestedIntegerArray(Integer[][] nestedIntegerArray);
int[] getSomeIntArray();
void setSomeIntArray(int[] someIntArray);
int[][] getNestedIntArray();
void setNestedIntArray(int[][] someNestedArray);
/**
* 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;
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,467 @@
/*
* 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.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 Integer[][] nestedIntegerArray;
private int[] someIntArray;
private int[][] nestedIntArray;
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 setConcreteSpouse(TestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public TestBean getConcreteSpouse() {
return (spouses != null ? (TestBean) 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 Integer[][] getNestedIntegerArray() {
return nestedIntegerArray;
}
public void setNestedIntegerArray(Integer[][] nestedIntegerArray) {
this.nestedIntegerArray = nestedIntegerArray;
}
public int[] getSomeIntArray() {
return someIntArray;
}
public void setSomeIntArray(int[] someIntArray) {
this.someIntArray = someIntArray;
}
public int[][] getNestedIntArray() {
return nestedIntArray;
}
public void setNestedIntArray(int[][] nestedIntArray) {
this.nestedIntArray = nestedIntArray;
}
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;
}
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
public Object returnsThis() {
return this;
}
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;
}
}

View File

@@ -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);
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.core.task;
/**
* @author Juergen Hoeller
*/
public class MockRunnable implements Runnable {
private boolean executed = false;
public void run() {
this.executed = true;
}
public boolean wasExecuted() {
return this.executed;
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* @author Arjen Poutsma
*/
public class HttpEntityTests {
@Test
public void noHeaders() {
String body = "foo";
HttpEntity<String> entity = new HttpEntity<String>(body);
assertSame(body, entity.getBody());
assertTrue(entity.getHeaders().isEmpty());
}
@Test
public void httpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
String body = "foo";
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
assertEquals(body, entity.getBody());
assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType());
assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
}
@Test
public void multiValueMap() {
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.set("Content-Type", "text/plain");
String body = "foo";
HttpEntity<String> entity = new HttpEntity<String>(body, map);
assertEquals(body, entity.getBody());
assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType());
assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
}
@Test
public void responseEntity() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
String body = "foo";
ResponseEntity<String> entity = new ResponseEntity<String>(body, headers, HttpStatus.OK);
assertEquals(body, entity.getBody());
assertEquals(MediaType.TEXT_PLAIN, entity.getHeaders().getContentType());
assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
assertEquals("text/plain", entity.getHeaders().getFirst("Content-Type"));
}
}

View File

@@ -0,0 +1,242 @@
/*
* 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.http;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.EnumSet;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/** @author Arjen Poutsma */
public class HttpHeadersTests {
private HttpHeaders headers;
@Before
public void setUp() {
headers = new HttpHeaders();
}
@Test
public void accept() {
MediaType mediaType1 = new MediaType("text", "html");
MediaType mediaType2 = new MediaType("text", "plain");
List<MediaType> mediaTypes = new ArrayList<MediaType>(2);
mediaTypes.add(mediaType1);
mediaTypes.add(mediaType2);
headers.setAccept(mediaTypes);
assertEquals("Invalid Accept header", mediaTypes, headers.getAccept());
assertEquals("Invalid Accept header", "text/html, text/plain", headers.getFirst("Accept"));
}
@Test
public void acceptCharsets() {
Charset charset1 = Charset.forName("UTF-8");
Charset charset2 = Charset.forName("ISO-8859-1");
List<Charset> charsets = new ArrayList<Charset>(2);
charsets.add(charset1);
charsets.add(charset2);
headers.setAcceptCharset(charsets);
assertEquals("Invalid Accept header", charsets, headers.getAcceptCharset());
assertEquals("Invalid Accept header", "utf-8, iso-8859-1", headers.getFirst("Accept-Charset"));
}
@Test
public void acceptCharsetWildcard() {
headers.set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
assertEquals("Invalid Accept header", Arrays.asList(Charset.forName("ISO-8859-1"), Charset.forName("UTF-8")),
headers.getAcceptCharset());
}
@Test
public void allow() {
EnumSet<HttpMethod> methods = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
headers.setAllow(methods);
assertEquals("Invalid Allow header", methods, headers.getAllow());
assertEquals("Invalid Allow header", "GET,POST", headers.getFirst("Allow"));
}
@Test
public void contentLength() {
long length = 42L;
headers.setContentLength(length);
assertEquals("Invalid Content-Length header", length, headers.getContentLength());
assertEquals("Invalid Content-Length header", "42", headers.getFirst("Content-Length"));
}
@Test
public void contentType() {
MediaType contentType = new MediaType("text", "html", Charset.forName("UTF-8"));
headers.setContentType(contentType);
assertEquals("Invalid Content-Type header", contentType, headers.getContentType());
assertEquals("Invalid Content-Type header", "text/html;charset=UTF-8", headers.getFirst("Content-Type"));
}
@Test
public void location() throws URISyntaxException {
URI location = new URI("http://www.example.com/hotels");
headers.setLocation(location);
assertEquals("Invalid Location header", location, headers.getLocation());
assertEquals("Invalid Location header", "http://www.example.com/hotels", headers.getFirst("Location"));
}
@Test
public void eTag() {
String eTag = "\"v2.6\"";
headers.setETag(eTag);
assertEquals("Invalid ETag header", eTag, headers.getETag());
assertEquals("Invalid ETag header", "\"v2.6\"", headers.getFirst("ETag"));
}
@Test(expected = IllegalArgumentException.class)
public void illegalETag() {
String eTag = "v2.6";
headers.setETag(eTag);
assertEquals("Invalid ETag header", eTag, headers.getETag());
assertEquals("Invalid ETag header", "\"v2.6\"", headers.getFirst("ETag"));
}
@Test
public void ifNoneMatch() {
String ifNoneMatch = "\"v2.6\"";
headers.setIfNoneMatch(ifNoneMatch);
assertEquals("Invalid If-None-Match header", ifNoneMatch, headers.getIfNoneMatch().get(0));
assertEquals("Invalid If-None-Match header", "\"v2.6\"", headers.getFirst("If-None-Match"));
}
@Test
public void ifNoneMatchList() {
String ifNoneMatch1 = "\"v2.6\"";
String ifNoneMatch2 = "\"v2.7\"";
List<String> ifNoneMatchList = new ArrayList<String>(2);
ifNoneMatchList.add(ifNoneMatch1);
ifNoneMatchList.add(ifNoneMatch2);
headers.setIfNoneMatch(ifNoneMatchList);
assertEquals("Invalid If-None-Match header", ifNoneMatchList, headers.getIfNoneMatch());
assertEquals("Invalid If-None-Match header", "\"v2.6\", \"v2.7\"", headers.getFirst("If-None-Match"));
}
@Test
public void date() {
Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
long date = calendar.getTimeInMillis();
headers.setDate(date);
assertEquals("Invalid Date header", date, headers.getDate());
assertEquals("Invalid Date header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("date"));
// RFC 850
headers.set("Date", "Thursday, 18-Dec-08 11:20:00 CET");
assertEquals("Invalid Date header", date, headers.getDate());
}
@Test(expected = IllegalArgumentException.class)
public void dateInvalid() {
headers.set("Date", "Foo Bar Baz");
headers.getDate();
}
@Test
public void dateOtherLocale() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(new Locale("nl", "nl"));
Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
long date = calendar.getTimeInMillis();
headers.setDate(date);
assertEquals("Invalid Date header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("date"));
assertEquals("Invalid Date header", date, headers.getDate());
}
finally {
Locale.setDefault(defaultLocale);
}
}
@Test
public void lastModified() {
Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
long date = calendar.getTimeInMillis();
headers.setLastModified(date);
assertEquals("Invalid Last-Modified header", date, headers.getLastModified());
assertEquals("Invalid Last-Modified header", "Thu, 18 Dec 2008 10:20:00 GMT",
headers.getFirst("last-modified"));
}
@Test
public void expires() {
Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
long date = calendar.getTimeInMillis();
headers.setExpires(date);
assertEquals("Invalid Expires header", date, headers.getExpires());
assertEquals("Invalid Expires header", "Thu, 18 Dec 2008 10:20:00 GMT", headers.getFirst("expires"));
}
@Test
public void ifModifiedSince() {
Calendar calendar = new GregorianCalendar(2008, 11, 18, 11, 20);
calendar.setTimeZone(TimeZone.getTimeZone("CET"));
long date = calendar.getTimeInMillis();
headers.setIfModifiedSince(date);
assertEquals("Invalid If-Modified-Since header", date, headers.getIfNotModifiedSince());
assertEquals("Invalid If-Modified-Since header", "Thu, 18 Dec 2008 10:20:00 GMT",
headers.getFirst("if-modified-since"));
}
@Test
public void pragma() {
String pragma = "no-cache";
headers.setPragma(pragma);
assertEquals("Invalid Pragma header", pragma, headers.getPragma());
assertEquals("Invalid Pragma header", "no-cache", headers.getFirst("pragma"));
}
@Test
public void cacheControl() {
String cacheControl = "no-cache";
headers.setCacheControl(cacheControl);
assertEquals("Invalid Cache-Control header", cacheControl, headers.getCacheControl());
assertEquals("Invalid Cache-Control header", "no-cache", headers.getFirst("cache-control"));
}
@Test
public void contentDisposition() {
headers.setContentDispositionFormData("name", null);
assertEquals("Invalid Content-Disposition header", "form-data; name=\"name\"",
headers.getFirst("Content-Disposition"));
headers.setContentDispositionFormData("name", "filename");
assertEquals("Invalid Content-Disposition header", "form-data; name=\"name\"; filename=\"filename\"",
headers.getFirst("Content-Disposition"));
}
}

View File

@@ -0,0 +1,125 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/** @author Arjen Poutsma */
public class HttpStatusTests {
private Map<Integer, String> statusCodes = new LinkedHashMap<Integer, String>();
@Before
public void createStatusCodes() {
statusCodes.put(100, "CONTINUE");
statusCodes.put(101, "SWITCHING_PROTOCOLS");
statusCodes.put(102, "PROCESSING");
statusCodes.put(103, "CHECKPOINT");
statusCodes.put(200, "OK");
statusCodes.put(201, "CREATED");
statusCodes.put(202, "ACCEPTED");
statusCodes.put(203, "NON_AUTHORITATIVE_INFORMATION");
statusCodes.put(204, "NO_CONTENT");
statusCodes.put(205, "RESET_CONTENT");
statusCodes.put(206, "PARTIAL_CONTENT");
statusCodes.put(207, "MULTI_STATUS");
statusCodes.put(208, "ALREADY_REPORTED");
statusCodes.put(226, "IM_USED");
statusCodes.put(300, "MULTIPLE_CHOICES");
statusCodes.put(301, "MOVED_PERMANENTLY");
statusCodes.put(302, "FOUND");
statusCodes.put(303, "SEE_OTHER");
statusCodes.put(304, "NOT_MODIFIED");
statusCodes.put(305, "USE_PROXY");
statusCodes.put(307, "TEMPORARY_REDIRECT");
statusCodes.put(308, "RESUME_INCOMPLETE");
statusCodes.put(400, "BAD_REQUEST");
statusCodes.put(401, "UNAUTHORIZED");
statusCodes.put(402, "PAYMENT_REQUIRED");
statusCodes.put(403, "FORBIDDEN");
statusCodes.put(404, "NOT_FOUND");
statusCodes.put(405, "METHOD_NOT_ALLOWED");
statusCodes.put(406, "NOT_ACCEPTABLE");
statusCodes.put(407, "PROXY_AUTHENTICATION_REQUIRED");
statusCodes.put(408, "REQUEST_TIMEOUT");
statusCodes.put(409, "CONFLICT");
statusCodes.put(410, "GONE");
statusCodes.put(411, "LENGTH_REQUIRED");
statusCodes.put(412, "PRECONDITION_FAILED");
statusCodes.put(413, "REQUEST_ENTITY_TOO_LARGE");
statusCodes.put(414, "REQUEST_URI_TOO_LONG");
statusCodes.put(415, "UNSUPPORTED_MEDIA_TYPE");
statusCodes.put(416, "REQUESTED_RANGE_NOT_SATISFIABLE");
statusCodes.put(417, "EXPECTATION_FAILED");
statusCodes.put(418, "I_AM_A_TEAPOT");
statusCodes.put(419, "INSUFFICIENT_SPACE_ON_RESOURCE");
statusCodes.put(420, "METHOD_FAILURE");
statusCodes.put(421, "DESTINATION_LOCKED");
statusCodes.put(422, "UNPROCESSABLE_ENTITY");
statusCodes.put(423, "LOCKED");
statusCodes.put(424, "FAILED_DEPENDENCY");
statusCodes.put(426, "UPGRADE_REQUIRED");
statusCodes.put(428, "PRECONDITION_REQUIRED");
statusCodes.put(429, "TOO_MANY_REQUESTS");
statusCodes.put(431, "REQUEST_HEADER_FIELDS_TOO_LARGE");
statusCodes.put(500, "INTERNAL_SERVER_ERROR");
statusCodes.put(501, "NOT_IMPLEMENTED");
statusCodes.put(502, "BAD_GATEWAY");
statusCodes.put(503, "SERVICE_UNAVAILABLE");
statusCodes.put(504, "GATEWAY_TIMEOUT");
statusCodes.put(505, "HTTP_VERSION_NOT_SUPPORTED");
statusCodes.put(506, "VARIANT_ALSO_NEGOTIATES");
statusCodes.put(507, "INSUFFICIENT_STORAGE");
statusCodes.put(508, "LOOP_DETECTED");
statusCodes.put(509, "BANDWIDTH_LIMIT_EXCEEDED");
statusCodes.put(510, "NOT_EXTENDED");
statusCodes.put(511, "NETWORK_AUTHENTICATION_REQUIRED");
}
@Test
public void fromMapToEnum() {
for (Map.Entry<Integer, String> entry : statusCodes.entrySet()) {
int value = entry.getKey();
HttpStatus status = HttpStatus.valueOf(value);
assertEquals("Invalid value", value, status.value());
assertEquals("Invalid name for [" + value + "]", entry.getValue(), status.name());
}
}
@Test
public void fromEnumToMap() {
for (HttpStatus status : HttpStatus.values()) {
int value = status.value();
if (value == 302) {
continue;
}
assertTrue("Map has no value for [" + value + "]", statusCodes.containsKey(value));
assertEquals("Invalid name for [" + value + "]", statusCodes.get(value), status.name());
}
}
}

View File

@@ -0,0 +1,515 @@
/*
* 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.http;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
* @author Juergen Hoeller
*/
public class MediaTypeTests {
@Test
public void includes() throws Exception {
MediaType textPlain = MediaType.TEXT_PLAIN;
assertTrue("Equal types is not inclusive", textPlain.includes(textPlain));
MediaType allText = new MediaType("text");
assertTrue("All subtypes is not inclusive", allText.includes(textPlain));
assertFalse("All subtypes is inclusive", textPlain.includes(allText));
assertTrue("All types is not inclusive", MediaType.ALL.includes(textPlain));
assertFalse("All types is inclusive", textPlain.includes(MediaType.ALL));
assertTrue("All types is not inclusive", MediaType.ALL.includes(textPlain));
assertFalse("All types is inclusive", textPlain.includes(MediaType.ALL));
MediaType applicationSoapXml = new MediaType("application", "soap+xml");
MediaType applicationWildcardXml = new MediaType("application", "*+xml");
assertTrue(applicationSoapXml.includes(applicationSoapXml));
assertTrue(applicationWildcardXml.includes(applicationWildcardXml));
assertTrue(applicationWildcardXml.includes(applicationSoapXml));
assertFalse(applicationSoapXml.includes(applicationWildcardXml));
}
@Test
public void isCompatible() throws Exception {
MediaType textPlain = MediaType.TEXT_PLAIN;
assertTrue("Equal types is not compatible", textPlain.isCompatibleWith(textPlain));
MediaType allText = new MediaType("text");
assertTrue("All subtypes is not compatible", allText.isCompatibleWith(textPlain));
assertTrue("All subtypes is not compatible", textPlain.isCompatibleWith(allText));
assertTrue("All types is not compatible", MediaType.ALL.isCompatibleWith(textPlain));
assertTrue("All types is not compatible", textPlain.isCompatibleWith(MediaType.ALL));
assertTrue("All types is not compatible", MediaType.ALL.isCompatibleWith(textPlain));
assertTrue("All types is compatible", textPlain.isCompatibleWith(MediaType.ALL));
MediaType applicationSoapXml = new MediaType("application", "soap+xml");
MediaType applicationWildcardXml = new MediaType("application", "*+xml");
assertTrue(applicationSoapXml.isCompatibleWith(applicationSoapXml));
assertTrue(applicationWildcardXml.isCompatibleWith(applicationWildcardXml));
assertTrue(applicationWildcardXml.isCompatibleWith(applicationSoapXml));
assertTrue(applicationSoapXml.isCompatibleWith(applicationWildcardXml));
}
@Test
public void testToString() throws Exception {
MediaType mediaType = new MediaType("text", "plain", 0.7);
String result = mediaType.toString();
assertEquals("Invalid toString() returned", "text/plain;q=0.7", result);
}
@Test(expected= IllegalArgumentException.class)
public void slashInType() {
new MediaType("text/plain");
}
@Test(expected= IllegalArgumentException.class)
public void slashInSubtype() {
new MediaType("text", "/");
}
@Test
public void getDefaultQualityValue() {
MediaType mediaType = new MediaType("text", "plain");
assertEquals("Invalid quality value", 1, mediaType.getQualityValue(), 0D);
}
@Test
public void parseMediaType() throws Exception {
String s = "audio/*; q=0.2";
MediaType mediaType = MediaType.parseMediaType(s);
assertEquals("Invalid type", "audio", mediaType.getType());
assertEquals("Invalid subtype", "*", mediaType.getSubtype());
assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D);
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeNoSubtype() {
MediaType.parseMediaType("audio");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeNoSubtypeSlash() {
MediaType.parseMediaType("audio/");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeTypeRange() {
MediaType.parseMediaType("*/json");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalType() {
MediaType.parseMediaType("audio(/basic");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalSubtype() {
MediaType.parseMediaType("audio/basic)");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeEmptyParameterAttribute() {
MediaType.parseMediaType("audio/*;=value");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeEmptyParameterValue() {
MediaType.parseMediaType("audio/*;attr=");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalParameterAttribute() {
MediaType.parseMediaType("audio/*;attr<=value");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalParameterValue() {
MediaType.parseMediaType("audio/*;attr=v>alue");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalQualityFactor() {
MediaType.parseMediaType("audio/basic;q=1.1");
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalCharset() {
MediaType.parseMediaType("text/html; charset=foo-bar");
}
// SPR-8917
@Test
public void parseMediaTypeQuotedParameterValue() {
MediaType mediaType = MediaType.parseMediaType("audio/*;attr=\"v>alue\"");
assertEquals("\"v>alue\"", mediaType.getParameter("attr"));
}
@Test(expected = IllegalArgumentException.class)
public void parseMediaTypeIllegalQuotedParameterValue() {
MediaType.parseMediaType("audio/*;attr=\"");
}
@Test
public void parseCharset() throws Exception {
String s = "text/html; charset=iso-8859-1";
MediaType mediaType = MediaType.parseMediaType(s);
assertEquals("Invalid type", "text", mediaType.getType());
assertEquals("Invalid subtype", "html", mediaType.getSubtype());
assertEquals("Invalid charset", Charset.forName("ISO-8859-1"), mediaType.getCharSet());
}
@Test
public void parseQuotedCharset() {
String s = "application/xml;charset=\"utf-8\"";
MediaType mediaType = MediaType.parseMediaType(s);
assertEquals("Invalid type", "application", mediaType.getType());
assertEquals("Invalid subtype", "xml", mediaType.getSubtype());
assertEquals("Invalid charset", Charset.forName("UTF-8"), mediaType.getCharSet());
}
@Test
public void parseURLConnectionMediaType() throws Exception {
String s = "*; q=.2";
MediaType mediaType = MediaType.parseMediaType(s);
assertEquals("Invalid type", "*", mediaType.getType());
assertEquals("Invalid subtype", "*", mediaType.getSubtype());
assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D);
}
@Test
public void parseMediaTypes() throws Exception {
String s = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c";
List<MediaType> mediaTypes = MediaType.parseMediaTypes(s);
assertNotNull("No media types returned", mediaTypes);
assertEquals("Invalid amount of media types", 4, mediaTypes.size());
mediaTypes = MediaType.parseMediaTypes(null);
assertNotNull("No media types returned", mediaTypes);
assertEquals("Invalid amount of media types", 0, mediaTypes.size());
}
@Test
public void compareTo() {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1"));
MediaType audioBasic07 = new MediaType("audio", "basic", 0.7);
// equal
assertEquals("Invalid comparison result", 0, audioBasic.compareTo(audioBasic));
assertEquals("Invalid comparison result", 0, audio.compareTo(audio));
assertEquals("Invalid comparison result", 0, audioBasicLevel.compareTo(audioBasicLevel));
assertTrue("Invalid comparison result", audioBasicLevel.compareTo(audio) > 0);
List<MediaType> expected = new ArrayList<MediaType>();
expected.add(audio);
expected.add(audioBasic);
expected.add(audioBasicLevel);
expected.add(audioBasic07);
expected.add(audioWave);
List<MediaType> result = new ArrayList<MediaType>(expected);
Random rnd = new Random();
// shuffle & sort 10 times
for (int i = 0; i < 10; i++) {
Collections.shuffle(result, rnd);
Collections.sort(result);
for (int j = 0; j < result.size(); j++) {
assertSame("Invalid media type at " + j + ", run " + i, expected.get(j), result.get(j));
}
}
}
@Test
public void compareToConsistentWithEquals() {
MediaType m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1");
MediaType m2 = MediaType.parseMediaType("text/html; charset=iso-8859-1; q=0.7");
assertEquals("Media types not equal", m1, m2);
assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2));
assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1));
m1 = MediaType.parseMediaType("text/html; q=0.7; charset=iso-8859-1");
m2 = MediaType.parseMediaType("text/html; Q=0.7; charset=iso-8859-1");
assertEquals("Media types not equal", m1, m2);
assertEquals("compareTo() not consistent with equals", 0, m1.compareTo(m2));
assertEquals("compareTo() not consistent with equals", 0, m2.compareTo(m1));
}
@Test
public void compareToCaseSensitivity() {
MediaType m1 = new MediaType("audio", "basic");
MediaType m2 = new MediaType("Audio", "Basic");
assertEquals("Invalid comparison result", 0, m1.compareTo(m2));
assertEquals("Invalid comparison result", 0, m2.compareTo(m1));
m1 = new MediaType("audio", "basic", Collections.singletonMap("foo", "bar"));
m2 = new MediaType("audio", "basic", Collections.singletonMap("Foo", "bar"));
assertEquals("Invalid comparison result", 0, m1.compareTo(m2));
assertEquals("Invalid comparison result", 0, m2.compareTo(m1));
m1 = new MediaType("audio", "basic", Collections.singletonMap("foo", "bar"));
m2 = new MediaType("audio", "basic", Collections.singletonMap("foo", "Bar"));
assertTrue("Invalid comparison result", m1.compareTo(m2) != 0);
assertTrue("Invalid comparison result", m2.compareTo(m1) != 0);
}
@Test
public void specificityComparator() throws Exception {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1"));
MediaType textHtml = new MediaType("text", "html");
MediaType all = MediaType.ALL;
Comparator<MediaType> comp = MediaType.SPECIFICITY_COMPARATOR;
// equal
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic,audioBasic));
assertEquals("Invalid comparison result", 0, comp.compare(audio, audio));
assertEquals("Invalid comparison result", 0, comp.compare(audio07, audio07));
assertEquals("Invalid comparison result", 0, comp.compare(audio03, audio03));
assertEquals("Invalid comparison result", 0, comp.compare(audioBasicLevel, audioBasicLevel));
// specific to unspecific
assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0);
assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0);
assertTrue("Invalid comparison result", comp.compare(audio, all) < 0);
// unspecific to specific
assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0);
assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0);
assertTrue("Invalid comparison result", comp.compare(all, audio) > 0);
// qualifiers
assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0);
assertTrue("Invalid comparison result", comp.compare(audio07, audio) > 0);
assertTrue("Invalid comparison result", comp.compare(audio07, audio03) < 0);
assertTrue("Invalid comparison result", comp.compare(audio03, audio07) > 0);
assertTrue("Invalid comparison result", comp.compare(audio03, all) < 0);
assertTrue("Invalid comparison result", comp.compare(all, audio03) > 0);
// other parameters
assertTrue("Invalid comparison result", comp.compare(audioBasic, audioBasicLevel) > 0);
assertTrue("Invalid comparison result", comp.compare(audioBasicLevel, audioBasic) < 0);
// different types
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, textHtml));
assertEquals("Invalid comparison result", 0, comp.compare(textHtml, audioBasic));
// different subtypes
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, audioWave));
assertEquals("Invalid comparison result", 0, comp.compare(audioWave, audioBasic));
}
@Test
public void sortBySpecificityRelated() {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1"));
MediaType all = MediaType.ALL;
List<MediaType> expected = new ArrayList<MediaType>();
expected.add(audioBasicLevel);
expected.add(audioBasic);
expected.add(audio);
expected.add(audio07);
expected.add(audio03);
expected.add(all);
List<MediaType> result = new ArrayList<MediaType>(expected);
Random rnd = new Random();
// shuffle & sort 10 times
for (int i = 0; i < 10; i++) {
Collections.shuffle(result, rnd);
MediaType.sortBySpecificity(result);
for (int j = 0; j < result.size(); j++) {
assertSame("Invalid media type at " + j, expected.get(j), result.get(j));
}
}
}
@Test
public void sortBySpecificityUnrelated() {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType textHtml = new MediaType("text", "html");
List<MediaType> expected = new ArrayList<MediaType>();
expected.add(textHtml);
expected.add(audioBasic);
expected.add(audioWave);
List<MediaType> result = new ArrayList<MediaType>(expected);
MediaType.sortBySpecificity(result);
for (int i = 0; i < result.size(); i++) {
assertSame("Invalid media type at " + i, expected.get(i), result.get(i));
}
}
@Test
public void qualityComparator() throws Exception {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1"));
MediaType textHtml = new MediaType("text", "html");
MediaType all = MediaType.ALL;
Comparator<MediaType> comp = MediaType.QUALITY_VALUE_COMPARATOR;
// equal
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic,audioBasic));
assertEquals("Invalid comparison result", 0, comp.compare(audio, audio));
assertEquals("Invalid comparison result", 0, comp.compare(audio07, audio07));
assertEquals("Invalid comparison result", 0, comp.compare(audio03, audio03));
assertEquals("Invalid comparison result", 0, comp.compare(audioBasicLevel, audioBasicLevel));
// specific to unspecific
assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0);
assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0);
assertTrue("Invalid comparison result", comp.compare(audio, all) < 0);
// unspecific to specific
assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0);
assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0);
assertTrue("Invalid comparison result", comp.compare(all, audio) > 0);
// qualifiers
assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0);
assertTrue("Invalid comparison result", comp.compare(audio07, audio) > 0);
assertTrue("Invalid comparison result", comp.compare(audio07, audio03) < 0);
assertTrue("Invalid comparison result", comp.compare(audio03, audio07) > 0);
assertTrue("Invalid comparison result", comp.compare(audio03, all) > 0);
assertTrue("Invalid comparison result", comp.compare(all, audio03) < 0);
// other parameters
assertTrue("Invalid comparison result", comp.compare(audioBasic, audioBasicLevel) > 0);
assertTrue("Invalid comparison result", comp.compare(audioBasicLevel, audioBasic) < 0);
// different types
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, textHtml));
assertEquals("Invalid comparison result", 0, comp.compare(textHtml, audioBasic));
// different subtypes
assertEquals("Invalid comparison result", 0, comp.compare(audioBasic, audioWave));
assertEquals("Invalid comparison result", 0, comp.compare(audioWave, audioBasic));
}
@Test
public void sortByQualityRelated() {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audio = new MediaType("audio");
MediaType audio03 = new MediaType("audio", "*", 0.3);
MediaType audio07 = new MediaType("audio", "*", 0.7);
MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1"));
MediaType all = MediaType.ALL;
List<MediaType> expected = new ArrayList<MediaType>();
expected.add(audioBasicLevel);
expected.add(audioBasic);
expected.add(audio);
expected.add(all);
expected.add(audio07);
expected.add(audio03);
List<MediaType> result = new ArrayList<MediaType>(expected);
Random rnd = new Random();
// shuffle & sort 10 times
for (int i = 0; i < 10; i++) {
Collections.shuffle(result, rnd);
MediaType.sortByQualityValue(result);
for (int j = 0; j < result.size(); j++) {
assertSame("Invalid media type at " + j, expected.get(j), result.get(j));
}
}
}
@Test
public void sortByQualityUnrelated() {
MediaType audioBasic = new MediaType("audio", "basic");
MediaType audioWave = new MediaType("audio", "wave");
MediaType textHtml = new MediaType("text", "html");
List<MediaType> expected = new ArrayList<MediaType>();
expected.add(textHtml);
expected.add(audioBasic);
expected.add(audioWave);
List<MediaType> result = new ArrayList<MediaType>(expected);
MediaType.sortBySpecificity(result);
for (int i = 0; i < result.size(); i++) {
assertSame("Invalid media type at " + i, expected.get(i), result.get(i));
}
}
@Test
public void testWithConversionService() {
ConversionService conversionService = new DefaultConversionService();
assertTrue(conversionService.canConvert(String.class, MediaType.class));
MediaType mediaType = MediaType.parseMediaType("application/xml");
assertEquals(mediaType, conversionService.convert("application/xml", MediaType.class));
}
@Test
public void isConcrete() {
assertTrue("text/plain not concrete", MediaType.TEXT_PLAIN.isConcrete());
assertFalse("*/* concrete", MediaType.ALL.isConcrete());
assertFalse("text/* concrete", new MediaType("text", "*").isConcrete());
}
}

View File

@@ -0,0 +1,51 @@
/*
* 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.http;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.util.Assert;
/**
* @author Arjen Poutsma
*/
public class MockHttpInputMessage implements HttpInputMessage {
private final HttpHeaders headers = new HttpHeaders();
private final InputStream body;
public MockHttpInputMessage(byte[] contents) {
Assert.notNull(contents, "'contents' must not be null");
this.body = new ByteArrayInputStream(contents);
}
public MockHttpInputMessage(InputStream body) {
Assert.notNull(body, "'body' must not be null");
this.body = body;
}
public HttpHeaders getHeaders() {
return headers;
}
public InputStream getBody() throws IOException {
return body;
}
}

View File

@@ -0,0 +1,49 @@
/*
* 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.http;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @author Arjen Poutsma
*/
public class MockHttpOutputMessage implements HttpOutputMessage {
private final HttpHeaders headers = new HttpHeaders();
private final ByteArrayOutputStream body = new ByteArrayOutputStream();
public HttpHeaders getHeaders() {
return headers;
}
public OutputStream getBody() throws IOException {
return body;
}
public byte[] getBodyAsBytes() {
return body.toByteArray();
}
public String getBodyAsString(Charset charset) {
byte[] bytes = getBodyAsBytes();
return new String(bytes, charset);
}
}

View File

@@ -0,0 +1,255 @@
/*
* 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.http.client;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public abstract class AbstractHttpRequestFactoryTestCase {
protected ClientHttpRequestFactory factory;
protected static String baseUrl;
private static Server jettyServer;
@BeforeClass
public static void startJettyServer() throws Exception {
int port = FreePortScanner.getFreePort();
jettyServer = new Server(port);
baseUrl = "http://localhost:" + port;
Context jettyContext = new Context(jettyServer, "/");
jettyContext.addServlet(new ServletHolder(new EchoServlet()), "/echo");
jettyContext.addServlet(new ServletHolder(new StatusServlet(200)), "/status/ok");
jettyContext.addServlet(new ServletHolder(new StatusServlet(404)), "/status/notfound");
jettyContext.addServlet(new ServletHolder(new MethodServlet("DELETE")), "/methods/delete");
jettyContext.addServlet(new ServletHolder(new MethodServlet("GET")), "/methods/get");
jettyContext.addServlet(new ServletHolder(new MethodServlet("HEAD")), "/methods/head");
jettyContext.addServlet(new ServletHolder(new MethodServlet("OPTIONS")), "/methods/options");
jettyContext.addServlet(new ServletHolder(new PostServlet()), "/methods/post");
jettyContext.addServlet(new ServletHolder(new MethodServlet("PUT")), "/methods/put");
jettyServer.start();
}
@Before
public final void createFactory() {
factory = createRequestFactory();
}
protected abstract ClientHttpRequestFactory createRequestFactory();
@AfterClass
public static void stopJettyServer() throws Exception {
if (jettyServer != null) {
jettyServer.stop();
}
}
@Test
public void status() throws Exception {
URI uri = new URI(baseUrl + "/status/notfound");
ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET);
assertEquals("Invalid HTTP method", HttpMethod.GET, request.getMethod());
assertEquals("Invalid HTTP URI", uri, request.getURI());
ClientHttpResponse response = request.execute();
assertEquals("Invalid status code", HttpStatus.NOT_FOUND, response.getStatusCode());
}
@Test
public void echo() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
String headerName = "MyHeader";
String headerValue1 = "value1";
request.getHeaders().add(headerName, headerValue1);
String headerValue2 = "value2";
request.getHeaders().add(headerName, headerValue2);
byte[] body = "Hello World".getBytes("UTF-8");
request.getHeaders().setContentLength(body.length);
FileCopyUtils.copy(body, request.getBody());
ClientHttpResponse response = request.execute();
try {
assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
assertTrue("Header not found", response.getHeaders().containsKey(headerName));
assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
response.getHeaders().get(headerName));
byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
assertTrue("Invalid body", Arrays.equals(body, result));
}
finally {
response.close();
}
}
@Test(expected = IllegalStateException.class)
public void multipleWrites() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
byte[] body = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(body, request.getBody());
ClientHttpResponse response = request.execute();
try {
FileCopyUtils.copy(body, request.getBody());
}
finally {
response.close();
}
}
@Test(expected = UnsupportedOperationException.class)
public void headersAfterExecute() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
request.getHeaders().add("MyHeader", "value");
byte[] body = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(body, request.getBody());
ClientHttpResponse response = request.execute();
try {
request.getHeaders().add("MyHeader", "value");
}
finally {
response.close();
}
}
@Test
public void httpMethods() throws Exception {
assertHttpMethod("get", HttpMethod.GET);
assertHttpMethod("head", HttpMethod.HEAD);
assertHttpMethod("post", HttpMethod.POST);
assertHttpMethod("put", HttpMethod.PUT);
assertHttpMethod("options", HttpMethod.OPTIONS);
assertHttpMethod("delete", HttpMethod.DELETE);
}
private void assertHttpMethod(String path, HttpMethod method) throws Exception {
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method);
response = request.execute();
assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode());
assertEquals("Invalid method", path.toUpperCase(Locale.ENGLISH), request.getMethod().name());
}
finally {
if (response != null) {
response.close();
}
}
}
/**
* Servlet that sets a given status code.
*/
private static class StatusServlet extends GenericServlet {
private final int sc;
private StatusServlet(int sc) {
this.sc = sc;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
((HttpServletResponse) response).setStatus(sc);
}
}
private static class MethodServlet extends GenericServlet {
private final String method;
private MethodServlet(String method) {
this.method = method;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest httpReq = (HttpServletRequest) req;
assertEquals("Invalid HTTP method", method, httpReq.getMethod());
res.setContentLength(0);
((HttpServletResponse) res).setStatus(200);
}
}
private static class PostServlet extends MethodServlet {
private PostServlet() {
super("POST");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
super.service(req, res);
long contentLength = req.getContentLength();
if (contentLength != -1) {
InputStream in = req.getInputStream();
long byteCount = 0;
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
byteCount += bytesRead;
}
assertEquals("Invalid content-length", contentLength, byteCount);
}
}
}
private static class EchoServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
echo(req, resp);
}
private void echo(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
for (Enumeration e1 = request.getHeaderNames(); e1.hasMoreElements();) {
String headerName = (String) e1.nextElement();
for (Enumeration e2 = request.getHeaders(headerName); e2.hasMoreElements();) {
String headerValue = (String) e2.nextElement();
response.addHeader(headerName, headerValue);
}
}
FileCopyUtils.copy(request.getInputStream(), response.getOutputStream());
}
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.http.client;
public class BufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new SimpleClientHttpRequestFactory();
}
}

View File

@@ -0,0 +1,72 @@
/*
* 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.http.client;
import java.net.URI;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import static org.junit.Assert.*;
public class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory());
}
@Test
public void repeatableRead() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
String headerName = "MyHeader";
String headerValue1 = "value1";
request.getHeaders().add(headerName, headerValue1);
String headerValue2 = "value2";
request.getHeaders().add(headerName, headerValue2);
byte[] body = "Hello World".getBytes("UTF-8");
request.getHeaders().setContentLength(body.length);
FileCopyUtils.copy(body, request.getBody());
ClientHttpResponse response = request.execute();
try {
assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
assertTrue("Header not found", response.getHeaders().containsKey(headerName));
assertTrue("Header not found", response.getHeaders().containsKey(headerName));
assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
response.getHeaders().get(headerName));
assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
response.getHeaders().get(headerName));
byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
assertTrue("Invalid body", Arrays.equals(body, result));
FileCopyUtils.copyToByteArray(response.getBody());
assertTrue("Invalid body", Arrays.equals(body, result));
}
finally {
response.close();
}
}
}

View File

@@ -0,0 +1,29 @@
/*
* 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.http.client;
import org.springframework.http.client.AbstractHttpRequestFactoryTestCase;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.CommonsClientHttpRequestFactory;
public class CommonsHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new CommonsClientHttpRequestFactory();
}
}

View File

@@ -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
}
}
}
}

View File

@@ -0,0 +1,25 @@
/*
* 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.http.client;
public class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
return new HttpComponentsClientHttpRequestFactory();
}
}

View File

@@ -0,0 +1,313 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.support.HttpRequestWrapper;
import static org.junit.Assert.*;
/** @author Arjen Poutsma */
public class InterceptingClientHttpRequestFactoryTests {
private InterceptingClientHttpRequestFactory requestFactory;
private RequestFactoryMock requestFactoryMock;
private RequestMock requestMock;
private ResponseMock responseMock;
@Before
public void setUp() throws Exception {
requestFactoryMock = new RequestFactoryMock();
requestMock = new RequestMock();
responseMock = new ResponseMock();
}
@Test
public void basic() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new NoOpInterceptor());
interceptors.add(new NoOpInterceptor());
interceptors.add(new NoOpInterceptor());
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
ClientHttpResponse response = request.execute();
assertTrue(((NoOpInterceptor) interceptors.get(0)).invoked);
assertTrue(((NoOpInterceptor) interceptors.get(1)).invoked);
assertTrue(((NoOpInterceptor) interceptors.get(2)).invoked);
assertTrue(requestMock.executed);
assertSame(responseMock, response);
}
@Test
public void noExecution() throws Exception {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return responseMock;
}
});
interceptors.add(new NoOpInterceptor());
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
ClientHttpResponse response = request.execute();
assertFalse(((NoOpInterceptor) interceptors.get(1)).invoked);
assertFalse(requestMock.executed);
assertSame(responseMock, response);
}
@Test
public void changeHeaders() throws Exception {
final String headerName = "Foo";
final String headerValue = "Bar";
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.set(headerName, headerValue);
return headers;
}
}, body);
}
};
requestMock = new RequestMock() {
@Override
public ClientHttpResponse execute() throws IOException {
assertEquals(headerValue, getHeaders().getFirst(headerName));
return super.execute();
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
request.execute();
}
@Test
public void changeURI() throws Exception {
final URI changedUri = new URI("http://example.com/2");
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
@Override
public URI getURI() {
return changedUri;
}
}, body);
}
};
requestFactoryMock = new RequestFactoryMock() {
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
assertEquals(changedUri, uri);
return super.createRequest(uri, httpMethod);
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
request.execute();
}
@Test
public void changeMethod() throws Exception {
final HttpMethod changedMethod = HttpMethod.POST;
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
@Override
public HttpMethod getMethod() {
return changedMethod;
}
}, body);
}
};
requestFactoryMock = new RequestFactoryMock() {
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
assertEquals(changedMethod, httpMethod);
return super.createRequest(uri, httpMethod);
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
request.execute();
}
@Test
public void changeBody() throws Exception {
final byte[] changedBody = "Foo".getBytes();
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
return execution.execute(request, changedBody);
}
};
requestFactory =
new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET);
request.execute();
assertTrue(Arrays.equals(changedBody, requestMock.body.toByteArray()));
}
private static class NoOpInterceptor implements ClientHttpRequestInterceptor {
private boolean invoked = false;
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
invoked = true;
return execution.execute(request, body);
}
}
private class RequestFactoryMock implements ClientHttpRequestFactory {
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
requestMock.setURI(uri);
requestMock.setMethod(httpMethod);
return requestMock;
}
}
private class RequestMock implements ClientHttpRequest {
private URI uri;
private HttpMethod method;
private HttpHeaders headers = new HttpHeaders();
private ByteArrayOutputStream body = new ByteArrayOutputStream();
private boolean executed = false;
private RequestMock() {
}
public URI getURI() {
return uri;
}
public void setURI(URI uri) {
this.uri = uri;
}
public HttpMethod getMethod() {
return method;
}
public void setMethod(HttpMethod method) {
this.method = method;
}
public HttpHeaders getHeaders() {
return headers;
}
public OutputStream getBody() throws IOException {
return body;
}
public ClientHttpResponse execute() throws IOException {
executed = true;
return responseMock;
}
}
private static class ResponseMock implements ClientHttpResponse {
private HttpStatus statusCode = HttpStatus.OK;
private String statusText = "";
private HttpHeaders headers = new HttpHeaders();
public HttpStatus getStatusCode() throws IOException {
return statusCode;
}
public int getRawStatusCode() throws IOException {
return statusCode.value();
}
public String getStatusText() throws IOException {
return statusText;
}
public HttpHeaders getHeaders() {
return headers;
}
public InputStream getBody() throws IOException {
return null;
}
public void close() {
}
}
}

View File

@@ -0,0 +1,101 @@
/*
* 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.http.client;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Collections;
import java.util.Random;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class StreamingSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase {
@Override
protected ClientHttpRequestFactory createRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setBufferRequestBody(false);
return factory;
}
// SPR-8809
@Test
public void interceptor() throws Exception {
final String headerName = "MyHeader";
final String headerValue = "MyValue";
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
request.getHeaders().add(headerName, headerValue);
return execution.execute(request, body);
}
};
InterceptingClientHttpRequestFactory factory = new InterceptingClientHttpRequestFactory(createRequestFactory(),
Collections.singletonList(interceptor));
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.GET);
response = request.execute();
assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode());
HttpHeaders responseHeaders = response.getHeaders();
assertEquals("Custom header invalid", headerValue, responseHeaders.getFirst(headerName));
}
finally {
if (response != null) {
response.close();
}
}
}
@Test
@Ignore
public void largeFileUpload() throws Exception {
Random rnd = new Random();
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/post"), HttpMethod.POST);
final int BUF_SIZE = 4096;
final int ITERATIONS = Integer.MAX_VALUE / BUF_SIZE;
final int contentLength = ITERATIONS * BUF_SIZE;
// request.getHeaders().setContentLength(contentLength);
OutputStream body = request.getBody();
for (int i = 0; i < ITERATIONS; i++) {
byte[] buffer = new byte[BUF_SIZE];
rnd.nextBytes(buffer);
body.write(buffer);
}
response = request.execute();
assertEquals("Invalid response status", HttpStatus.OK, response.getStatusCode());
}
finally {
if (response != null) {
response.close();
}
}
}
}

View File

@@ -0,0 +1,74 @@
/*
* 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.support;
import java.net.InetSocketAddress;
import java.net.Proxy;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
/**
* @author Arjen Poutsma
*/
public class ProxyFactoryBeanTest {
ProxyFactoryBean factoryBean;
@Before
public void setUp() {
factoryBean = new ProxyFactoryBean();
}
@Test(expected = IllegalArgumentException.class)
public void noType() {
factoryBean.setType(null);
factoryBean.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void noHostname() {
factoryBean.setHostname("");
factoryBean.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void noPort() {
factoryBean.setHostname("example.com");
factoryBean.afterPropertiesSet();
}
@Test
public void normal() {
Proxy.Type type = Proxy.Type.HTTP;
factoryBean.setType(type);
String hostname = "example.com";
factoryBean.setHostname(hostname);
int port = 8080;
factoryBean.setPort(port);
factoryBean.afterPropertiesSet();
Proxy result = factoryBean.getObject();
assertEquals(type, result.type());
InetSocketAddress address = (InetSocketAddress) result.address();
assertEquals(hostname, address.getHostName());
assertEquals(port, address.getPort());
}
}

View File

@@ -0,0 +1,96 @@
/*
* 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.http.converter;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.util.FileCopyUtils;
public class BufferedImageHttpMessageConverterTests {
private BufferedImageHttpMessageConverter converter;
@Before
public void setUp() {
converter = new BufferedImageHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue("Image not supported", converter.canRead(BufferedImage.class, null));
assertTrue("Image not supported", converter.canRead(BufferedImage.class, new MediaType("image", "png")));
}
@Test
public void canWrite() {
assertTrue("Image not supported", converter.canWrite(BufferedImage.class, null));
assertTrue("Image not supported", converter.canWrite(BufferedImage.class, new MediaType("image", "png")));
}
@Test
public void read() throws IOException {
Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
byte[] body = FileCopyUtils.copyToByteArray(logo.getInputStream());
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(new MediaType("image", "jpeg"));
BufferedImage result = converter.read(BufferedImage.class, inputMessage);
assertEquals("Invalid height", 500, result.getHeight());
assertEquals("Invalid width", 750, result.getWidth());
}
@Test
public void write() throws IOException {
Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
BufferedImage body = ImageIO.read(logo.getFile());
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = new MediaType("image", "png");
converter.write(body, contentType, outputMessage);
assertEquals("Invalid content type", contentType, outputMessage.getHeaders().getContentType());
assertTrue("Invalid size", outputMessage.getBodyAsBytes().length > 0);
BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes()));
assertEquals("Invalid height", 500, result.getHeight());
assertEquals("Invalid width", 750, result.getWidth());
}
@Test
public void writeDefaultContentType() throws IOException {
Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
MediaType contentType = new MediaType("image", "png");
converter.setDefaultContentType(contentType);
BufferedImage body = ImageIO.read(logo.getFile());
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(body, contentType, outputMessage);
assertEquals("Invalid content type", contentType, outputMessage.getHeaders().getContentType());
assertTrue("Invalid size", outputMessage.getBodyAsBytes().length > 0);
BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes()));
assertEquals("Invalid height", 500, result.getHeight());
assertEquals("Invalid width", 750, result.getWidth());
}
}

View File

@@ -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.http.converter;
import java.io.IOException;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
/** @author Arjen Poutsma */
public class ByteArrayHttpMessageConverterTests {
private ByteArrayHttpMessageConverter converter;
@Before
public void setUp() {
converter = new ByteArrayHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue(converter.canRead(byte[].class, new MediaType("application", "octet-stream")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(byte[].class, new MediaType("application", "octet-stream")));
assertTrue(converter.canWrite(byte[].class, MediaType.ALL));
}
@Test
public void read() throws IOException {
byte[] body = new byte[]{0x1, 0x2};
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(new MediaType("application", "octet-stream"));
byte[] result = converter.read(byte[].class, inputMessage);
assertArrayEquals("Invalid result", body, result);
}
@Test
public void write() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
byte[] body = new byte[]{0x1, 0x2};
converter.write(body, null, outputMessage);
assertArrayEquals("Invalid result", body, outputMessage.getBodyAsBytes());
assertEquals("Invalid content-type", new MediaType("application", "octet-stream"),
outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", 2, outputMessage.getHeaders().getContentLength());
}
}

View File

@@ -0,0 +1,189 @@
/*
* 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.http.converter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.List;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
*/
public class FormHttpMessageConverterTests {
private FormHttpMessageConverter converter;
@Before
public void setUp() {
converter = new XmlAwareFormHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue(converter.canRead(MultiValueMap.class, new MediaType("application", "x-www-form-urlencoded")));
assertFalse(converter.canRead(MultiValueMap.class, new MediaType("multipart", "form-data")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(MultiValueMap.class, new MediaType("application", "x-www-form-urlencoded")));
assertTrue(converter.canWrite(MultiValueMap.class, new MediaType("multipart", "form-data")));
assertTrue(converter.canWrite(MultiValueMap.class, MediaType.ALL));
}
@Test
@SuppressWarnings("unchecked")
public void readForm() throws Exception {
String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
Charset iso88591 = Charset.forName("ISO-8859-1");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(iso88591));
inputMessage.getHeaders().setContentType(new MediaType("application", "x-www-form-urlencoded", iso88591));
MultiValueMap<String, String> result = converter.read(null, inputMessage);
assertEquals("Invalid result", 3, result.size());
assertEquals("Invalid result", "value 1", result.getFirst("name 1"));
List<String> values = result.get("name 2");
assertEquals("Invalid result", 2, values.size());
assertEquals("Invalid result", "value 2+1", values.get(0));
assertEquals("Invalid result", "value 2+2", values.get(1));
assertNull("Invalid result", result.getFirst("name 3"));
}
@Test
public void writeForm() throws IOException {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.set("name 1", "value 1");
body.add("name 2", "value 2+1");
body.add("name 2", "value 2+2");
body.add("name 3", null);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage);
assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"),
outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
outputMessage.getHeaders().getContentLength());
}
@Test
public void writeMultipart() throws Exception {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("name 1", "value 1");
parts.add("name 2", "value 2+1");
parts.add("name 2", "value 2+2");
Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
parts.add("logo", logo);
Source xml = new StreamSource(new StringReader("<root><child/></root>"));
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(MediaType.TEXT_XML);
HttpEntity<Source> entity = new HttpEntity<Source>(xml, entityHeaders);
parts.add("xml", entity);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(parts, MediaType.MULTIPART_FORM_DATA, outputMessage);
final MediaType contentType = outputMessage.getHeaders().getContentType();
assertNotNull("No boundary found", contentType.getParameter("boundary"));
// see if Commons FileUpload can read what we wrote
FileItemFactory fileItemFactory = new DiskFileItemFactory();
FileUpload fileUpload = new FileUpload(fileItemFactory);
List items = fileUpload.parseRequest(new MockHttpOutputMessageRequestContext(outputMessage));
assertEquals(5, items.size());
FileItem item = (FileItem) items.get(0);
assertTrue(item.isFormField());
assertEquals("name 1", item.getFieldName());
assertEquals("value 1", item.getString());
item = (FileItem) items.get(1);
assertTrue(item.isFormField());
assertEquals("name 2", item.getFieldName());
assertEquals("value 2+1", item.getString());
item = (FileItem) items.get(2);
assertTrue(item.isFormField());
assertEquals("name 2", item.getFieldName());
assertEquals("value 2+2", item.getString());
item = (FileItem) items.get(3);
assertFalse(item.isFormField());
assertEquals("logo", item.getFieldName());
assertEquals("logo.jpg", item.getName());
assertEquals("image/jpeg", item.getContentType());
assertEquals(logo.getFile().length(), item.getSize());
item = (FileItem) items.get(4);
assertEquals("xml", item.getFieldName());
assertEquals("text/xml", item.getContentType());
}
private static class MockHttpOutputMessageRequestContext implements RequestContext {
private final MockHttpOutputMessage outputMessage;
private MockHttpOutputMessageRequestContext(MockHttpOutputMessage outputMessage) {
this.outputMessage = outputMessage;
}
public String getCharacterEncoding() {
MediaType contentType = outputMessage.getHeaders().getContentType();
return contentType != null && contentType.getCharSet() != null ? contentType.getCharSet().name() : null;
}
public String getContentType() {
MediaType contentType = outputMessage.getHeaders().getContentType();
return contentType != null ? contentType.toString() : null;
}
public int getContentLength() {
return outputMessage.getBodyAsBytes().length;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(outputMessage.getBodyAsBytes());
}
}
}

View File

@@ -0,0 +1,106 @@
/*
* 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.converter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.namespace.QName;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
/**
* Test-case for AbstractHttpMessageConverter.
*
* @author Arjen Poutsma
*/
public class HttpMessageConverterTests {
private static final MediaType MEDIA_TYPE = new MediaType("foo", "bar");
@Test
public void canRead() {
AbstractHttpMessageConverter<MyType> converter = new MyHttpMessageConverter<MyType>(MEDIA_TYPE) {
@Override
protected boolean supports(Class<?> clazz) {
return MyType.class.equals(clazz);
}
};
assertTrue(converter.canRead(MyType.class, MEDIA_TYPE));
assertFalse(converter.canRead(MyType.class, new MediaType("foo", "*")));
assertFalse(converter.canRead(MyType.class, MediaType.ALL));
}
@Test
public void canWrite() {
AbstractHttpMessageConverter<MyType> converter = new MyHttpMessageConverter<MyType>(MEDIA_TYPE) {
@Override
protected boolean supports(Class<?> clazz) {
return MyType.class.equals(clazz);
}
};
assertTrue(converter.canWrite(MyType.class, MEDIA_TYPE));
assertTrue(converter.canWrite(MyType.class, new MediaType("foo", "*")));
assertTrue(converter.canWrite(MyType.class, MediaType.ALL));
}
private static class MyHttpMessageConverter<T> extends AbstractHttpMessageConverter<T> {
private MyHttpMessageConverter(MediaType supportedMediaType) {
super(supportedMediaType);
}
@Override
protected boolean supports(Class<?> clazz) {
fail("Not expected");
return false;
}
@Override
protected T readInternal(Class clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
fail("Not expected");
return null;
}
@Override
protected void writeInternal(T t, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
fail("Not expected");
}
}
private static class MyType {
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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.converter;
import java.io.IOException;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.util.FileCopyUtils;
/**
* @author Arjen Poutsma
*/
public class ResourceHttpMessageConverterTests {
private ResourceHttpMessageConverter converter;
@Before
public void setUp() {
converter = new ResourceHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue(converter.canRead(Resource.class, new MediaType("application", "octet-stream")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(Resource.class, new MediaType("application", "octet-stream")));
assertTrue(converter.canWrite(Resource.class, MediaType.ALL));
}
@Test
public void read() throws IOException {
byte[] body = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("logo.jpg"));
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
converter.read(Resource.class, inputMessage);
}
@Test
public void write() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
Resource body = new ClassPathResource("logo.jpg", getClass());
converter.write(body, null, outputMessage);
assertEquals("Invalid content-type", MediaType.IMAGE_JPEG,
outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", body.getFile().length(), outputMessage.getHeaders().getContentLength());
}
}

View File

@@ -0,0 +1,106 @@
/*
* 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.http.converter;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
/** @author Arjen Poutsma */
public class StringHttpMessageConverterTests {
private StringHttpMessageConverter converter;
@Before
public void setUp() {
converter = new StringHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue(converter.canRead(String.class, new MediaType("text", "plain")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(String.class, new MediaType("text", "plain")));
assertTrue(converter.canWrite(String.class, MediaType.ALL));
}
@Test
public void read() throws IOException {
String body = "Hello World";
Charset charset = Charset.forName("UTF-8");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(charset));
inputMessage.getHeaders().setContentType(new MediaType("text", "plain", charset));
String result = converter.read(String.class, inputMessage);
assertEquals("Invalid result", body, result);
}
@Test
public void writeDefaultCharset() throws IOException {
Charset iso88591 = Charset.forName("ISO-8859-1");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
String body = "H\u00e9llo W\u00f6rld";
converter.write(body, null, outputMessage);
assertEquals("Invalid result", body, outputMessage.getBodyAsString(iso88591));
assertEquals("Invalid content-type", new MediaType("text", "plain", iso88591),
outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", body.getBytes(iso88591).length,
outputMessage.getHeaders().getContentLength());
assertFalse("Invalid accept-charset", outputMessage.getHeaders().getAcceptCharset().isEmpty());
}
@Test
public void writeUTF8() throws IOException {
Charset utf8 = Charset.forName("UTF-8");
MediaType contentType = new MediaType("text", "plain", utf8);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
String body = "H\u00e9llo W\u00f6rld";
converter.write(body, contentType, outputMessage);
assertEquals("Invalid result", body, outputMessage.getBodyAsString(utf8));
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", body.getBytes(utf8).length,
outputMessage.getHeaders().getContentLength());
assertFalse("Invalid accept-charset", outputMessage.getHeaders().getAcceptCharset().isEmpty());
}
// SPR-8867
@Test
public void writeOverrideRequestedContentType() throws IOException {
Charset utf8 = Charset.forName("UTF-8");
MediaType requestedContentType = new MediaType("text", "html");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MediaType contentType = new MediaType("text", "plain", utf8);
outputMessage.getHeaders().setContentType(contentType);
String body = "H\u00e9llo W\u00f6rld";
converter.write(body, requestedContentType, outputMessage);
assertEquals("Invalid result", body, outputMessage.getBodyAsString(utf8));
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", body.getBytes(utf8).length,
outputMessage.getHeaders().getContentLength());
assertFalse("Invalid accept-charset", outputMessage.getHeaders().getAcceptCharset().isEmpty());
}
}

View File

@@ -0,0 +1,130 @@
/*
* 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.converter.feed;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import static org.custommonkey.xmlunit.XMLAssert.*;
import org.custommonkey.xmlunit.XMLUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
/** @author Arjen Poutsma */
public class AtomFeedHttpMessageConverterTests {
private AtomFeedHttpMessageConverter converter;
private Charset utf8;
@Before
public void setUp() {
utf8 = Charset.forName("UTF-8");
converter = new AtomFeedHttpMessageConverter();
XMLUnit.setIgnoreWhitespace(true);
}
@Test
public void canRead() {
assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml")));
assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml", utf8)));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml")));
assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml", Charset.forName("UTF-8"))));
}
@Test
public void read() throws IOException {
InputStream is = getClass().getResourceAsStream("atom.xml");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(is);
inputMessage.getHeaders().setContentType(new MediaType("application", "atom+xml", utf8));
Feed result = converter.read(Feed.class, inputMessage);
assertEquals("title", result.getTitle());
assertEquals("subtitle", result.getSubtitle().getValue());
List entries = result.getEntries();
assertEquals(2, entries.size());
Entry entry1 = (Entry) entries.get(0);
assertEquals("id1", entry1.getId());
assertEquals("title1", entry1.getTitle());
Entry entry2 = (Entry) entries.get(1);
assertEquals("id2", entry2.getId());
assertEquals("title2", entry2.getTitle());
}
@Test
public void write() throws IOException, SAXException {
Feed feed = new Feed("atom_1.0");
feed.setTitle("title");
Entry entry1 = new Entry();
entry1.setId("id1");
entry1.setTitle("title1");
Entry entry2 = new Entry();
entry2.setId("id2");
entry2.setTitle("title2");
List entries = new ArrayList(2);
entries.add(entry1);
entries.add(entry2);
feed.setEntries(entries);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(feed, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "atom+xml", utf8),
outputMessage.getHeaders().getContentType());
String expected = "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>title</title>" +
"<entry><id>id1</id><title>title1</title></entry>" +
"<entry><id>id2</id><title>title2</title></entry></feed>";
assertXMLEqual(expected, outputMessage.getBodyAsString(utf8));
}
@Test
public void writeOtherCharset() throws IOException, SAXException {
Feed feed = new Feed("atom_1.0");
feed.setTitle("title");
String encoding = "ISO-8859-1";
feed.setEncoding(encoding);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(feed, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "atom+xml", Charset.forName(encoding)),
outputMessage.getHeaders().getContentType());
}
}

View File

@@ -0,0 +1,138 @@
/*
* 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.converter.feed;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Item;
import static org.custommonkey.xmlunit.XMLAssert.*;
import org.custommonkey.xmlunit.XMLUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
/** @author Arjen Poutsma */
public class RssChannelHttpMessageConverterTests {
private RssChannelHttpMessageConverter converter;
private Charset utf8;
@Before
public void setUp() {
utf8 = Charset.forName("UTF-8");
converter = new RssChannelHttpMessageConverter();
XMLUnit.setIgnoreWhitespace(true);
}
@Test
public void canRead() {
assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml")));
assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml", utf8)));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml")));
assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml", Charset.forName("UTF-8"))));
}
@Test
public void read() throws IOException {
InputStream is = getClass().getResourceAsStream("rss.xml");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(is);
inputMessage.getHeaders().setContentType(new MediaType("application", "rss+xml", utf8));
Channel result = converter.read(Channel.class, inputMessage);
assertEquals("title", result.getTitle());
assertEquals("http://example.com", result.getLink());
assertEquals("description", result.getDescription());
List items = result.getItems();
assertEquals(2, items.size());
Item item1 = (Item) items.get(0);
assertEquals("title1", item1.getTitle());
Item item2 = (Item) items.get(1);
assertEquals("title2", item2.getTitle());
}
@Test
public void write() throws IOException, SAXException {
Channel channel = new Channel("rss_2.0");
channel.setTitle("title");
channel.setLink("http://example.com");
channel.setDescription("description");
Item item1 = new Item();
item1.setTitle("title1");
Item item2 = new Item();
item2.setTitle("title2");
List items = new ArrayList(2);
items.add(item1);
items.add(item2);
channel.setItems(items);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(channel, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "rss+xml", utf8),
outputMessage.getHeaders().getContentType());
String expected = "<rss version=\"2.0\">" +
"<channel><title>title</title><link>http://example.com</link><description>description</description>" +
"<item><title>title1</title></item>" +
"<item><title>title2</title></item>" +
"</channel></rss>";
assertXMLEqual(expected, outputMessage.getBodyAsString(utf8));
}
@Test
public void writeOtherCharset() throws IOException, SAXException {
Channel channel = new Channel("rss_2.0");
channel.setTitle("title");
channel.setLink("http://example.com");
channel.setDescription("description");
String encoding = "ISO-8859-1";
channel.setEncoding(encoding);
Item item1 = new Item();
item1.setTitle("title1");
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(channel, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "rss+xml", Charset.forName(encoding)),
outputMessage.getHeaders().getContentType());
}
}

View File

@@ -0,0 +1,240 @@
/*
* 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.converter.json;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
/**
* @author Arjen Poutsma
*/
public class MappingJacksonHttpMessageConverterTests {
private MappingJacksonHttpMessageConverter converter;
@Before
public void setUp() {
converter = new MappingJacksonHttpMessageConverter();
}
@Test
public void canRead() {
assertTrue(converter.canRead(MyBean.class, new MediaType("application", "json")));
assertTrue(converter.canRead(Map.class, new MediaType("application", "json")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(MyBean.class, new MediaType("application", "json")));
assertTrue(converter.canWrite(Map.class, new MediaType("application", "json")));
}
@Test
public void readTyped() throws IOException {
String body =
"{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
MyBean result = (MyBean) converter.read(MyBean.class, inputMessage);
assertEquals("Foo", result.getString());
assertEquals(42, result.getNumber());
assertEquals(42F, result.getFraction(), 0F);
assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray());
assertTrue(result.isBool());
assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes());
}
@Test
@SuppressWarnings("unchecked")
public void readGenerics() throws IOException {
converter = new MappingJacksonHttpMessageConverter() {
@Override
protected JavaType getJavaType(Class<?> clazz) {
if (List.class.isAssignableFrom(clazz)) {
return TypeFactory.collectionType(ArrayList.class, MyBean.class);
}
else {
return super.getJavaType(clazz);
}
}
};
String body =
"[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage);
assertEquals(1, results.size());
MyBean result = results.get(0);
assertEquals("Foo", result.getString());
assertEquals(42, result.getNumber());
assertEquals(42F, result.getFraction(), 0F);
assertArrayEquals(new String[]{"Foo", "Bar"}, result.getArray());
assertTrue(result.isBool());
assertArrayEquals(new byte[]{0x1, 0x2}, result.getBytes());
}
@Test
@SuppressWarnings("unchecked")
public void readUntyped() throws IOException {
String body =
"{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
HashMap<String, Object> result = (HashMap<String, Object>) converter.read(HashMap.class, inputMessage);
assertEquals("Foo", result.get("string"));
assertEquals(42, result.get("number"));
assertEquals(42D, (Double) result.get("fraction"), 0D);
List<String> array = new ArrayList<String>();
array.add("Foo");
array.add("Bar");
assertEquals(array, result.get("array"));
assertEquals(Boolean.TRUE, result.get("bool"));
assertEquals("AQI=", result.get("bytes"));
}
@Test
public void write() throws IOException {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
MyBean body = new MyBean();
body.setString("Foo");
body.setNumber(42);
body.setFraction(42F);
body.setArray(new String[]{"Foo", "Bar"});
body.setBool(true);
body.setBytes(new byte[]{0x1, 0x2});
converter.write(body, null, outputMessage);
Charset utf8 = Charset.forName("UTF-8");
String result = outputMessage.getBodyAsString(utf8);
assertTrue(result.contains("\"string\":\"Foo\""));
assertTrue(result.contains("\"number\":42"));
assertTrue(result.contains("fraction\":42.0"));
assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]"));
assertTrue(result.contains("\"bool\":true"));
assertTrue(result.contains("\"bytes\":\"AQI=\""));
assertEquals("Invalid content-type", new MediaType("application", "json", utf8),
outputMessage.getHeaders().getContentType());
}
@Test
public void writeUTF16() throws IOException {
Charset utf16 = Charset.forName("UTF-16BE");
MediaType contentType = new MediaType("application", "json", utf16);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
String body = "H\u00e9llo W\u00f6rld";
converter.write(body, contentType, outputMessage);
assertEquals("Invalid result", "\"" + body + "\"", outputMessage.getBodyAsString(utf16));
assertEquals("Invalid content-type", contentType, outputMessage.getHeaders().getContentType());
}
@Test(expected = HttpMessageNotReadableException.class)
public void readInvalidJson() throws IOException {
String body = "FooBar";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
converter.read(MyBean.class, inputMessage);
}
@Test(expected = HttpMessageNotReadableException.class)
public void readValidJsonWithUnknownProperty() throws IOException {
String body = "{\"string\":\"string\",\"unknownProperty\":\"value\"}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
converter.read(MyBean.class, inputMessage);
}
public static class MyBean {
private String string;
private int number;
private float fraction;
private String[] array;
private boolean bool;
private byte[] bytes;
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public boolean isBool() {
return bool;
}
public void setBool(boolean bool) {
this.bool = bool;
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public float getFraction() {
return fraction;
}
public void setFraction(float fraction) {
this.fraction = fraction;
}
public String[] getArray() {
return array;
}
public void setArray(String[] array) {
this.array = array;
}
}
}

View File

@@ -0,0 +1,141 @@
/*
* 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.http.converter.xml;
import java.nio.charset.Charset;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import static org.custommonkey.xmlunit.XMLAssert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.framework.DefaultAopProxyFactory;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
/** @author Arjen Poutsma */
public class Jaxb2RootElementHttpMessageConverterTest {
private Jaxb2RootElementHttpMessageConverter converter;
private RootElement rootElement;
private RootElement rootElementCglib;
@Before
public void setUp() {
converter = new Jaxb2RootElementHttpMessageConverter();
rootElement = new RootElement();
DefaultAopProxyFactory proxyFactory = new DefaultAopProxyFactory();
AdvisedSupport advisedSupport = new AdvisedSupport();
advisedSupport.setTarget(rootElement);
advisedSupport.setProxyTargetClass(true);
AopProxy proxy = proxyFactory.createAopProxy(advisedSupport);
rootElementCglib = (RootElement) proxy.getProxy();
}
@Test
public void canRead() throws Exception {
assertTrue("Converter does not support reading @XmlRootElement", converter.canRead(RootElement.class, null));
assertTrue("Converter does not support reading @XmlType", converter.canRead(Type.class, null));
}
@Test
public void canWrite() throws Exception {
assertTrue("Converter does not support writing @XmlRootElement", converter.canWrite(RootElement.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass", converter.canWrite(RootElementSubclass.class, null));
assertTrue("Converter does not support writing @XmlRootElement subclass", converter.canWrite(rootElementCglib.getClass(), null));
assertFalse("Converter supports writing @XmlType", converter.canWrite(Type.class, null));
}
@Test
@SuppressWarnings("unchecked")
public void readXmlRootElement() throws Exception {
byte[] body = "<rootElement><type s=\"Hello World\"/></rootElement>".getBytes("UTF-8");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
RootElement result = (RootElement) converter.read((Class) RootElement.class, inputMessage);
assertEquals("Invalid result", "Hello World", result.type.s);
}
@Test
@SuppressWarnings("unchecked")
public void readXmlRootElementSubclass() throws Exception {
byte[] body = "<rootElement><type s=\"Hello World\"/></rootElement>".getBytes("UTF-8");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
RootElementSubclass result = (RootElementSubclass) converter.read((Class) RootElementSubclass.class, inputMessage);
assertEquals("Invalid result", "Hello World", result.type.s);
}
@Test
@SuppressWarnings("unchecked")
public void readXmlType() throws Exception {
byte[] body = "<foo s=\"Hello World\"/>".getBytes("UTF-8");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
Type result = (Type) converter.read((Class) Type.class, inputMessage);
assertEquals("Invalid result", "Hello World", result.s);
}
@Test
public void writeXmlRootElement() throws Exception {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(rootElement, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
}
@Test
public void writeXmlRootElementSubclass() throws Exception {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(rootElementCglib, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
}
@XmlRootElement
public static class RootElement {
@XmlElement
public Type type = new Type();
}
@XmlType
public static class Type {
@XmlAttribute
public String s = "Hello World";
}
public static class RootElementSubclass extends RootElement {
}
}

View File

@@ -0,0 +1,76 @@
/*
* 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.http.converter.xml;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
/** @author Arjen Poutsma */
public class MarshallingHttpMessageConverterTests {
private MarshallingHttpMessageConverter converter;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
@Before
public void setUp() {
marshaller = createMock(Marshaller.class);
unmarshaller = createMock(Unmarshaller.class);
converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller);
}
@Test
public void read() throws Exception {
String body = "<root>Hello World</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
expect(unmarshaller.unmarshal(isA(StreamSource.class))).andReturn(body);
replay(marshaller, unmarshaller);
String result = (String) converter.read(Object.class, inputMessage);
assertEquals("Invalid result", body, result);
verify(marshaller, unmarshaller);
}
@Test
public void write() throws Exception {
String body = "<root>Hello World</root>";
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
marshaller.marshal(eq(body), isA(StreamResult.class));
replay(marshaller, unmarshaller);
converter.write(body, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
verify(marshaller, unmarshaller);
}
}

View File

@@ -0,0 +1,150 @@
/*
* 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.http.converter.xml;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.Charset;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
import org.springframework.util.FileCopyUtils;
import static org.custommonkey.xmlunit.XMLAssert.*;
/** @author Arjen Poutsma */
@SuppressWarnings("unchecked")
public class SourceHttpMessageConverterTests {
private SourceHttpMessageConverter<Source> converter;
@Before
public void setUp() {
converter = new SourceHttpMessageConverter<Source>();
}
@Test
public void canRead() {
assertTrue(converter.canRead(Source.class, new MediaType("application", "xml")));
assertTrue(converter.canRead(Source.class, new MediaType("application", "soap+xml")));
}
@Test
public void canWrite() {
assertTrue(converter.canWrite(Source.class, new MediaType("application", "xml")));
assertTrue(converter.canWrite(Source.class, new MediaType("application", "soap+xml")));
assertTrue(converter.canWrite(Source.class, MediaType.ALL));
}
@Test
public void readDOMSource() throws Exception {
String body = "<root>Hello World</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
DOMSource result = (DOMSource) converter.read(DOMSource.class, inputMessage);
Document document = (Document) result.getNode();
assertEquals("Invalid result", "root", document.getDocumentElement().getLocalName());
}
@Test
public void readSAXSource() throws Exception {
String body = "<root>Hello World</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage);
InputSource inputSource = result.getInputSource();
String s = FileCopyUtils.copyToString(new InputStreamReader(inputSource.getByteStream()));
assertXMLEqual("Invalid result", body, s);
}
@Test
public void readStreamSource() throws Exception {
String body = "<root>Hello World</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
StreamSource result = (StreamSource) converter.read(StreamSource.class, inputMessage);
String s = FileCopyUtils.copyToString(new InputStreamReader(result.getInputStream()));
assertXMLEqual("Invalid result", body, s);
}
@Test
public void readSource() throws Exception {
String body = "<root>Hello World</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
converter.read(Source.class, inputMessage);
}
@Test
public void writeDOMSource() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
Element rootElement = document.createElement("root");
document.appendChild(rootElement);
rootElement.setTextContent("Hello World");
DOMSource domSource = new DOMSource(document);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(domSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
outputMessage.getHeaders().getContentLength());
}
@Test
public void writeSAXSource() throws Exception {
String xml = "<root>Hello World</root>";
SAXSource saxSource = new SAXSource(new InputSource(new StringReader(xml)));
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(saxSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
}
@Test
public void writeStreamSource() throws Exception {
String xml = "<root>Hello World</root>";
StreamSource streamSource = new StreamSource(new StringReader(xml));
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(streamSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8")));
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.http.server;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.FileCopyUtils;
import static org.junit.Assert.*;
/**
* @author Arjen Poutsma
*/
public class ServletServerHttpRequestTests {
private ServletServerHttpRequest request;
private MockHttpServletRequest mockRequest;
@Before
public void create() throws Exception {
mockRequest = new MockHttpServletRequest();
request = new ServletServerHttpRequest(mockRequest);
}
@Test
public void getMethod() throws Exception {
mockRequest.setMethod("POST");
assertEquals("Invalid method", HttpMethod.POST, request.getMethod());
}
@Test
public void getURI() throws Exception {
URI uri = new URI("http://example.com/path?query");
mockRequest.setServerName(uri.getHost());
mockRequest.setServerPort(uri.getPort());
mockRequest.setRequestURI(uri.getPath());
mockRequest.setQueryString(uri.getQuery());
assertEquals("Invalid uri", uri, request.getURI());
}
@Test
public void getHeaders() throws Exception {
String headerName = "MyHeader";
String headerValue1 = "value1";
mockRequest.addHeader(headerName, headerValue1);
String headerValue2 = "value2";
mockRequest.addHeader(headerName, headerValue2);
HttpHeaders headers = request.getHeaders();
assertNotNull("No HttpHeaders returned", headers);
assertTrue("Invalid headers returned", headers.containsKey(headerName));
List<String> headerValues = headers.get(headerName);
assertEquals("Invalid header values returned", 2, headerValues.size());
assertTrue("Invalid header values returned", headerValues.contains(headerValue1));
assertTrue("Invalid header values returned", headerValues.contains(headerValue2));
}
@Test
public void getBody() throws Exception {
byte[] content = "Hello World".getBytes("UTF-8");
mockRequest.setContent(content);
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
assertArrayEquals("Invalid content returned", content, result);
}
@Test
public void getFormBody() throws Exception {
// Charset (SPR-8676)
mockRequest.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
mockRequest.setMethod("POST");
mockRequest.addParameter("name 1", "value 1");
mockRequest.addParameter("name 2", new String[] {"value 2+1", "value 2+2"});
mockRequest.addParameter("name 3", (String) null);
byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
byte[] content = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes("UTF-8");
assertArrayEquals("Invalid content returned", content, result);
}
}

View File

@@ -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.http.server;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.FileCopyUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
/**
* @author Arjen Poutsma
*/
public class ServletServerHttpResponseTests {
private ServletServerHttpResponse response;
private MockHttpServletResponse mockResponse;
@Before
public void create() throws Exception {
mockResponse = new MockHttpServletResponse();
response = new ServletServerHttpResponse(mockResponse);
}
@Test
public void setStatusCode() throws Exception {
response.setStatusCode(HttpStatus.NOT_FOUND);
assertEquals("Invalid status code", 404, mockResponse.getStatus());
}
@Test
public void getHeaders() throws Exception {
HttpHeaders headers = response.getHeaders();
String headerName = "MyHeader";
String headerValue1 = "value1";
headers.add(headerName, headerValue1);
String headerValue2 = "value2";
headers.add(headerName, headerValue2);
response.close();
assertTrue("Header not set", mockResponse.getHeaderNames().contains(headerName));
List headerValues = mockResponse.getHeaders(headerName);
assertTrue("Header not set", headerValues.contains(headerValue1));
assertTrue("Header not set", headerValues.contains(headerValue2));
}
@Test
public void getBody() throws Exception {
byte[] content = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(content, response.getBody());
assertArrayEquals("Invalid content written", content, mockResponse.getContentAsByteArray());
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,71 @@
/*
* 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;
}
public void write(int b) throws IOException {
this.targetStream.write(b);
}
public void flush() throws IOException {
super.flush();
this.targetStream.flush();
}
public void close() throws IOException {
super.close();
this.targetStream.close();
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,92 @@
/*
* 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.jsp.JspException;
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.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
/**
* Mock implementation of the JSP 2.0 {@link javax.servlet.jsp.el.ExpressionEvaluator}
* interface, delegating to the Jakarta JSTL ExpressionEvaluatorManager.
*
* <p>Used for testing the web framework; only necessary for testing
* applications when testing custom JSP tags.
*
* <p>Note that the Jakarta JSTL implementation (jstl.jar, standard.jar)
* has to be available on the class path to use this expression evaluator.
*
* @author Juergen Hoeller
* @since 1.1.5
* @see org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager
*/
public class MockExpressionEvaluator extends ExpressionEvaluator {
private final PageContext pageContext;
/**
* Create a new MockExpressionEvaluator for the given PageContext.
* @param pageContext the JSP PageContext to run in
*/
public MockExpressionEvaluator(PageContext pageContext) {
this.pageContext = pageContext;
}
public Expression parseExpression(
final String expression, final Class expectedType, final FunctionMapper functionMapper)
throws ELException {
return new Expression() {
public Object evaluate(VariableResolver variableResolver) throws ELException {
return doEvaluate(expression, expectedType, functionMapper);
}
};
}
public Object evaluate(
String expression, Class expectedType, VariableResolver variableResolver, FunctionMapper functionMapper)
throws ELException {
if (variableResolver != null) {
throw new IllegalArgumentException("Custom VariableResolver not supported");
}
return doEvaluate(expression, expectedType, functionMapper);
}
protected Object doEvaluate(
String expression, Class expectedType, FunctionMapper functionMapper)
throws ELException {
if (functionMapper != null) {
throw new IllegalArgumentException("Custom FunctionMapper not supported");
}
try {
return ExpressionEvaluatorManager.evaluate("JSP EL expression", expression, expectedType, this.pageContext);
}
catch (JspException ex) {
throw new ELException("Parsing of JSP EL expression \"" + expression + "\" failed", ex);
}
}
}

View File

@@ -0,0 +1,70 @@
/*
* 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 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 useful 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;
}
}

View File

@@ -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());
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,569 @@
/*
* 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.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 3.0 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);
}
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}
}

View File

@@ -0,0 +1,351 @@
/*
* 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.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.ExpressionEvaluator;
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 MockExpressionEvaluator(this);
}
public ELContext getELContext() {
return null;
}
public VariableResolver getVariableResolver() {
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);
}
}

View File

@@ -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();
}
}

View File

@@ -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");
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,507 @@
/*
* 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).
*
* <p>Supports Servlet 3.0 API level, but throws {@link UnsupportedOperationException}
* for most 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 majorVersion = 2;
private int minorVersion = 5;
private int effectiveMajorVersion = 2;
private int effectiveMinorVersion = 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 void setMajorVersion(int majorVersion) {
this.majorVersion = majorVersion;
}
public int getMajorVersion() {
return this.majorVersion;
}
public void setMinorVersion(int minorVersion) {
this.minorVersion = minorVersion;
}
public int getMinorVersion() {
return this.minorVersion;
}
public void setEffectiveMajorVersion(int effectiveMajorVersion) {
this.effectiveMajorVersion = effectiveMajorVersion;
}
public int getEffectiveMajorVersion() {
return this.effectiveMajorVersion;
}
public void setEffectiveMinorVersion(int effectiveMinorVersion) {
this.effectiveMinorVersion = effectiveMinorVersion;
}
public int getEffectiveMinorVersion() {
return this.effectiveMinorVersion;
}
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 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();
}
}

View File

@@ -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);
}
}
}

View File

@@ -0,0 +1,255 @@
/*
* 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.remoting.caucho;
import com.caucho.burlap.client.BurlapProxyFactory;
import com.caucho.hessian.client.HessianProxyFactory;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.remoting.RemoteAccessException;
/**
* @author Juergen Hoeller
* @since 16.05.2003
*/
public class CauchoRemotingTests extends TestCase {
public void testHessianProxyFactoryBeanWithAccessError() throws Exception {
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
try {
factory.setServiceInterface(TestBean.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testHessianProxyFactoryBeanWithAuthenticationAndAccessError() throws Exception {
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
try {
factory.setServiceInterface(TestBean.class);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testHessianProxyFactoryBeanWithCustomProxyFactory() throws Exception {
TestHessianProxyFactory proxyFactory = new TestHessianProxyFactory();
HessianProxyFactoryBean factory = new HessianProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setProxyFactory(proxyFactory);
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
assertEquals(proxyFactory.user, "test");
assertEquals(proxyFactory.password, "bean");
assertTrue(proxyFactory.overloadEnabled);
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithAccessError() throws Exception {
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithAuthenticationAndAccessError() throws Exception {
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
public void testBurlapProxyFactoryBeanWithCustomProxyFactory() throws Exception {
TestBurlapProxyFactory proxyFactory = new TestBurlapProxyFactory();
BurlapProxyFactoryBean factory = new BurlapProxyFactoryBean();
factory.setServiceInterface(ITestBean.class);
factory.setServiceUrl("http://localhosta/testbean");
factory.setProxyFactory(proxyFactory);
factory.setUsername("test");
factory.setPassword("bean");
factory.setOverloadEnabled(true);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getObject() instanceof ITestBean);
ITestBean bean = (ITestBean) factory.getObject();
assertEquals(proxyFactory.user, "test");
assertEquals(proxyFactory.password, "bean");
assertTrue(proxyFactory.overloadEnabled);
try {
bean.setName("test");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
}
/** Using the JDK 1.6 HttpServer breaks when running multiple test methods
public void testSimpleHessianServiceExporter() throws IOException {
if (JdkVersion.getMajorJavaVersion() < JdkVersion.JAVA_16) {
return;
}
TestBean tb = new TestBean("tb");
SimpleHessianServiceExporter exporter = new SimpleHessianServiceExporter();
exporter.setService(tb);
exporter.setServiceInterface(ITestBean.class);
exporter.setDebug(true);
exporter.prepare();
HttpServer server = HttpServer.create(new InetSocketAddress(8889), -1);
server.createContext("/hessian", exporter);
server.start();
try {
HessianClientInterceptor client = new HessianClientInterceptor();
client.setServiceUrl("http://localhost:8889/hessian");
client.setServiceInterface(ITestBean.class);
//client.setHessian2(true);
client.prepare();
ITestBean proxy = ProxyFactory.getProxy(ITestBean.class, client);
assertEquals("tb", proxy.getName());
proxy.setName("test");
assertEquals("test", proxy.getName());
}
finally {
server.stop(Integer.MAX_VALUE);
}
}
*/
private static class TestHessianProxyFactory extends HessianProxyFactory {
private String user;
private String password;
private boolean overloadEnabled;
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setOverloadEnabled(boolean overloadEnabled) {
this.overloadEnabled = overloadEnabled;
}
}
private static class TestBurlapProxyFactory extends BurlapProxyFactory {
private String user;
private String password;
private boolean overloadEnabled;
public void setUser(String user) {
this.user = user;
}
public void setPassword(String password) {
this.password = password;
}
public void setOverloadEnabled(boolean overloadEnabled) {
this.overloadEnabled = overloadEnabled;
}
}
}

View File

@@ -0,0 +1,480 @@
/*
* 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.remoting.httpinvoker;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.support.DefaultRemoteInvocationExecutor;
import org.springframework.remoting.support.RemoteInvocation;
import org.springframework.remoting.support.RemoteInvocationFactory;
import org.springframework.remoting.support.RemoteInvocationResult;
/**
* @author Juergen Hoeller
* @since 09.08.2004
*/
public class HttpInvokerTests extends TestCase {
public void testHttpInvokerProxyFactoryBeanAndServiceExporter() throws Throwable {
doTestHttpInvokerProxyFactoryBeanAndServiceExporter(false);
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithExplicitClassLoader() throws Throwable {
doTestHttpInvokerProxyFactoryBeanAndServiceExporter(true);
}
private void doTestHttpInvokerProxyFactoryBeanAndServiceExporter(boolean explicitClassLoader) throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
if (explicitClassLoader) {
((BeanClassLoaderAware) pfb.getHttpInvokerRequestExecutor()).setBeanClassLoader(getClass().getClassLoader());
}
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
proxy.setStringArray(new String[] {"str1", "str2"});
assertTrue(Arrays.equals(new String[] {"str1", "str2"}, proxy.getStringArray()));
proxy.setSomeIntegerArray(new Integer[] {1, 2, 3});
assertTrue(Arrays.equals(new Integer[] {1, 2, 3}, proxy.getSomeIntegerArray()));
proxy.setNestedIntegerArray(new Integer[][] {{1, 2, 3}, {4, 5, 6}});
Integer[][] integerArray = proxy.getNestedIntegerArray();
assertTrue(Arrays.equals(new Integer[] {1, 2, 3}, integerArray[0]));
assertTrue(Arrays.equals(new Integer[] {4, 5, 6}, integerArray[1]));
proxy.setSomeIntArray(new int[] {1, 2, 3});
assertTrue(Arrays.equals(new int[] {1, 2, 3}, proxy.getSomeIntArray()));
proxy.setNestedIntArray(new int[][] {{1, 2, 3}, {4, 5, 6}});
int[][] intArray = proxy.getNestedIntArray();
assertTrue(Arrays.equals(new int[] {1, 2, 3}, intArray[0]));
assertTrue(Arrays.equals(new int[] {4, 5, 6}, intArray[1]));
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithIOException() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new HttpInvokerRequestExecutor() {
public RemoteInvocationResult executeRequest(
HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws IOException {
throw new IOException("argh");
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithGzipCompression() throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() {
protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException {
if ("gzip".equals(request.getHeader("Compression"))) {
return new GZIPInputStream(is);
}
else {
return is;
}
}
protected OutputStream decorateOutputStream(
HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
if ("gzip".equals(request.getHeader("Compression"))) {
return new GZIPOutputStream(os);
}
else {
return os;
}
}
};
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos)
throws IOException, ClassNotFoundException {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Compression", "gzip");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
try {
exporter.handleRequest(request, response);
}
catch (ServletException ex) {
throw new IOException(ex.toString());
}
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
protected OutputStream decorateOutputStream(OutputStream os) throws IOException {
return new GZIPOutputStream(os);
}
protected InputStream decorateInputStream(InputStream is) throws IOException {
return new GZIPInputStream(is);
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithWrappedInvocations() throws Throwable {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() {
protected RemoteInvocation doReadRemoteInvocation(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
Object obj = ois.readObject();
if (!(obj instanceof TestRemoteInvocationWrapper)) {
throw new IOException("Deserialized object needs to be assignable to type [" +
TestRemoteInvocationWrapper.class.getName() + "]: " + obj);
}
return ((TestRemoteInvocationWrapper) obj).remoteInvocation;
}
protected void doWriteRemoteInvocationResult(RemoteInvocationResult result, ObjectOutputStream oos)
throws IOException {
oos.writeObject(new TestRemoteInvocationResultWrapper(result));
}
};
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
protected void doWriteRemoteInvocation(RemoteInvocation invocation, ObjectOutputStream oos) throws IOException {
oos.writeObject(new TestRemoteInvocationWrapper(invocation));
}
protected RemoteInvocationResult doReadRemoteInvocationResult(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
Object obj = ois.readObject();
if (!(obj instanceof TestRemoteInvocationResultWrapper)) {
throw new IOException("Deserialized object needs to be assignable to type ["
+ TestRemoteInvocationResultWrapper.class.getName() + "]: " + obj);
}
return ((TestRemoteInvocationResultWrapper) obj).remoteInvocationResult;
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
proxy.setAge(50);
assertEquals(50, proxy.getAge());
try {
proxy.exceptional(new IllegalStateException());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
proxy.exceptional(new IllegalAccessException());
fail("Should have thrown IllegalAccessException");
}
catch (IllegalAccessException ex) {
// expected
}
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithInvocationAttributes() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setRemoteInvocationExecutor(new DefaultRemoteInvocationExecutor() {
public Object invoke(RemoteInvocation invocation, Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
assertNotNull(invocation.getAttributes());
assertEquals(1, invocation.getAttributes().size());
assertEquals("myValue", invocation.getAttributes().get("myKey"));
assertEquals("myValue", invocation.getAttribute("myKey"));
return super.invoke(invocation, targetObject);
}
});
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setRemoteInvocationFactory(new RemoteInvocationFactory() {
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
RemoteInvocation invocation = new RemoteInvocation(methodInvocation);
invocation.addAttribute("myKey", "myValue");
try {
invocation.addAttribute("myKey", "myValue");
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected: already defined
}
assertNotNull(invocation.getAttributes());
assertEquals(1, invocation.getAttributes().size());
assertEquals("myValue", invocation.getAttributes().get("myKey"));
assertEquals("myValue", invocation.getAttribute("myKey"));
return invocation;
}
});
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
}
public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithCustomInvocationObject() throws Exception {
TestBean target = new TestBean("myname", 99);
final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
exporter.setServiceInterface(ITestBean.class);
exporter.setService(target);
exporter.setRemoteInvocationExecutor(new DefaultRemoteInvocationExecutor() {
public Object invoke(RemoteInvocation invocation, Object targetObject)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
assertTrue(invocation instanceof TestRemoteInvocation);
assertNull(invocation.getAttributes());
assertNull(invocation.getAttribute("myKey"));
return super.invoke(invocation, targetObject);
}
});
exporter.afterPropertiesSet();
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl("http://myurl");
pfb.setRemoteInvocationFactory(new RemoteInvocationFactory() {
public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) {
RemoteInvocation invocation = new TestRemoteInvocation(methodInvocation);
assertNull(invocation.getAttributes());
assertNull(invocation.getAttribute("myKey"));
return invocation;
}
});
pfb.setHttpInvokerRequestExecutor(new AbstractHttpInvokerRequestExecutor() {
protected RemoteInvocationResult doExecuteRequest(
HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws Exception {
assertEquals("http://myurl", config.getServiceUrl());
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContent(baos.toByteArray());
exporter.handleRequest(request, response);
return readRemoteInvocationResult(
new ByteArrayInputStream(response.getContentAsByteArray()), config.getCodebaseUrl());
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
assertEquals("myname", proxy.getName());
assertEquals(99, proxy.getAge());
}
public void testHttpInvokerWithSpecialLocalMethods() throws Exception {
String serviceUrl = "http://myurl";
HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean();
pfb.setServiceInterface(ITestBean.class);
pfb.setServiceUrl(serviceUrl);
pfb.setHttpInvokerRequestExecutor(new HttpInvokerRequestExecutor() {
public RemoteInvocationResult executeRequest(
HttpInvokerClientConfiguration config, RemoteInvocation invocation) throws IOException {
throw new IOException("argh");
}
});
pfb.afterPropertiesSet();
ITestBean proxy = (ITestBean) pfb.getObject();
// shouldn't go through to remote service
assertTrue(proxy.toString().indexOf("HTTP invoker") != -1);
assertTrue(proxy.toString().indexOf(serviceUrl) != -1);
assertEquals(proxy.hashCode(), proxy.hashCode());
assertTrue(proxy.equals(proxy));
// should go through
try {
proxy.setAge(50);
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
}
}
private static class TestRemoteInvocation extends RemoteInvocation {
public TestRemoteInvocation(MethodInvocation methodInvocation) {
super(methodInvocation);
}
}
private static class TestRemoteInvocationWrapper implements Serializable {
private final RemoteInvocation remoteInvocation;
public TestRemoteInvocationWrapper(RemoteInvocation remoteInvocation) {
this.remoteInvocation = remoteInvocation;
}
}
private static class TestRemoteInvocationResultWrapper implements Serializable {
private final RemoteInvocationResult remoteInvocationResult;
public TestRemoteInvocationResultWrapper(RemoteInvocationResult remoteInvocationResult) {
this.remoteInvocationResult = remoteInvocationResult;
}
}
}

View File

@@ -0,0 +1,705 @@
/*
* 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.remoting.jaxrpc;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.Stub;
import junit.framework.TestCase;
import org.easymock.ArgumentsMatcher;
import org.easymock.MockControl;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.remoting.RemoteLookupFailureException;
import org.springframework.util.ObjectUtils;
/**
* @author Juergen Hoeller
* @since 18.12.2003
*/
public class JaxRpcSupportTests extends TestCase {
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndNamespace() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.afterPropertiesSet();
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndWsdl() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setServiceName("myService2");
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service2, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithServiceNameAndWsdlAndProperties() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setServiceName("myService2");
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
Properties props = new Properties();
props.setProperty("myKey", "myValue");
factory.setJaxRpcServiceProperties(props);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithJaxRpcServiceInterface() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setJaxRpcServiceInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service2, factory.getObject());
}
public void testLocalJaxRpcServiceFactoryBeanWithJaxRpcServiceInterfaceAndWsdl() throws Exception {
LocalJaxRpcServiceFactoryBean factory = new LocalJaxRpcServiceFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setWsdlDocumentUrl(new URL("http://myUrl1"));
factory.setJaxRpcServiceInterface(IRemoteBean.class);
Properties props = new Properties();
props.setProperty("myKey", "myValue");
factory.setJaxRpcServiceProperties(props);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertEquals(MockServiceFactory.service1, factory.getObject());
}
public void testJaxRpcPortProxyFactoryBean() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("user", stub._getProperty(Stub.USERNAME_PROPERTY));
assertEquals("pw", stub._getProperty(Stub.PASSWORD_PROPERTY));
assertEquals("ea", stub._getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY));
assertTrue(((Boolean) stub._getProperty(Stub.SESSION_MAINTAIN_PROPERTY)).booleanValue());
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithCustomProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
Properties customProps = new Properties();
customProps.setProperty("myProp", "myValue");
factory.setCustomProperties(customProps);
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("user", stub._getProperty(Stub.USERNAME_PROPERTY));
assertEquals("pw", stub._getProperty(Stub.PASSWORD_PROPERTY));
assertEquals("myValue", stub._getProperty("myProp"));
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithCustomPropertyMap() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
Map customProps = new HashMap();
customProps.put("myProp", new Integer(1));
factory.setCustomPropertyMap(customProps);
factory.addCustomProperty("myOtherProp", "myOtherValue");
factory.setPortInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue("Correct singleton value", factory.isSingleton());
assertTrue(factory.getPortStub() instanceof Stub);
Stub stub = (Stub) factory.getPortStub();
assertEquals("ea", stub._getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY));
assertTrue(((Boolean) stub._getProperty(Stub.SESSION_MAINTAIN_PROPERTY)).booleanValue());
assertEquals(new Integer(1), stub._getProperty("myProp"));
assertEquals("myOtherValue", stub._getProperty("myOtherProp"));
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCalls() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertNull(factory.getPortStub());
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndProperties() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallWithPropertiesMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setUsername("user");
factory.setPassword("pw");
factory.setEndpointAddress("ea");
factory.setMaintainSession(true);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertNull(factory.getPortStub());
assertTrue(factory.getObject() instanceof IBusinessBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
try {
factory.afterPropertiesSet();
fail("Should have thrown RemoteLookupFailureException");
}
catch (RemoteLookupFailureException ex) {
// expected
}
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndLazyLookupAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(CallMockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.setLookupServiceOnStartup(false);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteLookupFailureException ex) {
// expected
assertTrue(ex.getCause() instanceof ServiceException);
}
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteException() throws Exception {
ExceptionCallMockServiceFactory serviceFactory = new ExceptionCallMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(1, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
ExceptionCallMockServiceFactory.call2Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteExceptionAndRefresh() throws Exception {
ExceptionCallMockServiceFactory serviceFactory = new ExceptionCallMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
factory.setRefreshServiceAfterConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteException");
}
catch (RemoteException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(2, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
CallMockServiceFactory.call1Control.verify();
ExceptionCallMockServiceFactory.call2Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterface() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortInterface(IRemoteBean.class);
factory.setPortName("myPort");
factory.setServiceInterface(IRemoteBean.class);
try {
factory.afterPropertiesSet();
fail("Should have thrown RemoteLookupFailureException");
}
catch (RemoteLookupFailureException ex) {
// expected
}
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndLazyLookupAndServiceException() throws Exception {
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactoryClass(MockServiceFactory.class);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myServiceX");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IRemoteBean.class);
factory.setLookupServiceOnStartup(false);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IRemoteBean);
IRemoteBean proxy = (IRemoteBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown Service");
}
catch (RemoteLookupFailureException ex) {
// expected
assertTrue(ex.getCause() instanceof ServiceException);
}
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteException() throws Exception {
MockServiceFactory serviceFactory = new MockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(1, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
}
public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteExceptionAndRefresh() throws Exception {
ExceptionMockServiceFactory serviceFactory = new ExceptionMockServiceFactory();
JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean();
factory.setServiceFactory(serviceFactory);
factory.setNamespaceUri("myNamespace");
factory.setServiceName("myService1");
factory.setPortName("myPort");
factory.setPortInterface(IRemoteBean.class);
factory.setServiceInterface(IBusinessBean.class);
factory.setRefreshServiceAfterConnectFailure(true);
factory.afterPropertiesSet();
assertTrue(factory.getObject() instanceof IBusinessBean);
assertFalse(factory.getObject() instanceof IRemoteBean);
IBusinessBean proxy = (IBusinessBean) factory.getObject();
try {
proxy.setName("exception");
fail("Should have thrown RemoteAccessException");
}
catch (RemoteAccessException ex) {
// expected
}
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
proxy.setName("myName");
assertEquals("myName", RemoteBean.name);
assertEquals(2, serviceFactory.serviceCount);
MockServiceFactory.service1Control.verify();
}
public static class MockServiceFactory extends ServiceFactory {
protected static MockControl service1Control;
protected static Service service1;
protected static MockControl service2Control;
protected static Service service2;
protected int serviceCount = 0;
public MockServiceFactory() throws Exception {
service1Control = MockControl.createControl(Service.class);
service1 = (Service) service1Control.getMock();
service2Control = MockControl.createControl(Service.class);
service2 = (Service) service2Control.getMock();
initMocks();
service1Control.replay();
}
protected void initMocks() throws Exception {
service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class);
service1Control.setReturnValue(new RemoteBean());
}
public Service createService(QName qName) throws ServiceException {
if (!"myNamespace".equals(qName.getNamespaceURI()) || !"myService1".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
serviceCount++;
return service1;
}
public Service createService(URL url, QName qName) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !"".equals(qName.getNamespaceURI()) ||
!"myService2".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
serviceCount++;
return service2;
}
public Service loadService(URL url, QName qName, Properties props) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !"".equals(qName.getNamespaceURI()) ||
!"myService2".equals(qName.getLocalPart())) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
if (props == null || !"myValue".equals(props.getProperty("myKey"))) {
throw new ServiceException("invalid properties");
}
serviceCount++;
return service1;
}
public Service loadService(Class ifc) throws ServiceException {
if (!IRemoteBean.class.equals(ifc)) {
throw new ServiceException("not supported");
}
serviceCount++;
return service2;
}
public Service loadService(URL url, Class ifc, Properties props) throws ServiceException {
try {
if (!(new URL("http://myUrl1")).equals(url) || !IRemoteBean.class.equals(ifc)) {
throw new ServiceException("not supported");
}
}
catch (MalformedURLException ex) {
}
if (props == null || !"myValue".equals(props.getProperty("myKey"))) {
throw new ServiceException("invalid properties");
}
serviceCount++;
return service1;
}
}
public static class ExceptionMockServiceFactory extends MockServiceFactory {
public ExceptionMockServiceFactory() throws Exception {
super();
}
protected void initMocks() throws Exception {
super.initMocks();
service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class);
service1Control.setReturnValue(new RemoteBean());
}
}
public static class CallMockServiceFactory extends MockServiceFactory {
protected static MockControl call1Control;
protected static Call call1;
public CallMockServiceFactory() throws Exception {
super();
}
protected void initMocks() throws Exception {
initStandardCall(1);
}
protected void initStandardCall(int count) throws Exception {
call1Control = MockControl.createControl(Call.class);
call1 = (Call) call1Control.getMock();
service1.createCall(new QName("myNamespace", "myPort"), "setName");
service1Control.setReturnValue(call1, count);
call1.invoke(new Object[] {"myName"});
call1Control.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] objects, Object[] objects1) {
return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]);
}
public String toString(Object[] objects) {
return ObjectUtils.nullSafeToString(objects[0]);
}
});
call1Control.setReturnValue(null, count);
extendStandardCall();
call1Control.replay();
}
protected void extendStandardCall() {
}
}
public static class ExceptionCallMockServiceFactory extends CallMockServiceFactory {
protected static MockControl call2Control;
protected static Call call2;
public ExceptionCallMockServiceFactory() throws Exception {
}
protected void initMocks() throws Exception {
initExceptionCall();
initStandardCall(2);
}
protected void initExceptionCall() throws Exception {
call2Control = MockControl.createControl(Call.class);
call2 = (Call) call2Control.getMock();
service1.createCall(new QName("myNamespace", "myPort"), "setName");
service1Control.setReturnValue(call2);
call2.invoke(new Object[] {"exception"});
call2Control.setMatcher(new ArgumentsMatcher() {
public boolean matches(Object[] objects, Object[] objects1) {
return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]);
}
public String toString(Object[] objects) {
return ObjectUtils.nullSafeToString(objects[0]);
}
});
call2Control.setThrowable(new RemoteException());
call2Control.replay();
}
}
public static class CallWithPropertiesMockServiceFactory extends CallMockServiceFactory {
public CallWithPropertiesMockServiceFactory() throws Exception {
}
protected void extendStandardCall() {
call1.setProperty(Call.USERNAME_PROPERTY, "user");
call1Control.setVoidCallable();
call1.setProperty(Call.PASSWORD_PROPERTY, "pw");
call1Control.setVoidCallable();
call1.setTargetEndpointAddress("ea");
call1Control.setVoidCallable();
call1.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
call1Control.setVoidCallable();
}
}
public static interface IBusinessBean {
public void setName(String name);
}
public static interface IRemoteBean extends Remote {
public void setName(String name) throws RemoteException;
}
public static class RemoteBean implements IRemoteBean, Stub {
private static String name;
private static Map properties;
public RemoteBean() {
properties = new HashMap();
}
public void setName(String nam) throws RemoteException {
if ("exception".equals(nam)) {
throw new RemoteException();
}
name = nam;
}
public void _setProperty(String key, Object o) {
properties.put(key, o);
}
public Object _getProperty(String key) {
return properties.get(key);
}
public Iterator _getPropertyNames() {
return properties.keySet().iterator();
}
}
}

View File

@@ -0,0 +1,169 @@
/*
* 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.remoting.jaxws;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceRef;
import javax.xml.ws.soap.AddressingFeature;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
/**
* @author Juergen Hoeller
* @since 2.5
*/
@org.junit.Ignore // TODO until https://gist.github.com/1150858 is fixed
public class JaxWsSupportTests {
@Test
public void testJaxWsPortAccess() throws Exception {
doTestJaxWsPortAccess((Object[]) null);
}
@Test
public void testJaxWsPortAccessWithFeatureObject() throws Exception {
doTestJaxWsPortAccess(new AddressingFeature());
}
@Test
public void testJaxWsPortAccessWithFeatureClass() throws Exception {
doTestJaxWsPortAccess(AddressingFeature.class);
}
@Test
public void testJaxWsPortAccessWithFeatureString() throws Exception {
doTestJaxWsPortAccess("javax.xml.ws.soap.AddressingFeature");
}
private void doTestJaxWsPortAccess(Object... features) throws Exception {
GenericApplicationContext ac = new GenericApplicationContext();
GenericBeanDefinition serviceDef = new GenericBeanDefinition();
serviceDef.setBeanClass(OrderServiceImpl.class);
ac.registerBeanDefinition("service", serviceDef);
GenericBeanDefinition exporterDef = new GenericBeanDefinition();
exporterDef.setBeanClass(SimpleJaxWsServiceExporter.class);
exporterDef.getPropertyValues().add("baseAddress", "http://localhost:9999/");
ac.registerBeanDefinition("exporter", exporterDef);
GenericBeanDefinition clientDef = new GenericBeanDefinition();
clientDef.setBeanClass(JaxWsPortProxyFactoryBean.class);
clientDef.getPropertyValues().add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
clientDef.getPropertyValues().add("namespaceUri", "http://jaxws.remoting.springframework.org/");
clientDef.getPropertyValues().add("username", "juergen");
clientDef.getPropertyValues().add("password", "hoeller");
clientDef.getPropertyValues().add("serviceName", "OrderService");
clientDef.getPropertyValues().add("serviceInterface", OrderService.class);
clientDef.getPropertyValues().add("lookupServiceOnStartup", Boolean.FALSE);
if (features != null) {
clientDef.getPropertyValues().add("webServiceFeatures", features);
}
ac.registerBeanDefinition("client", clientDef);
GenericBeanDefinition serviceFactoryDef = new GenericBeanDefinition();
serviceFactoryDef.setBeanClass(LocalJaxWsServiceFactoryBean.class);
serviceFactoryDef.getPropertyValues().add("wsdlDocumentUrl", "http://localhost:9999/OrderService?wsdl");
serviceFactoryDef.getPropertyValues().add("namespaceUri", "http://jaxws.remoting.springframework.org/");
serviceFactoryDef.getPropertyValues().add("serviceName", "OrderService");
ac.registerBeanDefinition("orderService", serviceFactoryDef);
ac.registerBeanDefinition("accessor", new RootBeanDefinition(ServiceAccessor.class));
AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);
try {
ac.refresh();
OrderService orderService = ac.getBean("client", OrderService.class);
assertTrue(orderService instanceof BindingProvider);
((BindingProvider) orderService).getRequestContext();
String order = orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
ServiceAccessor serviceAccessor = ac.getBean("accessor", ServiceAccessor.class);
order = serviceAccessor.orderService.getOrder(1000);
assertEquals("order 1000", order);
try {
serviceAccessor.orderService.getOrder(0);
fail("Should have thrown OrderNotFoundException");
}
catch (OrderNotFoundException ex) {
// expected
}
}
catch (BeanCreationException ex) {
if ("exporter".equals(ex.getBeanName()) && ex.getRootCause() instanceof ClassNotFoundException) {
// ignore - probably running on JDK < 1.6 without the JAX-WS impl present
}
else {
throw ex;
}
}
finally {
ac.close();
}
}
public static class ServiceAccessor {
@WebServiceRef
public OrderService orderService;
public OrderService myService;
@WebServiceRef(value=OrderServiceService.class, wsdlLocation = "http://localhost:9999/OrderService?wsdl")
public void setMyService(OrderService myService) {
this.myService = myService;
}
}
@WebServiceClient(targetNamespace = "http://jaxws.remoting.springframework.org/", name="OrderService")
public static class OrderServiceService extends Service {
public OrderServiceService() throws MalformedURLException {
super(new URL("http://localhost:9999/OrderService?wsdl"),
new QName("http://jaxws.remoting.springframework.org/", "OrderService"));
}
public OrderServiceService(URL wsdlDocumentLocation, QName serviceName) {
super(wsdlDocumentLocation, serviceName);
}
}
}

View File

@@ -0,0 +1,42 @@
/*
* 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.remoting.jaxws;
import javax.xml.ws.WebFault;
/**
* @author Juergen Hoeller
*/
@WebFault
public class OrderNotFoundException extends Exception {
private String faultInfo;
public OrderNotFoundException(String message) {
super(message);
}
public OrderNotFoundException(String message, String faultInfo) {
super(message);
this.faultInfo = faultInfo;
}
public String getFaultInfo() {
return this.faultInfo;
}
}

View File

@@ -0,0 +1,31 @@
/*
* 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.remoting.jaxws;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
/**
* @author Juergen Hoeller
*/
@WebService
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface OrderService {
String getOrder(int id) throws OrderNotFoundException;
}

View File

@@ -0,0 +1,42 @@
/*
* 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.remoting.jaxws;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import org.springframework.util.Assert;
/**
* @author Juergen Hoeller
*/
@WebService(serviceName="OrderService", portName="OrderService", endpointInterface = "org.springframework.remoting.jaxws.OrderService")
public class OrderServiceImpl implements OrderService {
@Resource
private WebServiceContext webServiceContext;
public String getOrder(int id) throws OrderNotFoundException {
Assert.notNull(this.webServiceContext, "WebServiceContext has not been injected");
if (id == 0) {
throw new OrderNotFoundException("Order 0 not found");
}
return "order " + id;
}
}

View File

@@ -0,0 +1,97 @@
/*
* The Spring Framework is published under the terms
* of the Apache Software License.
*/
package org.springframework.util;
import java.awt.Point;
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;
import java.io.Serializable;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
/**
* Utilities for testing serializability of objects.
* Exposes static methods for use in other test cases.
* Extends TestCase only to test itself.
*
* @author Rod Johnson
*/
public class SerializationTestUtils extends TestCase {
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;
}
public SerializationTestUtils(String s) {
super(s);
}
public void testWithNonSerializableObject() throws IOException {
TestBean o = new TestBean();
assertFalse(o instanceof Serializable);
assertFalse(isSerializable(o));
try {
testSerialization(o);
fail();
}
catch (NotSerializableException ex) {
// Ok
}
}
public void testWithSerializableObject() throws Exception {
int x = 5;
int y = 10;
Point p = new Point(x, y);
assertTrue(p instanceof Serializable);
testSerialization(p);
assertTrue(isSerializable(p));
Point p2 = (Point) serializeAndDeserialize(p);
assertNotSame(p, p2);
assertEquals(x, (int) p2.getX());
assertEquals(y, (int) p2.getY());
}
}

View File

@@ -0,0 +1,93 @@
/*
* 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.bind;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @since 02.05.2003
*/
public class EscapedErrorsTests {
@Test
public void testEscapedErrors() {
TestBean tb = new TestBean();
tb.setName("empty &");
Errors errors = new EscapedErrors(new BindException(tb, "tb"));
errors.rejectValue("name", "NAME_EMPTY &", null, "message: &");
errors.rejectValue("age", "AGE_NOT_SET <tag>", null, "message: <tag>");
errors.rejectValue("age", "AGE_NOT_32 <tag>", null, "message: <tag>");
errors.reject("GENERAL_ERROR \" '", null, "message: \" '");
assertTrue("Correct errors flag", errors.hasErrors());
assertTrue("Correct number of errors", errors.getErrorCount() == 4);
assertTrue("Correct object name", "tb".equals(errors.getObjectName()));
assertTrue("Correct global errors flag", errors.hasGlobalErrors());
assertTrue("Correct number of global errors", errors.getGlobalErrorCount() == 1);
ObjectError globalError = errors.getGlobalError();
assertTrue("Global error message escaped", "message: &quot; &#39;".equals(globalError.getDefaultMessage()));
assertTrue("Global error code not escaped", "GENERAL_ERROR \" '".equals(globalError.getCode()));
ObjectError globalErrorInList = errors.getGlobalErrors().get(0);
assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInList.getDefaultMessage()));
ObjectError globalErrorInAllList = errors.getAllErrors().get(3);
assertTrue("Same global error in list", globalError.getDefaultMessage().equals(globalErrorInAllList.getDefaultMessage()));
assertTrue("Correct field errors flag", errors.hasFieldErrors());
assertTrue("Correct number of field errors", errors.getFieldErrorCount() == 3);
assertTrue("Correct number of field errors in list", errors.getFieldErrors().size() == 3);
FieldError fieldError = errors.getFieldError();
assertTrue("Field error code not escaped", "NAME_EMPTY &".equals(fieldError.getCode()));
assertTrue("Field value escaped", "empty &amp;".equals(errors.getFieldValue("name")));
FieldError fieldErrorInList = errors.getFieldErrors().get(0);
assertTrue("Same field error in list", fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage()));
assertTrue("Correct name errors flag", errors.hasFieldErrors("name"));
assertTrue("Correct number of name errors", errors.getFieldErrorCount("name") == 1);
assertTrue("Correct number of name errors in list", errors.getFieldErrors("name").size() == 1);
FieldError nameError = errors.getFieldError("name");
assertTrue("Name error message escaped", "message: &amp;".equals(nameError.getDefaultMessage()));
assertTrue("Name error code not escaped", "NAME_EMPTY &".equals(nameError.getCode()));
assertTrue("Name value escaped", "empty &amp;".equals(errors.getFieldValue("name")));
FieldError nameErrorInList = errors.getFieldErrors("name").get(0);
assertTrue("Same name error in list", nameError.getDefaultMessage().equals(nameErrorInList.getDefaultMessage()));
assertTrue("Correct age errors flag", errors.hasFieldErrors("age"));
assertTrue("Correct number of age errors", errors.getFieldErrorCount("age") == 2);
assertTrue("Correct number of age errors in list", errors.getFieldErrors("age").size() == 2);
FieldError ageError = errors.getFieldError("age");
assertTrue("Age error message escaped", "message: &lt;tag&gt;".equals(ageError.getDefaultMessage()));
assertTrue("Age error code not escaped", "AGE_NOT_SET <tag>".equals(ageError.getCode()));
assertTrue("Age value not escaped", (new Integer(0)).equals(errors.getFieldValue("age")));
FieldError ageErrorInList = errors.getFieldErrors("age").get(0);
assertTrue("Same name error in list", ageError.getDefaultMessage().equals(ageErrorInList.getDefaultMessage()));
FieldError ageError2 = errors.getFieldErrors("age").get(1);
assertTrue("Age error 2 message escaped", "message: &lt;tag&gt;".equals(ageError2.getDefaultMessage()));
assertTrue("Age error 2 code not escaped", "AGE_NOT_32 <tag>".equals(ageError2.getCode()));
}
}

View File

@@ -0,0 +1,256 @@
/*
* 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.bind;
import static org.junit.Assert.*;
import java.beans.PropertyEditorSupport;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
* @author Scott Andrews
*/
public class ServletRequestDataBinderTests {
@Test
public void testBindingWithNestedObjectCreation() throws Exception {
TestBean tb = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(tb, "person");
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean());
}
});
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("spouse", "someValue");
request.addParameter("spouse.name", "test");
binder.bind(request);
assertNotNull(tb.getSpouse());
assertEquals("test", tb.getSpouse().getName());
}
@Test
public void testFieldPrefixCausesFieldReset() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(request);
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(request);
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldPrefixCausesFieldResetWithIgnoreUnknownFields() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
binder.setIgnoreUnknownFields(false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(request);
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(request);
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefault() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!postProcessed", "off");
request.addParameter("postProcessed", "on");
binder.bind(request);
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(request);
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefaultPreemptsFieldMarker() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!postProcessed", "on");
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(request);
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(request);
assertTrue(target.isPostProcessed());
request.removeParameter("!postProcessed");
binder.bind(request);
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefaultNonBoolean() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!name", "anonymous");
request.addParameter("name", "Scott");
binder.bind(request);
assertEquals("Scott", target.getName());
request.removeParameter("name");
binder.bind(request);
assertEquals("anonymous", target.getName());
}
@Test
public void testWithCommaSeparatedStringArray() throws Exception {
TestBean target = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("stringArray", "bar");
request.addParameter("stringArray", "abc");
request.addParameter("stringArray", "123,def");
binder.bind(request);
assertEquals("Expected all three items to be bound", 3, target.getStringArray().length);
request.removeParameter("stringArray");
request.addParameter("stringArray", "123,def");
binder.bind(request);
assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length);
}
@Test
public void testBindingWithNestedObjectCreationAndWrongOrder() throws Exception {
TestBean tb = new TestBean();
ServletRequestDataBinder binder = new ServletRequestDataBinder(tb, "person");
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean());
}
});
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("spouse.name", "test");
request.addParameter("spouse", "someValue");
binder.bind(request);
assertNotNull(tb.getSpouse());
assertEquals("test", tb.getSpouse().getName());
}
@Test
public void testNoPrefix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("forname", "Tony");
request.addParameter("surname", "Blair");
request.addParameter("age", "" + 50);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
doTestTony(pvs);
}
@Test
public void testPrefix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("test_forname", "Tony");
request.addParameter("test_surname", "Blair");
request.addParameter("test_age", "" + 50);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Didn't fidn normal when given prefix", !pvs.contains("forname"));
assertTrue("Did treat prefix as normal when not given prefix", pvs.contains("test_forname"));
pvs = new ServletRequestParameterPropertyValues(request, "test");
doTestTony(pvs);
}
@Test
public void testNoParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Found no parameters", pvs.getPropertyValues().length == 0);
}
@Test
public void testMultipleValuesForParameter() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
String[] original = new String[] {"Tony", "Rod"};
request.addParameter("forname", original);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Found 1 parameter", pvs.getPropertyValues().length == 1);
assertTrue("Found array value", pvs.getPropertyValue("forname").getValue() instanceof String[]);
String[] values = (String[]) pvs.getPropertyValue("forname").getValue();
assertEquals("Correct values", Arrays.asList(values), Arrays.asList(original));
}
/**
* Must contain: forname=Tony surname=Blair age=50
*/
protected void doTestTony(PropertyValues pvs) throws Exception {
assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
assertTrue("Contains forname", pvs.contains("forname"));
assertTrue("Contains surname", pvs.contains("surname"));
assertTrue("Contains age", pvs.contains("age"));
assertTrue("Doesn't contain tory", !pvs.contains("tory"));
PropertyValue[] ps = pvs.getPropertyValues();
Map<String, String> m = new HashMap<String, String>();
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (int i = 0; i < ps.length; i++) {
Object val = m.get(ps[i].getName());
assertTrue("Can't have unexpected value", val != null);
assertTrue("Val i string", val instanceof String);
assertTrue("val matches expected", val.equals(ps[i].getValue()));
m.remove(ps[i].getName());
}
assertTrue("Map size is 0", m.size() == 0);
}
}

View File

@@ -0,0 +1,465 @@
/*
* 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.bind;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.util.StopWatch;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 06.08.2003
*/
public class ServletRequestUtilsTests {
@Test
public void testIntParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(ServletRequestUtils.getIntParameter(request, "param1"), new Integer(5));
assertEquals(ServletRequestUtils.getIntParameter(request, "param1", 6), 5);
assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5);
assertEquals(ServletRequestUtils.getIntParameter(request, "param2", 6), 6);
try {
ServletRequestUtils.getRequiredIntParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertEquals(ServletRequestUtils.getIntParameter(request, "param3"), null);
assertEquals(ServletRequestUtils.getIntParameter(request, "param3", 6), 6);
try {
ServletRequestUtils.getRequiredIntParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
try {
ServletRequestUtils.getRequiredIntParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testIntParameters() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param", new String[] {"1", "2", "3"});
request.addParameter("param2", "1");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
int[] array = new int[] {1, 2, 3};
int[] values = ServletRequestUtils.getRequiredIntParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
ServletRequestUtils.getRequiredIntParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testLongParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(ServletRequestUtils.getLongParameter(request, "param1"), new Long(5L));
assertEquals(ServletRequestUtils.getLongParameter(request, "param1", 6L), 5L);
assertEquals(ServletRequestUtils.getRequiredIntParameter(request, "param1"), 5L);
assertEquals(ServletRequestUtils.getLongParameter(request, "param2", 6L), 6L);
try {
ServletRequestUtils.getRequiredLongParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertEquals(ServletRequestUtils.getLongParameter(request, "param3"), null);
assertEquals(ServletRequestUtils.getLongParameter(request, "param3", 6L), 6L);
try {
ServletRequestUtils.getRequiredLongParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
try {
ServletRequestUtils.getRequiredLongParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testLongParameters() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("param", new String[] {"1", "2", "3"});
request.setParameter("param2", "0");
request.setParameter("param2", "1");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
long[] array = new long[] {1L, 2L, 3L};
long[] values = ServletRequestUtils.getRequiredLongParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
ServletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
request.setParameter("param2", new String[] {"1", "2"});
values = ServletRequestUtils.getRequiredLongParameters(request, "param2");
assertEquals(2, values.length);
assertEquals(1, values[0]);
assertEquals(2, values[1]);
request.removeParameter("param2");
try {
ServletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testFloatParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(ServletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f)));
assertTrue(ServletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f);
assertTrue(ServletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f);
assertTrue(ServletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f);
try {
ServletRequestUtils.getRequiredFloatParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertTrue(ServletRequestUtils.getFloatParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f);
try {
ServletRequestUtils.getRequiredFloatParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
try {
ServletRequestUtils.getRequiredFloatParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testFloatParameters() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param", new String[] {"1.5", "2.5", "3"});
request.addParameter("param2", "1.5");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
float[] array = new float[] {1.5F, 2.5F, 3};
float[] values = ServletRequestUtils.getRequiredFloatParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
ServletRequestUtils.getRequiredFloatParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testDoubleParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5)));
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5);
assertTrue(ServletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5);
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5);
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5);
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
try {
ServletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testDoubleParameters() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param", new String[] {"1.5", "2.5", "3"});
request.addParameter("param2", "1.5");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
double[] array = new double[] {1.5, 2.5, 3};
double[] values = ServletRequestUtils.getRequiredDoubleParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
ServletRequestUtils.getRequiredDoubleParameters(request, "param2");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
}
@Test
public void testBooleanParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "true");
request.addParameter("param2", "e");
request.addParameter("param4", "yes");
request.addParameter("param5", "1");
request.addParameter("paramEmpty", "");
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE));
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param1", false));
assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param1"));
assertFalse(ServletRequestUtils.getBooleanParameter(request, "param2", true));
assertFalse(ServletRequestUtils.getRequiredBooleanParameter(request, "param2"));
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3") == null);
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param3", true));
try {
ServletRequestUtils.getRequiredBooleanParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param4", false));
assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param4"));
assertTrue(ServletRequestUtils.getBooleanParameter(request, "param5", false));
assertTrue(ServletRequestUtils.getRequiredBooleanParameter(request, "param5"));
assertFalse(ServletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty"));
}
@Test
public void testBooleanParameters() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param", new String[] {"true", "yes", "off", "1", "bogus"});
request.addParameter("param2", "false");
request.addParameter("param2", "true");
request.addParameter("param2", "");
boolean[] array = new boolean[] {true, true, false, true, false};
boolean[] values = ServletRequestUtils.getRequiredBooleanParameters(request, "param");
assertEquals(array.length, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
array = new boolean[] {false, true, false};
values = ServletRequestUtils.getRequiredBooleanParameters(request, "param2");
assertEquals(array.length, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
}
@Test
public void testStringParameter() throws ServletRequestBindingException {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("param1", "str");
request.addParameter("paramEmpty", "");
assertEquals("str", ServletRequestUtils.getStringParameter(request, "param1"));
assertEquals("str", ServletRequestUtils.getStringParameter(request, "param1", "string"));
assertEquals("str", ServletRequestUtils.getRequiredStringParameter(request, "param1"));
assertEquals(null, ServletRequestUtils.getStringParameter(request, "param3"));
assertEquals("string", ServletRequestUtils.getStringParameter(request, "param3", "string"));
assertNull(ServletRequestUtils.getStringParameter(request, "param3", null));
try {
ServletRequestUtils.getRequiredStringParameter(request, "param3");
fail("Should have thrown ServletRequestBindingException");
}
catch (ServletRequestBindingException ex) {
// expected
}
assertEquals("", ServletRequestUtils.getStringParameter(request, "paramEmpty"));
assertEquals("", ServletRequestUtils.getRequiredStringParameter(request, "paramEmpty"));
}
@Test
public void testGetIntParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getIntParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
@Test
public void testGetLongParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getLongParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
@Test
public void testGetFloatParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getFloatParameter(request, "nonExistingParam", 0f);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
@Test
public void testGetDoubleParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getDoubleParameter(request, "nonExistingParam", 0d);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
@Test
public void testGetBooleanParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getBooleanParameter(request, "nonExistingParam", false);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
@Test
public void testGetStringParameterWithDefaultValueHandlingIsFastEnough() {
MockHttpServletRequest request = new MockHttpServletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
ServletRequestUtils.getStringParameter(request, "nonExistingParam", "defaultValue");
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
}

View File

@@ -0,0 +1,324 @@
/*
* 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.bind.support;
import java.beans.PropertyEditorSupport;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.support.StringMultipartFileEditor;
/**
* @author Juergen Hoeller
*/
public class WebRequestDataBinderTests {
@Test
public void testBindingWithNestedObjectCreation() throws Exception {
TestBean tb = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(tb, "person");
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean());
}
});
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("spouse", "someValue");
request.addParameter("spouse.name", "test");
binder.bind(new ServletWebRequest(request));
assertNotNull(tb.getSpouse());
assertEquals("test", tb.getSpouse().getName());
}
@Test
public void testBindingWithNestedObjectCreationThroughAutoGrow() throws Exception {
TestBean tb = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(tb, "person");
binder.setIgnoreUnknownFields(false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("concreteSpouse.name", "test");
binder.bind(new ServletWebRequest(request));
assertNotNull(tb.getSpouse());
assertEquals("test", tb.getSpouse().getName());
}
@Test
public void testFieldPrefixCausesFieldReset() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(new ServletWebRequest(request));
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(new ServletWebRequest(request));
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldPrefixCausesFieldResetWithIgnoreUnknownFields() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
binder.setIgnoreUnknownFields(false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(new ServletWebRequest(request));
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(new ServletWebRequest(request));
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefault() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!postProcessed", "off");
request.addParameter("postProcessed", "on");
binder.bind(new ServletWebRequest(request));
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(new ServletWebRequest(request));
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefaultPreemptsFieldMarker() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!postProcessed", "on");
request.addParameter("_postProcessed", "visible");
request.addParameter("postProcessed", "on");
binder.bind(new ServletWebRequest(request));
assertTrue(target.isPostProcessed());
request.removeParameter("postProcessed");
binder.bind(new ServletWebRequest(request));
assertTrue(target.isPostProcessed());
request.removeParameter("!postProcessed");
binder.bind(new ServletWebRequest(request));
assertFalse(target.isPostProcessed());
}
@Test
public void testFieldDefaultNonBoolean() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("!name", "anonymous");
request.addParameter("name", "Scott");
binder.bind(new ServletWebRequest(request));
assertEquals("Scott", target.getName());
request.removeParameter("name");
binder.bind(new ServletWebRequest(request));
assertEquals("anonymous", target.getName());
}
@Test
public void testWithCommaSeparatedStringArray() throws Exception {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("stringArray", "bar");
request.addParameter("stringArray", "abc");
request.addParameter("stringArray", "123,def");
binder.bind(new ServletWebRequest(request));
assertEquals("Expected all three items to be bound", 3, target.getStringArray().length);
request.removeParameter("stringArray");
request.addParameter("stringArray", "123,def");
binder.bind(new ServletWebRequest(request));
assertEquals("Expected only 1 item to be bound", 1, target.getStringArray().length);
}
@Test
public void testEnumBinding() {
EnumHolder target = new EnumHolder();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("myEnum", "FOO");
binder.bind(new ServletWebRequest(request));
assertEquals(MyEnum.FOO, target.getMyEnum());
}
@Test
public void testMultipartFileAsString() {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
request.addFile(new MockMultipartFile("name", "Juergen".getBytes()));
binder.bind(new ServletWebRequest(request));
assertEquals("Juergen", target.getName());
}
@Test
public void testMultipartFileAsStringArray() {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
request.addFile(new MockMultipartFile("stringArray", "Juergen".getBytes()));
binder.bind(new ServletWebRequest(request));
assertEquals(1, target.getStringArray().length);
assertEquals("Juergen", target.getStringArray()[0]);
}
@Test
public void testMultipartFilesAsStringArray() {
TestBean target = new TestBean();
WebRequestDataBinder binder = new WebRequestDataBinder(target);
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
request.addFile(new MockMultipartFile("stringArray", "Juergen".getBytes()));
request.addFile(new MockMultipartFile("stringArray", "Eva".getBytes()));
binder.bind(new ServletWebRequest(request));
assertEquals(2, target.getStringArray().length);
assertEquals("Juergen", target.getStringArray()[0]);
assertEquals("Eva", target.getStringArray()[1]);
}
@Test
public void testNoPrefix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("forname", "Tony");
request.addParameter("surname", "Blair");
request.addParameter("age", "" + 50);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
doTestTony(pvs);
}
@Test
public void testPrefix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("test_forname", "Tony");
request.addParameter("test_surname", "Blair");
request.addParameter("test_age", "" + 50);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Didn't fidn normal when given prefix", !pvs.contains("forname"));
assertTrue("Did treat prefix as normal when not given prefix", pvs.contains("test_forname"));
pvs = new ServletRequestParameterPropertyValues(request, "test");
doTestTony(pvs);
}
/**
* Must contain: forname=Tony surname=Blair age=50
*/
protected void doTestTony(PropertyValues pvs) throws Exception {
assertTrue("Contains 3", pvs.getPropertyValues().length == 3);
assertTrue("Contains forname", pvs.contains("forname"));
assertTrue("Contains surname", pvs.contains("surname"));
assertTrue("Contains age", pvs.contains("age"));
assertTrue("Doesn't contain tory", !pvs.contains("tory"));
PropertyValue[] pvArray = pvs.getPropertyValues();
Map<String, String> m = new HashMap<String, String>();
m.put("forname", "Tony");
m.put("surname", "Blair");
m.put("age", "50");
for (PropertyValue pv : pvArray) {
Object val = m.get(pv.getName());
assertTrue("Can't have unexpected value", val != null);
assertTrue("Val i string", val instanceof String);
assertTrue("val matches expected", val.equals(pv.getValue()));
m.remove(pv.getName());
}
assertTrue("Map size is 0", m.size() == 0);
}
@Test
public void testNoParameters() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Found no parameters", pvs.getPropertyValues().length == 0);
}
@Test
public void testMultipleValuesForParameter() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
String[] original = new String[] {"Tony", "Rod"};
request.addParameter("forname", original);
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(request);
assertTrue("Found 1 parameter", pvs.getPropertyValues().length == 1);
assertTrue("Found array value", pvs.getPropertyValue("forname").getValue() instanceof String[]);
String[] values = (String[]) pvs.getPropertyValue("forname").getValue();
assertEquals("Correct values", Arrays.asList(values), Arrays.asList(original));
}
public static class EnumHolder {
private MyEnum myEnum;
public MyEnum getMyEnum() {
return myEnum;
}
public void setMyEnum(MyEnum myEnum) {
this.myEnum = myEnum;
}
}
public enum MyEnum {
FOO, BAR
}
}

View File

@@ -0,0 +1,117 @@
/*
* 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.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/** @author Arjen Poutsma */
public class DefaultResponseErrorHandlerTests {
private DefaultResponseErrorHandler handler;
private ClientHttpResponse response;
@Before
public void setUp() throws Exception {
handler = new DefaultResponseErrorHandler();
response = createMock(ClientHttpResponse.class);
}
@Test
public void hasErrorTrue() throws Exception {
expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND);
replay(response);
assertTrue(handler.hasError(response));
verify(response);
}
@Test
public void hasErrorFalse() throws Exception {
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
replay(response);
assertFalse(handler.hasError(response));
verify(response);
}
@Test(expected = HttpClientErrorException.class)
public void handleError() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND);
expect(response.getStatusText()).andReturn("Not Found");
expect(response.getHeaders()).andReturn(headers);
expect(response.getBody()).andReturn(new ByteArrayInputStream("Hello World".getBytes("UTF-8")));
replay(response);
handler.handleError(response);
verify(response);
}
@Test(expected = HttpClientErrorException.class)
public void handleErrorIOException() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND);
expect(response.getStatusText()).andReturn("Not Found");
expect(response.getHeaders()).andReturn(headers);
expect(response.getBody()).andThrow(new IOException());
replay(response);
handler.handleError(response);
verify(response);
}
@Test(expected = HttpClientErrorException.class)
public void handleErrorNullResponse() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND);
expect(response.getStatusText()).andReturn("Not Found");
expect(response.getHeaders()).andReturn(headers);
expect(response.getBody()).andReturn(null);
replay(response);
handler.handleError(response);
verify(response);
}
}

View File

@@ -0,0 +1,391 @@
/*
* 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.client;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.FreePortScanner;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
/** @author Arjen Poutsma */
public class RestTemplateIntegrationTests {
private RestTemplate template;
private static Server jettyServer;
private static String helloWorld = "H\u00e9llo W\u00f6rld";
private static String baseUrl;
private static MediaType contentType;
@BeforeClass
public static void startJettyServer() throws Exception {
int port = FreePortScanner.getFreePort();
jettyServer = new Server(port);
baseUrl = "http://localhost:" + port;
Context jettyContext = new Context(jettyServer, "/");
byte[] bytes = helloWorld.getBytes("UTF-8");
contentType = new MediaType("text", "plain", Collections.singletonMap("charset", "utf-8"));
jettyContext.addServlet(new ServletHolder(new GetServlet(bytes, contentType)), "/get");
jettyContext.addServlet(new ServletHolder(new GetServlet(new byte[0], contentType)), "/get/nothing");
jettyContext.addServlet(new ServletHolder(new GetServlet(bytes, null)), "/get/nocontenttype");
jettyContext.addServlet(
new ServletHolder(new PostServlet(helloWorld, baseUrl + "/post/1", bytes, contentType)),
"/post");
jettyContext.addServlet(new ServletHolder(new StatusCodeServlet(204)), "/status/nocontent");
jettyContext.addServlet(new ServletHolder(new StatusCodeServlet(304)), "/status/notmodified");
jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/status/notfound");
jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/status/server");
jettyContext.addServlet(new ServletHolder(new UriServlet()), "/uri/*");
jettyContext.addServlet(new ServletHolder(new MultipartServlet()), "/multipart");
jettyServer.start();
}
@Before
public void createTemplate() {
template = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
}
@AfterClass
public static void stopJettyServer() throws Exception {
if (jettyServer != null) {
jettyServer.stop();
}
}
@Test
public void getString() {
String s = template.getForObject(baseUrl + "/{method}", String.class, "get");
assertEquals("Invalid content", helloWorld, s);
}
@Test
public void getEntity() {
ResponseEntity<String> entity = template.getForEntity(baseUrl + "/{method}", String.class, "get");
assertEquals("Invalid content", helloWorld, entity.getBody());
assertFalse("No headers", entity.getHeaders().isEmpty());
assertEquals("Invalid content-type", contentType, entity.getHeaders().getContentType());
assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode());
}
@Test
public void getNoResponse() {
String s = template.getForObject(baseUrl + "/get/nothing", String.class);
assertNull("Invalid content", s);
}
@Test
public void getNoContentTypeHeader() throws UnsupportedEncodingException {
byte[] bytes = template.getForObject(baseUrl + "/get/nocontenttype", byte[].class);
assertArrayEquals("Invalid content", helloWorld.getBytes("UTF-8"), bytes);
}
@Test
public void getNoContent() {
String s = template.getForObject(baseUrl + "/status/nocontent", String.class);
assertNull("Invalid content", s);
ResponseEntity<String> entity = template.getForEntity(baseUrl + "/status/nocontent", String.class);
assertEquals("Invalid response code", HttpStatus.NO_CONTENT, entity.getStatusCode());
assertNull("Invalid content", entity.getBody());
}
@Test
public void getNotModified() {
String s = template.getForObject(baseUrl + "/status/notmodified", String.class);
assertNull("Invalid content", s);
ResponseEntity<String> entity = template.getForEntity(baseUrl + "/status/notmodified", String.class);
assertEquals("Invalid response code", HttpStatus.NOT_MODIFIED, entity.getStatusCode());
assertNull("Invalid content", entity.getBody());
}
@Test
public void postForLocation() throws URISyntaxException {
URI location = template.postForLocation(baseUrl + "/{method}", helloWorld, "post");
assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location);
}
@Test
public void postForLocationEntity() throws URISyntaxException {
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(new MediaType("text", "plain", Charset.forName("ISO-8859-15")));
HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
URI location = template.postForLocation(baseUrl + "/{method}", entity, "post");
assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location);
}
@Test
public void postForObject() throws URISyntaxException {
String s = template.postForObject(baseUrl + "/{method}", helloWorld, String.class, "post");
assertEquals("Invalid content", helloWorld, s);
}
@Test
public void notFound() {
try {
template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
fail("HttpClientErrorException expected");
}
catch (HttpClientErrorException ex) {
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
}
}
@Test
public void serverError() {
try {
template.execute(baseUrl + "/status/server", HttpMethod.GET, null, null);
fail("HttpServerErrorException expected");
}
catch (HttpServerErrorException ex) {
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode());
assertNotNull(ex.getStatusText());
assertNotNull(ex.getResponseBodyAsString());
}
}
@Test
public void optionsForAllow() throws URISyntaxException {
Set<HttpMethod> allowed = template.optionsForAllow(new URI(baseUrl + "/get"));
assertEquals("Invalid response",
EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE), allowed);
}
@Test
public void uri() throws InterruptedException, URISyntaxException {
String result = template.getForObject(baseUrl + "/uri/{query}", String.class, "Z\u00fcrich");
assertEquals("Invalid request URI", "/uri/Z%C3%BCrich", result);
result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "foo@bar");
assertEquals("Invalid request URI", "/uri/query=foo@bar", result);
result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "T\u014dky\u014d");
assertEquals("Invalid request URI", "/uri/query=T%C5%8Dky%C5%8D", result);
}
@Test
public void multipart() throws UnsupportedEncodingException {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("name 1", "value 1");
parts.add("name 2", "value 2+1");
parts.add("name 2", "value 2+2");
Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
parts.add("logo", logo);
template.postForLocation(baseUrl + "/multipart", parts);
}
@Test
public void exchangeGet() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyHeader", "MyValue");
HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
ResponseEntity<String> response =
template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get");
assertEquals("Invalid content", helloWorld, response.getBody());
}
@Test
public void exchangePost() throws Exception {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("MyHeader", "MyValue");
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> requestEntity = new HttpEntity<String>(helloWorld, requestHeaders);
HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, Void.class, "post");
assertEquals("Invalid location", new URI(baseUrl + "/post/1"), result.getHeaders().getLocation());
assertFalse(result.hasBody());
}
/** Servlet that sets the given status code. */
private static class StatusCodeServlet extends GenericServlet {
private final int sc;
private StatusCodeServlet(int sc) {
this.sc = sc;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
((HttpServletResponse) response).setStatus(sc);
}
}
/** Servlet that returns an error message for a given status code. */
private static class ErrorServlet extends GenericServlet {
private final int sc;
private ErrorServlet(int sc) {
this.sc = sc;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
((HttpServletResponse) response).sendError(sc);
}
}
private static class GetServlet extends HttpServlet {
private final byte[] buf;
private final MediaType contentType;
private GetServlet(byte[] buf, MediaType contentType) {
this.buf = buf;
this.contentType = contentType;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (contentType != null) {
response.setContentType(contentType.toString());
}
response.setContentLength(buf.length);
FileCopyUtils.copy(buf, response.getOutputStream());
}
}
private static class PostServlet extends HttpServlet {
private final String s;
private final String location;
private final byte[] buf;
private final MediaType contentType;
private PostServlet(String s, String location, byte[] buf, MediaType contentType) {
this.s = s;
this.location = location;
this.buf = buf;
this.contentType = contentType;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
assertTrue("Invalid request content-length", request.getContentLength() > 0);
assertNotNull("No content-type", request.getContentType());
String body = FileCopyUtils.copyToString(request.getReader());
assertEquals("Invalid request body", s, body);
response.setStatus(HttpServletResponse.SC_CREATED);
response.setHeader("Location", location);
response.setContentLength(buf.length);
response.setContentType(contentType.toString());
FileCopyUtils.copy(buf, response.getOutputStream());
}
}
private static class UriServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(req.getRequestURI());
}
}
private static class MultipartServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
assertTrue(ServletFileUpload.isMultipartContent(req));
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(req);
assertEquals(4, items.size());
FileItem item = (FileItem) items.get(0);
assertTrue(item.isFormField());
assertEquals("name 1", item.getFieldName());
assertEquals("value 1", item.getString());
item = (FileItem) items.get(1);
assertTrue(item.isFormField());
assertEquals("name 2", item.getFieldName());
assertEquals("value 2+1", item.getString());
item = (FileItem) items.get(2);
assertTrue(item.isFormField());
assertEquals("name 2", item.getFieldName());
assertEquals("value 2+2", item.getString());
item = (FileItem) items.get(3);
assertFalse(item.isFormField());
assertEquals("logo", item.getFieldName());
assertEquals("logo.jpg", item.getName());
assertEquals("image/jpeg", item.getContentType());
}
catch (FileUploadException ex) {
throw new ServletException(ex);
}
}
}
}

View File

@@ -0,0 +1,650 @@
/*
* 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.client;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
/** @author Arjen Poutsma */
@SuppressWarnings("unchecked")
public class RestTemplateTests {
private RestTemplate template;
private ClientHttpRequestFactory requestFactory;
private ClientHttpRequest request;
private ClientHttpResponse response;
private ResponseErrorHandler errorHandler;
private HttpMessageConverter converter;
@Before
public void setUp() {
requestFactory = createMock(ClientHttpRequestFactory.class);
request = createMock(ClientHttpRequest.class);
response = createMock(ClientHttpResponse.class);
errorHandler = createMock(ResponseErrorHandler.class);
converter = createMock(HttpMessageConverter.class);
template = new RestTemplate(requestFactory);
template.setErrorHandler(errorHandler);
template.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(converter));
}
@Test
public void varArgsTemplateVariables() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET))
.andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
template.execute("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42",
"21");
verifyMocks();
}
@Test
public void varArgsNullTemplateVariable() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET))
.andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, null, "foo");
verifyMocks();
}
@Test
public void mapTemplateVariables() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/42"), HttpMethod.GET))
.andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
Map<String, String> vars = Collections.singletonMap("hotel", "42");
template.execute("http://example.com/hotels/{hotel}/bookings/{hotel}", HttpMethod.GET, null, null, vars);
verifyMocks();
}
@Test
public void mapNullTemplateVariable() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET))
.andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
Map<String, String> vars = new HashMap<String, String>(2);
vars.put("first", null);
vars.put("last", "foo");
template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, vars);
verifyMocks();
}
@Test
public void errorHandling() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(true);
expect(response.getStatusCode()).andReturn(HttpStatus.INTERNAL_SERVER_ERROR);
expect(response.getStatusText()).andReturn("Internal Server Error");
errorHandler.handleError(response);
expectLastCall().andThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
response.close();
replayMocks();
try {
template.execute("http://example.com", HttpMethod.GET, null, null);
fail("HttpServerErrorException expected");
}
catch (HttpServerErrorException ex) {
// expected
}
verifyMocks();
}
@Test
public void getForObject() throws Exception {
expect(converter.canRead(String.class, null)).andReturn(true);
MediaType textPlain = new MediaType("text", "plain");
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(2);
expect(converter.canRead(String.class, textPlain)).andReturn(true);
String expected = "Hello World";
expect(converter.read(String.class, response)).andReturn(expected);
response.close();
replayMocks();
String result = template.getForObject("http://example.com", String.class);
assertEquals("Invalid GET result", expected, result);
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verifyMocks();
}
@Test
public void getUnsupportedMediaType() throws Exception {
expect(converter.canRead(String.class, null)).andReturn(true);
MediaType supportedMediaType = new MediaType("foo", "bar");
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(supportedMediaType));
expect(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = new MediaType("bar", "baz");
responseHeaders.setContentType(contentType);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(2);
expect(converter.canRead(String.class, contentType)).andReturn(false);
response.close();
replayMocks();
try {
template.getForObject("http://example.com/{p}", String.class, "resource");
fail("UnsupportedMediaTypeException expected");
}
catch (RestClientException ex) {
// expected
}
verifyMocks();
}
@Test
public void getForEntity() throws Exception {
expect(converter.canRead(String.class, null)).andReturn(true);
MediaType textPlain = new MediaType("text", "plain");
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(3);
expect(converter.canRead(String.class, textPlain)).andReturn(true);
String expected = "Hello World";
expect(converter.read(String.class, response)).andReturn(expected);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
response.close();
replayMocks();
ResponseEntity<String> result = template.getForEntity("http://example.com", String.class);
assertEquals("Invalid GET result", expected, result.getBody());
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
assertEquals("Invalid Content-Type header", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verifyMocks();
}
@Test
public void headForHeaders() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.HEAD)).andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
HttpHeaders result = template.headForHeaders("http://example.com");
assertSame("Invalid headers returned", responseHeaders, result);
verifyMocks();
}
@Test
public void postForLocation() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
String helloWorld = "Hello World";
expect(converter.canWrite(String.class, null)).andReturn(true);
converter.write(helloWorld, null, request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
URI result = template.postForLocation("http://example.com", helloWorld);
assertEquals("Invalid POST result", expected, result);
verifyMocks();
}
@Test
public void postForLocationEntityContentType() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
String helloWorld = "Hello World";
MediaType contentType = MediaType.TEXT_PLAIN;
expect(converter.canWrite(String.class, contentType)).andReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
converter.write(helloWorld, contentType, request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(contentType);
HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
URI result = template.postForLocation("http://example.com", entity);
assertEquals("Invalid POST result", expected, result);
verifyMocks();
}
@Test
public void postForLocationEntityCustomHeader() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
String helloWorld = "Hello World";
expect(converter.canWrite(String.class, null)).andReturn(true);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
converter.write(helloWorld, null, request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("http://example.com/hotels");
responseHeaders.setLocation(expected);
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> entity = new HttpEntity<String>(helloWorld, entityHeaders);
URI result = template.postForLocation("http://example.com", entity);
assertEquals("Invalid POST result", expected, result);
assertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader"));
verifyMocks();
}
@Test
public void postForLocationNoLocation() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
String helloWorld = "Hello World";
expect(converter.canWrite(String.class, null)).andReturn(true);
converter.write(helloWorld, null, request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
URI result = template.postForLocation("http://example.com", helloWorld);
assertNull("Invalid POST result", result);
verifyMocks();
}
@Test
public void postForLocationNull() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
template.postForLocation("http://example.com", null);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verifyMocks();
}
@Test
public void postForObject() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
expect(converter.canRead(Integer.class, null)).andReturn(true);
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(this.request.getHeaders()).andReturn(requestHeaders);
String request = "Hello World";
expect(converter.canWrite(String.class, null)).andReturn(true);
converter.write(request, null, this.request);
expect(this.request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(2);
Integer expected = 42;
expect(converter.canRead(Integer.class, textPlain)).andReturn(true);
expect(converter.read(Integer.class, response)).andReturn(expected);
response.close();
replayMocks();
Integer result = template.postForObject("http://example.com", request, Integer.class);
assertEquals("Invalid POST result", expected, result);
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
verifyMocks();
}
@Test
public void postForEntity() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
expect(converter.canRead(Integer.class, null)).andReturn(true);
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(this.request.getHeaders()).andReturn(requestHeaders);
String request = "Hello World";
expect(converter.canWrite(String.class, null)).andReturn(true);
converter.write(request, null, this.request);
expect(this.request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(3);
Integer expected = 42;
expect(converter.canRead(Integer.class, textPlain)).andReturn(true);
expect(converter.read(Integer.class, response)).andReturn(expected);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
response.close();
replayMocks();
ResponseEntity<Integer> result = template.postForEntity("http://example.com", request, Integer.class);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verifyMocks();
}
@Test
public void postForObjectNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
expect(converter.canRead(Integer.class, null)).andReturn(true);
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders).times(2);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(2);
expect(converter.canRead(Integer.class, textPlain)).andReturn(true);
expect(converter.read(Integer.class, response)).andReturn(null);
response.close();
replayMocks();
Integer result = template.postForObject("http://example.com", null, Integer.class);
assertNull("Invalid POST result", result);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verifyMocks();
}
@Test
public void postForEntityNull() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
expect(converter.canRead(Integer.class, null)).andReturn(true);
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders).times(2);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(3);
expect(converter.canRead(Integer.class, textPlain)).andReturn(true);
expect(converter.read(Integer.class, response)).andReturn(null);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
response.close();
replayMocks();
ResponseEntity<Integer> result = template.postForEntity("http://example.com", null, Integer.class);
assertFalse("Invalid POST result", result.hasBody());
assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verifyMocks();
}
@Test
public void put() throws Exception {
expect(converter.canWrite(String.class, null)).andReturn(true);
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).andReturn(request);
String helloWorld = "Hello World";
converter.write(helloWorld, null, request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
template.put("http://example.com", helloWorld);
verifyMocks();
}
@Test
public void putNull() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).andReturn(request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(request.getHeaders()).andReturn(requestHeaders);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
template.put("http://example.com", null);
assertEquals("Invalid content length", 0, requestHeaders.getContentLength());
verifyMocks();
}
@Test
public void delete() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
response.close();
replayMocks();
template.delete("http://example.com");
verifyMocks();
}
@Test
public void optionsForAllow() throws Exception {
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).andReturn(request);
expect(request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST);
responseHeaders.setAllow(expected);
expect(response.getHeaders()).andReturn(responseHeaders);
response.close();
replayMocks();
Set<HttpMethod> result = template.optionsForAllow("http://example.com");
assertEquals("Invalid OPTIONS result", expected, result);
verifyMocks();
}
@Test
public void ioException() throws Exception {
expect(converter.canRead(String.class, null)).andReturn(true);
MediaType mediaType = new MediaType("foo", "bar");
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(mediaType));
expect(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).andReturn(request);
expect(request.getHeaders()).andReturn(new HttpHeaders());
expect(request.execute()).andThrow(new IOException());
replayMocks();
try {
template.getForObject("http://example.com/resource", String.class);
fail("RestClientException expected");
}
catch (ResourceAccessException ex) {
// expected
}
verifyMocks();
}
@Test
public void exchange() throws Exception {
MediaType textPlain = new MediaType("text", "plain");
expect(converter.canRead(Integer.class, null)).andReturn(true);
expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain));
expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request);
HttpHeaders requestHeaders = new HttpHeaders();
expect(this.request.getHeaders()).andReturn(requestHeaders).times(2);
expect(converter.canWrite(String.class, null)).andReturn(true);
String body = "Hello World";
converter.write(body, null, this.request);
expect(this.request.execute()).andReturn(response);
expect(errorHandler.hasError(response)).andReturn(false);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(textPlain);
responseHeaders.setContentLength(10);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
expect(response.getHeaders()).andReturn(responseHeaders).times(3);
Integer expected = 42;
expect(converter.canRead(Integer.class, textPlain)).andReturn(true);
expect(converter.read(Integer.class, response)).andReturn(expected);
expect(response.getStatusCode()).andReturn(HttpStatus.OK);
response.close();
replayMocks();
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.set("MyHeader", "MyValue");
HttpEntity<String> requestEntity = new HttpEntity<String>(body, entityHeaders);
ResponseEntity<Integer> result = template.exchange("http://example.com", HttpMethod.POST, requestEntity, Integer.class);
assertEquals("Invalid POST result", expected, result.getBody());
assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType());
assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept"));
assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());
verifyMocks();
}
private void replayMocks() {
replay(requestFactory, request, response, errorHandler, converter);
}
private void verifyMocks() {
verify(requestFactory, request, response, errorHandler, converter);
}
}

View File

@@ -0,0 +1,105 @@
/*
* 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.context.request;
import javax.servlet.http.HttpServletRequest;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class RequestAndSessionScopedBeanTests {
@Test
public void testPutBeanInRequest() throws Exception {
String targetBeanName = "target";
StaticWebApplicationContext wac = new StaticWebApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
bd.getPropertyValues().add("name", "abc");
wac.registerBeanDefinition(targetBeanName, bd);
wac.refresh();
HttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
TestBean target = (TestBean) wac.getBean(targetBeanName);
assertEquals("abc", target.getName());
assertSame(target, request.getAttribute(targetBeanName));
TestBean target2 = (TestBean) wac.getBean(targetBeanName);
assertEquals("abc", target2.getName());
assertSame(target2, target);
assertSame(target2, request.getAttribute(targetBeanName));
request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
TestBean target3 = (TestBean) wac.getBean(targetBeanName);
assertEquals("abc", target3.getName());
assertSame(target3, request.getAttribute(targetBeanName));
assertNotSame(target3, target);
RequestContextHolder.setRequestAttributes(null);
try {
wac.getBean(targetBeanName);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
}
@Test
public void testPutBeanInSession() throws Exception {
String targetBeanName = "target";
HttpServletRequest request = new MockHttpServletRequest();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
StaticWebApplicationContext wac = new StaticWebApplicationContext();
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setScope(WebApplicationContext.SCOPE_SESSION);
bd.getPropertyValues().add("name", "abc");
wac.registerBeanDefinition(targetBeanName, bd);
wac.refresh();
TestBean target = (TestBean) wac.getBean(targetBeanName);
assertEquals("abc", target.getName());
assertSame(target, request.getSession().getAttribute(targetBeanName));
RequestContextHolder.setRequestAttributes(null);
try {
wac.getBean(targetBeanName);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* 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.request;
import javax.servlet.ServletRequestEvent;
import junit.framework.TestCase;
import org.springframework.core.task.MockRunnable;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
/**
* @author Juergen Hoeller
*/
public class RequestContextListenerTests extends TestCase {
public void testRequestContextListenerWithSameThread() {
RequestContextListener listener = new RequestContextListener();
MockServletContext context = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(context);
request.setAttribute("test", "value");
assertNull(RequestContextHolder.getRequestAttributes());
listener.requestInitialized(new ServletRequestEvent(context, request));
assertNotNull(RequestContextHolder.getRequestAttributes());
assertEquals("value",
RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST));
MockRunnable runnable = new MockRunnable();
RequestContextHolder.getRequestAttributes().registerDestructionCallback(
"test", runnable, RequestAttributes.SCOPE_REQUEST);
listener.requestDestroyed(new ServletRequestEvent(context, request));
assertNull(RequestContextHolder.getRequestAttributes());
assertTrue(runnable.wasExecuted());
}
public void testRequestContextListenerWithSameThreadAndAttributesGone() {
RequestContextListener listener = new RequestContextListener();
MockServletContext context = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(context);
request.setAttribute("test", "value");
assertNull(RequestContextHolder.getRequestAttributes());
listener.requestInitialized(new ServletRequestEvent(context, request));
assertNotNull(RequestContextHolder.getRequestAttributes());
assertEquals("value",
RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST));
MockRunnable runnable = new MockRunnable();
RequestContextHolder.getRequestAttributes().registerDestructionCallback(
"test", runnable, RequestAttributes.SCOPE_REQUEST);
request.clearAttributes();
listener.requestDestroyed(new ServletRequestEvent(context, request));
assertNull(RequestContextHolder.getRequestAttributes());
assertTrue(runnable.wasExecuted());
}
public void testRequestContextListenerWithDifferentThread() {
final RequestContextListener listener = new RequestContextListener();
final MockServletContext context = new MockServletContext();
final MockHttpServletRequest request = new MockHttpServletRequest(context);
request.setAttribute("test", "value");
assertNull(RequestContextHolder.getRequestAttributes());
listener.requestInitialized(new ServletRequestEvent(context, request));
assertNotNull(RequestContextHolder.getRequestAttributes());
assertEquals("value",
RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST));
MockRunnable runnable = new MockRunnable();
RequestContextHolder.getRequestAttributes().registerDestructionCallback(
"test", runnable, RequestAttributes.SCOPE_REQUEST);
// Execute requestDestroyed callback in different thread.
Thread thread = new Thread() {
public void run() {
listener.requestDestroyed(new ServletRequestEvent(context, request));
}
};
thread.start();
try {
thread.join();
}
catch (InterruptedException ex) {
}
// Still bound to original thread, but at least completed.
assertNotNull(RequestContextHolder.getRequestAttributes());
assertTrue(runnable.wasExecuted());
// Check that a repeated execution in the same thread works and performs cleanup.
listener.requestInitialized(new ServletRequestEvent(context, request));
listener.requestDestroyed(new ServletRequestEvent(context, request));
assertNull(RequestContextHolder.getRequestAttributes());
}
}

View File

@@ -0,0 +1,175 @@
/*
* 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.request;
import junit.framework.TestCase;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Mark Fisher
*/
public class RequestScopeTests extends TestCase {
private DefaultListableBeanFactory beanFactory;
protected void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.registerScope("request", new RequestScope());
this.beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("requestScopeTests.xml", getClass()));
this.beanFactory.preInstantiateSingletons();
}
public void testGetFromScope() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/path");
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "requestScopedObject";
assertNull(request.getAttribute(name));
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertEquals("/path", bean.getName());
assertSame(bean, request.getAttribute(name));
assertSame(bean, this.beanFactory.getBean(name));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testDestructionAtRequestCompletion() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "requestScopedDisposableObject";
assertNull(request.getAttribute(name));
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertSame(bean, request.getAttribute(name));
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testGetFromFactoryBeanInScope() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "requestScopedFactoryBean";
assertNull(request.getAttribute(name));
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertTrue(request.getAttribute(name) instanceof FactoryBean);
assertSame(bean, this.beanFactory.getBean(name));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testCircleLeadsToException() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "requestScopedObjectCircle1";
assertNull(request.getAttribute(name));
this.beanFactory.getBean(name);
fail("Should have thrown BeanCreationException");
}
catch (BeanCreationException ex) {
// expected
assertTrue(ex.contains(BeanCurrentlyInCreationException.class));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testInnerBeanInheritsContainingBeanScopeByDefault() {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String outerBeanName = "requestScopedOuterBean";
assertNull(request.getAttribute(outerBeanName));
TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName);
assertNotNull(request.getAttribute(outerBeanName));
TestBean inner1 = (TestBean) outer1.getSpouse();
assertSame(outer1, this.beanFactory.getBean(outerBeanName));
requestAttributes.requestCompleted();
assertTrue(outer1.wasDestroyed());
assertTrue(inner1.wasDestroyed());
request = new MockHttpServletRequest();
requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName);
assertNotSame(outer1, outer2);
assertNotSame(inner1, outer2.getSpouse());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testRequestScopedInnerBeanDestroyedWhileContainedBySingleton() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String outerBeanName = "singletonOuterBean";
TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName);
assertNull(request.getAttribute(outerBeanName));
TestBean inner1 = (TestBean) outer1.getSpouse();
TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName);
assertSame(outer1, outer2);
assertSame(inner1, outer2.getSpouse());
requestAttributes.requestCompleted();
assertTrue(inner1.wasDestroyed());
assertFalse(outer1.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
}

View File

@@ -0,0 +1,200 @@
/*
* 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.context.request;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.DummyFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* @author Juergen Hoeller
*/
public class RequestScopedProxyTests {
private DefaultListableBeanFactory beanFactory;
@Before
public void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.registerScope("request", new RequestScope());
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("requestScopedProxyTests.xml", getClass()));
this.beanFactory.preInstantiateSingletons();
}
@Test
public void testGetFromScope() throws Exception {
String name = "requestScopedObject";
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
TestBean target = (TestBean) request.getAttribute("scopedTarget." + name);
assertEquals(TestBean.class, target.getClass());
assertEquals("scoped", target.getName());
assertSame(bean, this.beanFactory.getBean(name));
assertEquals(bean.toString(), target.toString());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetFromScopeThroughDynamicProxy() throws Exception {
String name = "requestScopedProxy";
ITestBean bean = (ITestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isJdkDynamicProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
TestBean target = (TestBean) request.getAttribute("scopedTarget." + name);
assertEquals(TestBean.class, target.getClass());
assertEquals("scoped", target.getName());
assertSame(bean, this.beanFactory.getBean(name));
assertEquals(bean.toString(), target.toString());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testDestructionAtRequestCompletion() throws Exception {
String name = "requestScopedDisposableObject";
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(DerivedTestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
assertTrue(((TestBean) request.getAttribute("scopedTarget." + name)).wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetFromFactoryBeanInScope() throws Exception {
String name = "requestScopedFactoryBean";
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertTrue(AopUtils.isCglibProxy(bean));
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals(DummyFactory.SINGLETON_NAME, bean.getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(DummyFactory.class, request.getAttribute("scopedTarget." + name).getClass());
assertSame(bean, this.beanFactory.getBean(name));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetInnerBeanFromScope() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
assertFalse(AopUtils.isAopProxy(bean));
assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));
String name = "scopedInnerBean";
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getSpouse().getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGetAnonymousInnerBeanFromScope() throws Exception {
TestBean bean = (TestBean) this.beanFactory.getBean("outerBean");
assertFalse(AopUtils.isAopProxy(bean));
assertTrue(AopUtils.isCglibProxy(bean.getSpouse()));
BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean");
BeanDefinitionHolder innerBeanDef =
(BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue();
String name = innerBeanDef.getBeanName();
MockHttpServletRequest request = new MockHttpServletRequest();
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute("scopedTarget." + name));
assertEquals("scoped", bean.getSpouse().getName());
assertNotNull(request.getAttribute("scopedTarget." + name));
assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass());
assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
}

View File

@@ -0,0 +1,173 @@
/*
* 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.request;
import java.io.Serializable;
import javax.servlet.http.HttpServletRequest;
import org.easymock.MockControl;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class ServletRequestAttributesTests {
private static final String KEY = "ThatThingThatThing";
private static final Serializable VALUE = new Serializable() {
};
@Test(expected = IllegalArgumentException.class)
public void ctorRejectsNullArg() throws Exception {
new ServletRequestAttributes(null);
}
@Test
public void updateAccessedAttributes() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertSame(VALUE, value);
attrs.requestCompleted();
}
@Test
public void setRequestScopedAttribute() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
Object value = request.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void setRequestScopedAttributeAfterCompletion() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
request.close();
try {
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
@Test
public void setSessionScopedAttribute() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void setSessionScopedAttributeAfterCompletion() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.requestCompleted();
request.close();
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void setGlobalSessionScopedAttribute() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void setGlobalSessionScopedAttributeAfterCompletion() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.requestCompleted();
request.close();
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void getSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getSession(false);
mockRequest.setReturnValue(null, 1);
mockRequest.replay();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertNull(value);
mockRequest.verify();
}
@Test
public void removeSessionScopedAttribute() throws Exception {
MockHttpSession session = new MockHttpSession();
session.setAttribute(KEY, VALUE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertNull(value);
}
@Test
public void removeSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getSession(false);
mockRequest.setReturnValue(null, 1);
mockRequest.replay();
ServletRequestAttributes attrs = new ServletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
mockRequest.verify();
}
}

View File

@@ -0,0 +1,166 @@
/*
* 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.request;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.multipart.MultipartRequest;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @since 26.07.2006
*/
public class ServletWebRequestTests {
private MockHttpServletRequest servletRequest;
private MockHttpServletResponse servletResponse;
private ServletWebRequest request;
@Before
public void setUp() {
servletRequest = new MockHttpServletRequest();
servletResponse = new MockHttpServletResponse();
request = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void parameters() {
servletRequest.addParameter("param1", "value1");
servletRequest.addParameter("param2", "value2");
servletRequest.addParameter("param2", "value2a");
assertEquals("value1", request.getParameter("param1"));
assertEquals(1, request.getParameterValues("param1").length);
assertEquals("value1", request.getParameterValues("param1")[0]);
assertEquals("value2", request.getParameter("param2"));
assertEquals(2, request.getParameterValues("param2").length);
assertEquals("value2", request.getParameterValues("param2")[0]);
assertEquals("value2a", request.getParameterValues("param2")[1]);
Map paramMap = request.getParameterMap();
assertEquals(2, paramMap.size());
assertEquals(1, ((String[]) paramMap.get("param1")).length);
assertEquals("value1", ((String[]) paramMap.get("param1"))[0]);
assertEquals(2, ((String[]) paramMap.get("param2")).length);
assertEquals("value2", ((String[]) paramMap.get("param2"))[0]);
assertEquals("value2a", ((String[]) paramMap.get("param2"))[1]);
}
@Test
public void locale() {
servletRequest.addPreferredLocale(Locale.UK);
assertEquals(Locale.UK, request.getLocale());
}
@Test
public void nativeRequest() {
assertSame(servletRequest, request.getNativeRequest());
assertSame(servletRequest, request.getNativeRequest(ServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(HttpServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(servletResponse, request.getNativeResponse());
assertSame(servletResponse, request.getNativeResponse(ServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(HttpServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
@Test
public void decoratedNativeRequest() {
HttpServletRequest decoratedRequest = new HttpServletRequestWrapper(servletRequest);
HttpServletResponse decoratedResponse = new HttpServletResponseWrapper(servletResponse);
ServletWebRequest request = new ServletWebRequest(decoratedRequest, decoratedResponse);
assertSame(decoratedRequest, request.getNativeRequest());
assertSame(decoratedRequest, request.getNativeRequest(ServletRequest.class));
assertSame(decoratedRequest, request.getNativeRequest(HttpServletRequest.class));
assertSame(servletRequest, request.getNativeRequest(MockHttpServletRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(decoratedResponse, request.getNativeResponse());
assertSame(decoratedResponse, request.getNativeResponse(ServletResponse.class));
assertSame(decoratedResponse, request.getNativeResponse(HttpServletResponse.class));
assertSame(servletResponse, request.getNativeResponse(MockHttpServletResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
@Test
public void checkNotModifiedTimeStamp() {
long currentTime = new Date().getTime();
servletRequest.setMethod("GET");
servletRequest.addHeader("If-Modified-Since", currentTime);
request.checkNotModified(currentTime);
assertEquals(304, servletResponse.getStatus());
}
@Test
public void checkModifiedTimeStamp() {
long currentTime = new Date().getTime();
long oneMinuteAgo = currentTime - (1000 * 60);
servletRequest.setMethod("GET");
servletRequest.addHeader("If-Modified-Since", oneMinuteAgo);
request.checkNotModified(currentTime);
assertEquals(200, servletResponse.getStatus());
assertEquals(""+currentTime, servletResponse.getHeader("Last-Modified"));
}
@Test
public void checkNotModifiedETag() {
String eTag = "\"Foo\"";
servletRequest.setMethod("GET");
servletRequest.addHeader("If-None-Match", eTag );
request.checkNotModified(eTag);
assertEquals(304, servletResponse.getStatus());
}
@Test
public void checkModifiedETag() {
String currentETag = "\"Foo\"";
String oldEtag = "Bar";
servletRequest.setMethod("GET");
servletRequest.addHeader("If-None-Match", oldEtag);
request.checkNotModified(currentETag);
assertEquals(200, servletResponse.getStatus());
assertEquals(currentETag, servletResponse.getHeader("ETag"));
}
}

View File

@@ -0,0 +1,196 @@
/*
* 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.request;
import java.io.Serializable;
import junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.util.SerializationTestUtils;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class SessionScopeTests extends TestCase {
private DefaultListableBeanFactory beanFactory;
protected void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.registerScope("session", new SessionScope());
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("sessionScopeTests.xml", getClass()));
}
public void testGetFromScope() throws Exception {
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "sessionScopedObject";
assertNull(session.getAttribute(name));
TestBean bean = (TestBean) this.beanFactory.getBean(name);
assertEquals(session.getAttribute(name), bean);
assertSame(bean, this.beanFactory.getBean(name));
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testDestructionAtSessionTermination() throws Exception {
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "sessionScopedDisposableObject";
assertNull(session.getAttribute(name));
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertEquals(session.getAttribute(name), bean);
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
session.invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
public void testDestructionWithSessionSerialization() throws Exception {
doTestDestructionWithSessionSerialization(false);
}
public void testDestructionWithSessionSerializationAndBeanPostProcessor() throws Exception {
this.beanFactory.addBeanPostProcessor(new CustomDestructionAwareBeanPostProcessor());
doTestDestructionWithSessionSerialization(false);
}
public void testDestructionWithSessionSerializationAndSerializableBeanPostProcessor() throws Exception {
this.beanFactory.addBeanPostProcessor(new CustomSerializableDestructionAwareBeanPostProcessor());
doTestDestructionWithSessionSerialization(true);
}
private void doTestDestructionWithSessionSerialization(boolean beanNameReset) throws Exception {
Serializable serializedState = null;
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "sessionScopedDisposableObject";
assertNull(session.getAttribute(name));
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertEquals(session.getAttribute(name), bean);
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
serializedState = session.serializeState();
assertFalse(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
serializedState = (Serializable) SerializationTestUtils.serializeAndDeserialize(serializedState);
session = new MockHttpSession();
session.deserializeState(serializedState);
request = new MockHttpServletRequest();
request.setSession(session);
requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
String name = "sessionScopedDisposableObject";
assertNotNull(session.getAttribute(name));
DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
assertEquals(session.getAttribute(name), bean);
assertSame(bean, this.beanFactory.getBean(name));
requestAttributes.requestCompleted();
session.invalidate();
assertTrue(bean.wasDestroyed());
if (beanNameReset) {
assertNull(bean.getBeanName());
}
else {
assertNotNull(bean.getBeanName());
}
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
private static class CustomDestructionAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
}
}
private static class CustomSerializableDestructionAwareBeanPostProcessor
implements DestructionAwareBeanPostProcessor, Serializable {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(null);
}
}
}
}

View File

@@ -0,0 +1,100 @@
/*
* 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.request;
import javax.servlet.ServletContextEvent;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextCleanupListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
/**
* @author Juergen Hoeller
*/
public class WebApplicationContextScopeTests {
private static final String NAME = "scoped";
private WebApplicationContext initApplicationContext(String scope) {
MockServletContext sc = new MockServletContext();
GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(DerivedTestBean.class);
bd.setScope(scope);
ac.registerBeanDefinition(NAME, bd);
ac.refresh();
return ac;
}
@Test
public void testRequestScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_REQUEST);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
requestAttributes.requestCompleted();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testSessionScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_SESSION);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getSession().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getSession().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
request.getSession().invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testApplicationScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION);
assertNull(ac.getServletContext().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, ac.getServletContext().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext()));
assertTrue(bean.wasDestroyed());
}
}

View File

@@ -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.web.context.support;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Chris Beams
*/
public class AnnotationConfigWebApplicationContextTests {
@Test
public void registerSingleClass() {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.refresh();
TestBean bean = ctx.getBean(TestBean.class);
assertNotNull(bean);
}
@Test
public void configLocationWithSingleClass() {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.setConfigLocation(Config.class.getName());
ctx.refresh();
TestBean bean = ctx.getBean(TestBean.class);
assertNotNull(bean);
}
@Configuration
static class Config {
@Bean
public TestBean myTestBean() {
return new TestBean();
}
}
static class NotConfigurationAnnotated { }
static class TestBean { }
}

View File

@@ -0,0 +1,47 @@
package org.springframework.web.context.support;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockServletContext;
/**
* @author Chris Beams
* @see org.springframework.core.io.ResourceTests
*/
public class ResourceTests {
@Test
public void testServletContextResource() throws IOException {
MockServletContext sc = new MockServletContext();
Resource resource = new ServletContextResource(sc, "org/springframework/core/io/Resource.class");
doTestResource(resource);
assertEquals(resource, new ServletContextResource(sc, "org/springframework/core/../core/io/./Resource.class"));
}
@Test
public void testServletContextResourceWithRelativePath() throws IOException {
MockServletContext sc = new MockServletContext();
Resource resource = new ServletContextResource(sc, "dir/");
Resource relative = resource.createRelative("subdir");
assertEquals(new ServletContextResource(sc, "dir/subdir"), relative);
}
private void doTestResource(Resource resource) throws IOException {
assertEquals("Resource.class", resource.getFilename());
assertTrue(resource.getURL().getFile().endsWith("Resource.class"));
Resource relative1 = resource.createRelative("ClassPathResource.class");
assertEquals("ClassPathResource.class", relative1.getFilename());
assertTrue(relative1.getURL().getFile().endsWith("ClassPathResource.class"));
assertTrue(relative1.exists());
Resource relative2 = resource.createRelative("support/ResourcePatternResolver.class");
assertEquals("ResourcePatternResolver.class", relative2.getFilename());
assertTrue(relative2.getURL().getFile().endsWith("ResourcePatternResolver.class"));
assertTrue(relative2.exists());
}
}

View File

@@ -0,0 +1,187 @@
/*
* 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.support;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import javax.servlet.ServletContextEvent;
import org.junit.Test;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ContextLoaderListener;
/**
* Tests the interaction between a WebApplicationContext and ContextLoaderListener with
* regard to config location precedence, overriding and defaulting in programmatic
* configuration use cases, e.g. with Spring 3.1's WebApplicationInitializer.
*
* @author Chris Beams
* @since 3.1
* @see org.springframework.web.context.ContextLoaderTests
*/
public class Spr8510Tests {
@Test
public void abstractRefreshableWAC_respectsProgrammaticConfigLocations() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("programmatic.xml");
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
} catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/programmatic.xml]"));
}
}
/**
* If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
* then it should take precedence. This is generally not a recommended practice, but
* when it does happen, the init-param should be considered more specific than the
* programmatic configuration, given that it still quite possibly externalized in
* hybrid web.xml + WebApplicationInitializer cases.
*/
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("programmatic.xml");
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
} catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
}
/**
* If setConfigLocation has not been called explicitly against the application context,
* then fall back to the ContextLoaderListener init-param if present.
*/
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
} catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
}
/**
* Ensure that any custom default locations are still respected.
*/
@Test
public void customAbstractRefreshableWAC_fallsBackToInitParam() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext() {
@Override
protected String[] getDefaultConfigLocations() {
return new String[] { "/WEB-INF/custom.xml" };
}
};
//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
} catch (Throwable t) {
// assert that an attempt was made to load the correct XML
System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
}
/**
* If context config locations have been specified neither against the application
* context nor the context loader listener, then fall back to default values.
*/
@Test
public void abstractRefreshableWAC_fallsBackToConventionBasedNaming() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
// no init-param set
//sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
} catch (Throwable t) {
// assert that an attempt was made to load the correct XML
System.out.println(t.getMessage());
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/WEB-INF/applicationContext.xml]"));
}
}
/**
* Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
*/
@Test
public void genericWAC() {
GenericWebApplicationContext ctx = new GenericWebApplicationContext();
ContextLoaderListener cll = new ContextLoaderListener(ctx);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
scanner.scan("bogus.pkg");
cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
/**
* Ensure that ContextLoaderListener and AnnotationConfigApplicationContext interact nicely.
*/
@Test
public void annotationConfigWAC() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.scan("does.not.matter");
ContextLoaderListener cll = new ContextLoaderListener(ctx);
cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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.support;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class SpringBeanAutowiringSupportTests {
@Test
public void testProcessInjectionBasedOnServletContext() {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "tb");
wac.registerSingleton("testBean", TestBean.class, pvs);
wac.setServletContext(sc);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
InjectionTarget target = new InjectionTarget();
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
assertTrue(target.testBean instanceof TestBean);
assertEquals("tb", target.name);
}
public static class InjectionTarget {
@Autowired
public ITestBean testBean;
@Value("#{testBean.name}")
public String name;
}
}

View File

@@ -0,0 +1,50 @@
/*
* 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.support;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
/**
* Unit tests for {@link StandardServletEnvironment}.
*
* @author Chris Beams
* @since 3.1
*/
public class StandardServletEnvironmentTests {
@Test
public void propertySourceOrder() {
ConfigurableEnvironment env = new StandardServletEnvironment();
MutablePropertySources sources = env.getPropertySources();
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME)), equalTo(0));
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)), equalTo(1));
assertThat(sources.precedenceOf(PropertySource.named(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)), equalTo(2));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(3));
assertThat(sources.precedenceOf(PropertySource.named(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(4));
assertThat(sources.size(), is(5));
}
}

View File

@@ -0,0 +1,199 @@
/*
* 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.filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class CharacterEncodingFilterTests extends TestCase {
private static final String FILTER_NAME = "boot";
private static final String ENCODING = "UTF-8";
public void testForceAlwaysSetsEncoding() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockControl mockResponse = MockControl.createControl(HttpServletResponse.class);
HttpServletResponse response = (HttpServletResponse) mockResponse.getMock();
response.setCharacterEncoding(ENCODING);
mockResponse.setVoidCallable();
mockResponse.replay();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(true);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockResponse.verify();
mockFilter.verify();
}
public void testEncodingIfEmptyAndNotForced() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(false);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testDoesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(ENCODING);
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testWithBeanInitialization() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.setBeanName(FILTER_NAME);
filter.setServletContext(new MockServletContext());
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testWithIncompleteInitialization() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2004, 2005 Acegi Technology Pty Limited
* Copyright 2006-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.filter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.junit.Test;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
/**
* @author Dave Syer
*/
public class CompositeFilterTests {
@Test
public void testCompositeFilter() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
MockFilter targetFilter = new MockFilter();
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
CompositeFilter filterProxy = new CompositeFilter();
filterProxy.setFilters(Arrays.asList(targetFilter));
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNotNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public static class MockFilter implements Filter {
public FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setAttribute("called", Boolean.TRUE);
}
public void destroy() {
this.filterConfig = null;
}
}
}

View File

@@ -0,0 +1,288 @@
/*
* Copyright 2004, 2005 Acegi Technology Pty Limited
* Copyright 2006-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.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Juergen Hoeller
* @author Chris Beams
* @since 08.05.2005
*/
public class DelegatingFilterProxyTests {
@Test
public void testDelegatingFilterProxy() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyAndCustomContextAttribute() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute("CUSTOM_ATTR", wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
proxyConfig.addInitParameter("contextAttribute", "CUSTOM_ATTR");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyWithFilterDelegateInstance() throws ServletException, IOException {
MockFilter targetFilter = new MockFilter();
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(targetFilter);
filterProxy.init(new MockFilterConfig(new MockServletContext()));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyWithTargetBeanName() throws ServletException, IOException {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter");
filterProxy.init(new MockFilterConfig(sc));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyWithTargetBeanNameAndNotYetRefreshedApplicationContext() throws ServletException, IOException {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
// wac.refresh();
// note that the context is not set as the ROOT attribute in the ServletContext!
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter", wac);
filterProxy.init(new MockFilterConfig(sc));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test(expected=IllegalStateException.class)
public void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext() throws ServletException, IOException {
MockServletContext sc = new MockServletContext();
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter", null);
filterProxy.init(new MockFilterConfig(sc));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null); // throws
}
@Test
public void testDelegatingFilterProxyWithFilterName() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc, "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyWithLazyContextStartup() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
@Test
public void testDelegatingFilterProxyWithTargetFilterLifecycle() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
proxyConfig.addInitParameter("targetFilterLifecycle", "true");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
assertEquals(proxyConfig, targetFilter.filterConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertEquals(proxyConfig, targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public static class MockFilter implements Filter {
public FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setAttribute("called", Boolean.TRUE);
}
public void destroy() {
this.filterConfig = null;
}
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright ${YEAR} 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.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/** @author Arjen Poutsma */
public class HiddenHttpMethodFilterTest {
private HiddenHttpMethodFilter filter;
@Before
public void createFilter() {
filter = new HiddenHttpMethodFilter();
}
@Test
public void filterWithParameter() throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
request.addParameter("_method", "delete");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid method", "DELETE", ((HttpServletRequest) filterRequest).getMethod());
}
};
filter.doFilter(request, response, filterChain);
}
@Test
public void filterWithNoParameter() throws IOException, ServletException {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid method", "POST", ((HttpServletRequest) filterRequest).getMethod());
}
};
filter.doFilter(request, response, filterChain);
}
}

View File

@@ -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.filter;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Test fixture for {@link HttpPutFormContentFilter}.
*
* @author Rossen Stoyanchev
*/
public class HttpPutFormContentFilterTests {
private HttpPutFormContentFilter filter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain filterChain;
@Before
public void setup() {
filter = new HttpPutFormContentFilter();
request = new MockHttpServletRequest("PUT", "/");
request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
request.setContentType("application/x-www-form-urlencoded; charset=ISO-8859-1");
response = new MockHttpServletResponse();
filterChain = new MockFilterChain();
}
@Test
public void wrapPutOnly() throws Exception {
request.setContent("".getBytes("ISO-8859-1"));
String[] methods = new String[] {"GET", "POST", "DELETE", "HEAD", "OPTIONS", "TRACE"};
for (String method : methods) {
request.setMethod(method);
filterChain = new MockFilterChain();
filter.doFilter(request, response, filterChain);
assertSame("Should not wrap for HTTP method " + method, request, filterChain.getRequest());
}
}
@Test
public void wrapFormEncodedOnly() throws Exception {
request.setContent("".getBytes("ISO-8859-1"));
String[] contentTypes = new String[] {"text/plain", "multipart/form-data"};
for (String contentType : contentTypes) {
request.setContentType(contentType);
filterChain = new MockFilterChain();
filter.doFilter(request, response, filterChain);
assertSame("Should not wrap for content type " + contentType, request, filterChain.getRequest());
}
}
@Test
public void getParameter() throws Exception {
request.setContent("name=value".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
assertEquals("value", filterChain.getRequest().getParameter("name"));
}
@Test
public void getParameterFromQueryString() throws Exception {
request.addParameter("name", "value1");
request.setContent("name=value2".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertEquals("Query string parameters should be listed ahead of form parameters",
"value1", filterChain.getRequest().getParameter("name"));
}
@Test
public void getParameterNullValue() throws Exception {
request.setContent("name=value".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertNull(filterChain.getRequest().getParameter("noSuchParam"));
}
@Test
public void getParameterNames() throws Exception {
request.addParameter("name1", "value1");
request.addParameter("name2", "value2");
request.setContent("name1=value1&name3=value3&name4=value4".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
List<String> names = Collections.list(filterChain.getRequest().getParameterNames());
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertEquals(Arrays.asList("name1", "name2", "name3", "name4"), names);
}
@Test
public void getParameterValues() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("name=value3&name=value4".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("name");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"value1", "value2", "value3", "value4"}, values);
}
@Test
public void getParameterValuesFromQueryString() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("name");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"value1", "value2"}, values);
}
@Test
public void getParameterValuesFromFormContent() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("anotherName");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertArrayEquals(new String[]{"anotherValue"}, values);
}
@Test
public void getParameterValuesInvalidName() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("anotherName=anotherValue".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
String[] values = filterChain.getRequest().getParameterValues("noSuchParameter");
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertNull(values);
}
@Test
public void getParameterMap() throws Exception {
request.addParameter("name", "value1");
request.addParameter("name", "value2");
request.setContent("name=value3&name4=value4".getBytes("ISO-8859-1"));
filter.doFilter(request, response, filterChain);
Map<String, String[]> parameters = filterChain.getRequest().getParameterMap();
assertNotSame("Request not wrapped", request, filterChain.getRequest());
assertEquals(2, parameters.size());
assertArrayEquals(new String[] {"value1", "value2", "value3"}, parameters.get("name"));
assertArrayEquals(new String[] {"value4"}, parameters.get("name4"));
}
}

View File

@@ -0,0 +1,99 @@
/*
* 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.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class RequestContextFilterTests extends TestCase {
public void testHappyPath() throws Exception {
testFilterInvocation(null);
}
public void testWithException() throws Exception {
testFilterInvocation(new ServletException());
}
public void testFilterInvocation(final ServletException sex) throws Exception {
final MockHttpServletRequest req = new MockHttpServletRequest();
req.setAttribute("myAttr", "myValue");
final MockHttpServletResponse resp = new MockHttpServletResponse();
// Expect one invocation by the filter being tested
class DummyFilterChain implements FilterChain {
public int invocations = 0;
public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
++invocations;
if (invocations == 1) {
assertSame("myValue",
RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST));
if (sex != null) {
throw sex;
}
}
else {
throw new IllegalStateException("Too many invocations");
}
}
};
DummyFilterChain fc = new DummyFilterChain();
MockFilterConfig mfc = new MockFilterConfig(new MockServletContext(), "foo");
RequestContextFilter rbf = new RequestContextFilter();
rbf.init(mfc);
try {
rbf.doFilter(req, resp, fc);
if (sex != null) {
fail();
}
}
catch (ServletException ex) {
assertNotNull(sex);
}
try {
RequestContextHolder.currentRequestAttributes();
fail();
}
catch (IllegalStateException ex) {
// Ok
}
assertEquals(1, fc.invocations);
}
}

View File

@@ -0,0 +1,189 @@
/*
* 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.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.FileCopyUtils;
/**
* Test for {@link AbstractRequestLoggingFilter} and sub classes.
*
* @author Arjen Poutsma
*/
public class RequestLoggingFilterTests {
private MyRequestLoggingFilter filter;
@Before
public void createFilter() throws Exception {
filter = new MyRequestLoggingFilter();
}
@Test
public void uri() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setQueryString("booking=42");
FilterChain filterChain = new NoopFilterChain();
filter.doFilter(request, response, filterChain);
assertNotNull(filter.beforeRequestMessage);
assertTrue(filter.beforeRequestMessage.indexOf("uri=/hotel") != -1);
assertFalse(filter.beforeRequestMessage.indexOf("booking=42") != -1);
assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("uri=/hotel") != -1);
assertFalse(filter.afterRequestMessage.indexOf("booking=42") != -1);
}
@Test
public void queryString() throws Exception {
filter.setIncludeQueryString(true);
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setQueryString("booking=42");
FilterChain filterChain = new NoopFilterChain();
filter.doFilter(request, response, filterChain);
assertNotNull(filter.beforeRequestMessage);
assertTrue(filter.beforeRequestMessage.indexOf("uri=/hotels?booking=42") != -1);
assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("uri=/hotels?booking=42") != -1);
}
@Test
public void payloadInputStream() throws Exception {
filter.setIncludePayload(true);
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
final byte[] requestBody = "Hello World".getBytes("UTF-8");
request.setContent(requestBody);
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
assertArrayEquals(requestBody, buf);
}
};
filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("Hello World") != -1);
}
@Test
public void payloadReader() throws Exception {
filter.setIncludePayload(true);
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
final String requestBody = "Hello World";
request.setContent(requestBody.getBytes("UTF-8"));
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
String buf = FileCopyUtils.copyToString(filterRequest.getReader());
assertEquals(requestBody, buf);
}
};
filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf(requestBody) != -1);
}
@Test
public void payloadMaxLength() throws Exception {
filter.setIncludePayload(true);
filter.setMaxPayloadLength(3);
final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
final byte[] requestBody = "Hello World".getBytes("UTF-8");
request.setContent(requestBody);
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
assertArrayEquals(requestBody, buf);
}
};
filter.doFilter(request, response, filterChain);
assertNotNull(filter.afterRequestMessage);
assertTrue(filter.afterRequestMessage.indexOf("Hel") != -1);
assertFalse(filter.afterRequestMessage.indexOf("Hello World") != -1);
}
private static class MyRequestLoggingFilter extends AbstractRequestLoggingFilter {
private String beforeRequestMessage;
private String afterRequestMessage;
@Override
protected void beforeRequest(HttpServletRequest request, String message) {
this.beforeRequestMessage = message;
}
@Override
protected void afterRequest(HttpServletRequest request, String message) {
this.afterRequestMessage = message;
}
}
private static class NoopFilterChain implements FilterChain {
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
}
}
}

View File

@@ -0,0 +1,129 @@
/*
* 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.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.FileCopyUtils;
import static org.junit.Assert.*;
public class ShallowEtagHeaderFilterTests {
private ShallowEtagHeaderFilter filter;
@Before
public void createFilter() throws Exception {
filter = new ShallowEtagHeaderFilter();
}
@Test
public void isEligibleForEtag() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
assertTrue(filter.isEligibleForEtag(request, response, 200, new byte[0]));
assertFalse(filter.isEligibleForEtag(request, response, 300, new byte[0]));
}
@Test
public void filterNoMatch() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
final byte[] responseBody = "Hello World".getBytes("UTF-8");
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid request passed", request, filterRequest);
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
}
};
filter.doFilter(request, response, filterChain);
assertEquals("Invalid status", 200, response.getStatus());
assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
@Test
public void filterMatch() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
request.addHeader("If-None-Match", etag);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid request passed", request, filterRequest);
byte[] responseBody = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
filterResponse.setContentLength(responseBody.length);
}
};
filter.doFilter(request, response, filterChain);
assertEquals("Invalid status", 304, response.getStatus());
assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
@Test
public void filterWriter() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
request.addHeader("If-None-Match", etag);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid request passed", request, filterRequest);
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
String responseBody = "Hello World";
FileCopyUtils.copy(responseBody, filterResponse.getWriter());
}
};
filter.doFilter(request, response, filterChain);
assertEquals("Invalid status", 304, response.getStatus());
assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
}

View File

@@ -0,0 +1,104 @@
/*
* 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.jsf;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import junit.framework.TestCase;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
/**
* @author Colin Sampaleanu
* @author Juergen Hoeller
*/
public class DelegatingNavigationHandlerTests extends TestCase {
private MockFacesContext facesContext;
private StaticListableBeanFactory beanFactory;
private TestNavigationHandler origNavHandler;
private DelegatingNavigationHandlerProxy delNavHandler;
@Override
protected void setUp() {
facesContext = new MockFacesContext();
beanFactory = new StaticListableBeanFactory();
origNavHandler = new TestNavigationHandler();
delNavHandler = new DelegatingNavigationHandlerProxy(origNavHandler) {
@Override
protected BeanFactory getBeanFactory(FacesContext facesContext) {
return beanFactory;
}
};
}
public void testHandleNavigationWithoutDecoration() {
TestNavigationHandler targetHandler = new TestNavigationHandler();
beanFactory.addBean("jsfNavigationHandler", targetHandler);
delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId");
assertEquals("fromAction", targetHandler.lastFromAction);
assertEquals("myViewId", targetHandler.lastOutcome);
}
public void testHandleNavigationWithDecoration() {
TestDecoratingNavigationHandler targetHandler = new TestDecoratingNavigationHandler();
beanFactory.addBean("jsfNavigationHandler", targetHandler);
delNavHandler.handleNavigation(facesContext, "fromAction", "myViewId");
assertEquals("fromAction", targetHandler.lastFromAction);
assertEquals("myViewId", targetHandler.lastOutcome);
// Original handler must have been invoked as well...
assertEquals("fromAction", origNavHandler.lastFromAction);
assertEquals("myViewId", origNavHandler.lastOutcome);
}
public static class TestNavigationHandler extends NavigationHandler {
private String lastFromAction;
private String lastOutcome;
@Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
lastFromAction = fromAction;
lastOutcome = outcome;
}
}
public static class TestDecoratingNavigationHandler extends DecoratingNavigationHandler {
private String lastFromAction;
private String lastOutcome;
@Override
public void handleNavigation(
FacesContext facesContext, String fromAction, String outcome, NavigationHandler originalNavigationHandler) {
lastFromAction = fromAction;
lastOutcome = outcome;
if (originalNavigationHandler != null) {
originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome);
}
}
}
}

View File

@@ -0,0 +1,101 @@
/*
* 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.jsf;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import junit.framework.TestCase;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.StaticListableBeanFactory;
/**
* @author Colin Sampaleanu
* @author Juergen Hoeller
*/
public class DelegatingPhaseListenerTests extends TestCase {
private MockFacesContext facesContext;
private StaticListableBeanFactory beanFactory;
private DelegatingPhaseListenerMulticaster delPhaseListener;
protected void setUp() {
facesContext = new MockFacesContext();
beanFactory = new StaticListableBeanFactory();
delPhaseListener = new DelegatingPhaseListenerMulticaster() {
protected ListableBeanFactory getBeanFactory(FacesContext facesContext) {
return beanFactory;
}
};
}
public void testBeforeAndAfterPhaseWithSingleTarget() {
TestListener target = new TestListener();
beanFactory.addBean("testListener", target);
assertEquals(delPhaseListener.getPhaseId(), PhaseId.ANY_PHASE);
PhaseEvent event = new PhaseEvent(facesContext, PhaseId.INVOKE_APPLICATION, new MockLifecycle());
delPhaseListener.beforePhase(event);
assertTrue(target.beforeCalled);
delPhaseListener.afterPhase(event);
assertTrue(target.afterCalled);
}
public void testBeforeAndAfterPhaseWithMultipleTargets() {
TestListener target1 = new TestListener();
TestListener target2 = new TestListener();
beanFactory.addBean("testListener1", target1);
beanFactory.addBean("testListener2", target2);
assertEquals(delPhaseListener.getPhaseId(), PhaseId.ANY_PHASE);
PhaseEvent event = new PhaseEvent(facesContext, PhaseId.INVOKE_APPLICATION, new MockLifecycle());
delPhaseListener.beforePhase(event);
assertTrue(target1.beforeCalled);
assertTrue(target2.beforeCalled);
delPhaseListener.afterPhase(event);
assertTrue(target1.afterCalled);
assertTrue(target2.afterCalled);
}
public static class TestListener implements PhaseListener {
boolean beforeCalled = false;
boolean afterCalled = false;
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
public void beforePhase(PhaseEvent arg0) {
beforeCalled = true;
}
public void afterPhase(PhaseEvent arg0) {
afterCalled = true;
}
}
}

View File

@@ -0,0 +1,83 @@
/*
* 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.jsf;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.VariableResolver;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Juergen Hoeller
* @since 02.08.2004
*/
public class DelegatingVariableResolverTests extends TestCase {
public void testDelegatingVariableResolver() {
final StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.registerSingleton("bean1", TestBean.class, null);
wac.registerSingleton("var1", TestBean.class, null);
wac.refresh();
TestBean bean1 = (TestBean) wac.getBean("bean1");
// We need to override the getWebApplicationContext method here:
// FacesContext and ExternalContext are hard to mock.
DelegatingVariableResolver resolver = new DelegatingVariableResolver(new OriginalVariableResolver()) {
protected WebApplicationContext getWebApplicationContext(FacesContext facesContext) {
return wac;
}
};
assertEquals(bean1, resolver.resolveVariable(null, "bean1"));
assertEquals("val1", resolver.resolveVariable(null, "var1"));
}
public void testSpringBeanVariableResolver() {
final StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.registerSingleton("bean1", TestBean.class, null);
wac.registerSingleton("var1", TestBean.class, null);
wac.refresh();
TestBean bean1 = (TestBean) wac.getBean("bean1");
TestBean var1 = (TestBean) wac.getBean("var1");
// We need to override the getWebApplicationContext method here:
// FacesContext and ExternalContext are hard to mock.
SpringBeanVariableResolver resolver = new SpringBeanVariableResolver(new OriginalVariableResolver()) {
protected WebApplicationContext getWebApplicationContext(FacesContext facesContext) {
return wac;
}
};
assertEquals(bean1, resolver.resolveVariable(null, "bean1"));
assertEquals(var1, resolver.resolveVariable(null, "var1"));
}
private static class OriginalVariableResolver extends VariableResolver {
public Object resolveVariable(FacesContext facesContext, String name) throws EvaluationException {
if ("var1".equals(name)) {
return "val1";
}
return null;
}
}
}

Some files were not shown because too many files have changed in this diff Show More